'use strict';var sy={TAB:0,Ri:1,gm:2},ty=function(a){Rb("MediaRouter.CastStreaming.Start.Success",a,sy)};var uy=tb("mr.mirror.cast.LogUploader"),wy=function(a,b,c){vy("raw_events.log.gz",a,b,c);return b?"https://crash.corp.google.com/samples?reportid=&q="+encodeURIComponent("UserComments='"+b+"'"):""},vy=function(a,b,c,d){if(0==b.size)uy.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);Zv("https://clients2.google.com/cr/report",function(a){a=a.target;
var b=null;iw(a)?(b=jw(a),uy.info("Upload to Crash succeeded: "+b)):uy.info("Upload to Crash failed. HTTP status: "+a.Ia());d&&d(b)},"POST",e,void 0,3E4)}};var xy=function(){this.b=0;qj(this)},zy=function(){yy||(yy=new xy);return yy},Ay=function(){var a=zy(),b={fraction:.01,autoSubmitTimeLimitMillis:6048E5},c=b.autoSubmitTimeLimitMillis,d=Date.now();return a.b&&c&&d-a.b<c?!1:Math.random()<b.fraction};xy.prototype.ua=function(){return"mirror.cast.LogUtils"};xy.prototype.Ta=function(){return[void 0,{lastAutoSubmitMillis:this.b}]};xy.prototype.Ya=function(){var a=oj(this);this.b=a&&a.lastAutoSubmitMillis||0};var yy=null;tb("mr.mirror.cast.LogUtils");var By={su:"OFFER",Iq:"ANSWER",Pu:"PRESENTATION",ws:"GET_STATUS",Kv:"STATUS_RESPONSE",vs:"GET_CAPABILITIES",fr:"CAPABILITIES_RESPONSE",qv:"RPC"};var Cy=function(){this.capabilities=this.status=this.b=this.error=this.rpc=this.result=this.type=this.f=this.sessionId=null},Fy=function(a){try{if("string"!==typeof a)throw SyntaxError("Cannot parse non-string as JSON");var b;Dy(JSON.parse(a),function(a){b=Ey(a)},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);},Ey=function(a){var b=new Cy;null!=a.sessionId&&(b.sessionId=String(a.sessionId));Gy(a.seqNum,function(a){b.f=a},function(){throw Error('"seqNum" must be a number');});if("type"in a){for(var c=String(a.type).toUpperCase(),d=ma(Object.keys(By)),e=d.next();!e.done;e=d.next())if(By[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(xa(atob(a.rpc))).map(function(a){return a.charCodeAt(0)}))}Dy(a.error,function(a){b.error=Hy(a)},function(){throw Error('"error" must be an Object');});Dy(a.answer,function(a){b.b=Iy(a)},function(){throw Error('"answer" must be an Object');});Dy(a.status,function(a){b.status=Jy(a)},function(){throw Error('"status" must be an Object');
});Dy(a.capabilities,function(a){b.capabilities=Ky(a)},function(){throw Error('"capabilities" must be an Object');});return b},Dy=function(a,b,c){void 0!==a&&(a instanceof Object?b(a):c())},Gy=function(a,b,c){void 0!==a&&("number"!==typeof a?c():b(a))},Ly=function(a,b,c){void 0!==a&&(a instanceof Array&&a.every(function(a){return"number"===typeof a})?b(a):c())},My=function(a,b,c){void 0!==a&&(a instanceof Array?b(a.map(function(a){return String(a)})):c())},Ny=function(){this.j=null;this.b=[];this.f=
[];this.h=this.g=this.s=null},Iy=function(a){var b=new Ny;Gy(a.udpPort,function(a){b.j=a},function(){throw Error('"answer.udpPort" must be a number');});Ly(a.sendIndexes,function(a){b.b=a},function(){throw Error('"answer.sendIndexes" must be an array of numbers');});Ly(a.ssrcs,function(a){b.f=a},function(){throw Error('"answer.ssrcs" must be an array of numbers');});"IV"in a&&(b.s=String(a.IV));"receiverGetStatus"in a&&(b.g="true"==String(a.receiverGetStatus).toLowerCase());"castMode"in a&&(b.h=String(a.castMode));
return b},Oy=function(){this.details=this.description=this.code=null},Hy=function(a){var b=new Oy;Gy(a.code,function(a){b.code=a},function(){throw Error('"error.code" must be a number');});"description"in a&&(b.description=String(a.description));Dy(a.details,function(a){b.details=a},function(){throw Error('"error.details" must be an Object');});return b},Py=function(){this.f=this.b=null},Jy=function(a){var b=new Py;Gy(a.wifiSnr,function(a){b.b=a},function(){throw Error('"status.wifiSnr" must be a number');
});Ly(a.wifiSpeed,function(a){b.f=a},function(){throw Error('"status.wifiSpeed" must be an array of numbers');});return b},Qy=function(){this.f=this.b=null},Ky=function(a){var b=new Qy;My(a.mediaCaps,function(a){b.b=a},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.f=a.map(function(a){var b;Dy(a,function(a){b=Ry(a)},function(){throw Error('"capabilities.keySystems" entries must be *Objects');
});return b})}return b},Sy=function(){this.h=this.m=this.s=this.j=this.u=this.b=this.o=this.f=this.initDataTypes=this.g=null},Ry=function(a){var b=new Sy;"keySystemName"in a&&(b.g=String(a.keySystemName));My(a.initDataTypes,function(a){b.initDataTypes=a},function(){throw Error('"capabilities.initDataTypes" must be an array');});My(a.codecs,function(a){b.f=a},function(){throw Error('"capabilities.codecs" must be an array');});My(a.secureCodecs,function(a){b.o=a},function(){throw Error('"capabilities.secureCodecs" must be an array');
});My(a.audioRobustness,function(a){b.b=a},function(){throw Error('"capabilities.audioRobustness" must be an array');});My(a.videoRobustness,function(a){b.u=a},function(){throw Error('"capabilities.videoRobustness" must be an array');});"persistentLicenseSessionSupport"in a&&(b.j=String(a.persistentLicenseSessionSupport));"persistentReleaseMessageSessionSupport"in a&&(b.s=String(a.persistentReleaseMessageSessionSupport));"persistentStateSupport"in a&&(b.m=String(a.persistentStateSupport));"distinctiveIdentifierSupport"in
a&&(b.h=String(a.distinctiveIdentifierSupport));return b};var Ty=function(a){this.l=tb("mr.mirror.cast.MessageDispatcher");this.g=a;this.b=null;this.f=new Map;this.h=0},Uy=function(a,b,c){if(a.f.has(b))throw Error("Attempt to multiple-subscribe to the same response type: "+b);a.f.set(b,c);a.h=0;Ab(a.l,"Added subscriber for "+b+"-type messages.");a.b||(a.b=rx(a.g),a.b.onMessage=a.j.bind(a))},Vy=function(a,b){a.f.delete(b)&&Ab(a.l,function(){return"Removed subscriber of "+b+"-type messages."});0==a.f.size&&a.b&&(a.b.Ra(),a.b=null)};
Ty.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 Wy=function(a,b,c,d,e){var f=null,h=function(){Vy(a,c);null!=f&&(clearTimeout(f),f=null)};try{Uy(a,c,function(a){e(a)&&h()})}catch(k){e(null,k);return}f=setTimeout(function(){h();e(null,Error("timeout"))},d);a.sendMessage(b).catch(function(a){h();e(null,a)})};
Ty.prototype.j=function(a){if(a&&"string"===typeof a.namespace_&&a.namespace_.startsWith("urn:x-cast:com.google.cast.")){do{var b=void 0;try{b=Fy(a.data)}catch(d){b=d.message;break}if(b.type){var c=this.f.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.h?v(this.l,b):Ab(this.l,b);++this.h}};var Xy=function(){this.b=Promise.resolve(1)},Zy=function(a,b,c){return Yy(a,function(a){return a==b},c)},$y=function(a,b){var c=[3,4];return Yy(a,function(a){return-1!=c.indexOf(a)},b)},az=function(a,b){a.b=a.b.catch(function(){return 1});return Yy(a,function(){return!0},b)},Yy=function(a,b,c){var d,e,f=new Promise(function(a,b){d=a;e=b});a.b=a.b.then(function(a){if(!b(a))return e(Error("Operation requires a different starting checkpoint than "+a)),Promise.resolve(a);var f=new bz(a);try{var h=c(f)}catch(u){h=
Promise.reject(u)}return h.then(function(a){return d(a)},function(a){return e(a)}).then(function(){if(null===f.b)throw Error("A prior operation that started at "+(a+" did not complete."));return f.b})},function(a){e(a);throw a;});return f},bz=function(a){this.f=a;this.b=null},cz=function(a,b){a.b="number"===typeof b?b:a.f};var dz=chrome.cast.streaming,fz=function(a,b,c,d,e){this.D=a.sessionId;this.u=a.Vf;this.ka=a.je;this.h=b;this.L=c;this.C=d;this.K=ez(e,"onAnswer",this.u);this.M=ez(e,"onSessionStop",this.u);this.l=tb("mr.mirror.cast.StreamingLaunchWorkflow");this.A=new Xy;this.m=this.B=this.o=this.f=this.b=this.s=this.j=this.g=null};
fz.prototype.start=function(a,b,c){var d=this;if(!a&&!b)return Promise.reject(Error("No tracks to stream"));var e=a instanceof gz,f=b instanceof gz;(e&&b&&!f||f&&a&&!e)&&Xb("Mixing remoting and non-remoting tracks");return Zy(this.A,1,function(e){d.g=a;d.j=b;d.s=c;d.l.info(function(){return"Launching streaming for "+hz(d)+" "+("to a "+d.ka+".")});return iz(d).then(d.F.bind(d)).then(function(a){return jz(d,a).then(function(b){d.K();var c=kz(d,b,a);d.b=lz(d,d.b,c);d.f=lz(d,d.f,c);if(!d.b&&!d.f)throw Error("Receiver did not select any offers from: "+
JSON.stringify(a));d.B=!!b.g;d.m=function(a,b){a==d.b?d.s.de("Audio stream (id="+a+") error: "+b):a==d.f&&d.s.de("Video stream (id="+a+") error: "+b)};dz.rtpStream.onError.addListener(d.m);return mz(d,b,c)})}).then(function(){d.l.info(function(){return"Launched streaming for "+hz(d)});d.s.tf(d);cz(e,2);return{xn:d.b,jq:d.f}})})};
fz.prototype.stop=function(){var a=this;return az(this.A,function(b){if(!a.g&&!a.j)return cz(b,1),Promise.resolve();a.l.info(function(){return"Stopping streaming for "+hz(a)+"."});a.m&&(dz.rtpStream.onError.removeListener(a.m),a.m=null);if(a.s){var c=a.s.ag();a.s=null}else c=Promise.resolve();return c.then(function(){a.b&&(dz.rtpStream.stop(a.b),dz.rtpStream.destroy(a.b),a.b=null);a.f&&(dz.rtpStream.stop(a.f),dz.rtpStream.destroy(a.f),a.f=null);a.o&&(dz.udpTransport.destroy(a.o),a.o=null);a.M();a.l.info(function(){return"Stopped streaming for "+
hz(a)+"."});a.g=null;a.j=null;cz(b,1)})})};
var nz=function(a,b){var c=JSON.stringify(b);return Promise.all([a.b&&new Promise(function(b){return dz.rtpStream.getRawEvents(a.b,c,b)}),a.f&&new Promise(function(b){return dz.rtpStream.getRawEvents(a.f,c,b)})]).catch(function(b){a.l.error("Unexpected error when calling getRawEvents()",b);return[]}).then(function(a){return new Blob(a.filter(function(a){return!!a}),{type:"application/gzip"})})},oz=function(a){return Promise.all([a.b&&new Promise(function(b){return dz.rtpStream.getStats(a.b,b)}),a.f&&
new Promise(function(b){return dz.rtpStream.getStats(a.f,b)})]).catch(function(b){a.l.error("Unexpected error when calling getStats()",b);return[]}).then(function(a){return Object.assign.apply(Object,[{}].concat(xa(a.filter(function(a){return!!a}))))})},hz=function(a){if(a.g&&a.j)var b="audio+video ";else if(a.g)b="audio-only ";else if(a.j)b="video-only ";else return"stopped";return a.g instanceof gz||a.j instanceof gz?b+"remoting":b+"streaming"},iz=function(a){return new Promise(function(b){var c=
function(c,e,f){c&&!a.g&&(dz.rtpStream.destroy(c),c=null);e&&!a.j&&(dz.rtpStream.destroy(e),e=null);a.l.info(function(){return"Created Cast Streaming session: audioStreamId="+c+", videoStreamId="+e+"."});a.b=c;a.f=e;a.o=f;b()};a.g instanceof gz||a.j instanceof gz?dz.session.create(null,null,c):dz.session.create(a.g,a.j,c)})};
fz.prototype.F=function(){for(var a=oh(),b=oh(),c=[],d=ma([this.b,this.f]),e=d.next();!e.done;e=d.next())if(e=e.value)for(var f=e==this.b,h=f?127:96,k=f?Math.floor(499999*Math.random())+1:Math.floor(499999*Math.random())+500001,n=f?48E3:9E4,u=ma(dz.rtpStream.getSupportedParams(e)),z=u.next();!z.done;z=u.next())z=z.value,z.payload.payloadType=h,z.payload.maxLatency=this.h.maxLatencyMillis,z.payload.minLatency=this.h.minLatencyMillis,z.payload.animatedLatency=this.h.animatedLatencyMillis,z.payload.ssrc=
k,z.payload.clockRate=n,z.payload.aesKey=a,z.payload.aesIvMask=b,f?(z.payload.channels=2,z.payload.maxBitrate=this.h.audioBitrate,z.payload.maxFrameRate=100):(z.payload.minBitrate=this.h.minVideoBitrate,z.payload.maxBitrate=this.h.maxVideoBitrate,z.payload.maxFrameRate=this.h.maxFrameRate),c.push(new pz(e,z));return c};
var lz=function(a,b,c){b&&!c.some(function(a){return a.af==b})&&(v(a.l,"Destroying RTP stream not selected by the receiver: id="+b),dz.rtpStream.destroy(b),b=null);return b},jz=function(a,b){return new Promise(function(c,d){for(var e=[],f=0;f<b.length;++f){var h=b[f].params,k={index:f,codecName:h.payload.codecName.toLowerCase(),rtpProfile:"cast",rtpPayloadType:h.payload.payloadType,ssrc:h.payload.ssrc,targetDelay:h.payload.animatedLatency,aesKey:h.payload.aesKey,aesIvMask:h.payload.aesIvMask,timeBase:"1/"+
h.payload.clockRate,receiverRtcpEventLog:a.h.enableLogging,rtpExtensions:["adaptive_playout_delay"]};a.h.dscpEnabled&&(k.receiverRtcpDscp=46);127==h.payload.payloadType?Object.assign(k,{type:"audio_source",bitRate:0<h.payload.maxBitrate?1E3*h.payload.maxBitrate:60*h.payload.maxFrameRate+h.payload.clockRate*h.payload.channels,sampleRate:h.payload.clockRate,channels:h.payload.channels}):Object.assign(k,{type:"video_source",renderMode:"video",maxFrameRate:Math.round(1E3*h.payload.maxFrameRate)+"/1000",
maxBitRate:1E3*h.payload.maxBitrate,resolutions:[{width:a.h.maxWidth,height:a.h.maxHeight}]});e.push(k)}var n=a.g instanceof gz||a.j instanceof gz?"remoting":"mirroring",u={type:"OFFER",sessionId:a.D,seqNum:yl(a.L),offer:{castMode:n,receiverGetStatus:!0,supportedStreams:e}};a.l.info(function(){return"Sending OFFER message: "+JSON.stringify(u)});Wy(a.C,u,"ANSWER",1E4,function(b,e){if(null==b)d(e);else if("ok"==b.result&&b.b){if(b.f!=u.seqNum)return v(a.l,"Ignoring ANSWER for OFFER with different seqNum: "+
JSON.stringify(b)),!1;((e=b.b.h)&&e!=n||!e&&"mirroring"!=n)&&a.l.error("Expected receiver to ANSWER with castMode="+n+", but got: "+e);Ab(a.l,function(){return"Received ANSWER: "+JSON.stringify(b)});c(b.b)}else d(Error("Non-OK ANSWER received: "+JSON.stringify(b)));return!0})})},kz=function(a,b,c){if(b.b.length!=b.f.length)return a.l.error("sendIndexes.length != ssrcs.length in ANSWER: "+JSON.stringify(b)),[];for(var d=[],e={},f=0;f<b.b.length;e={candidate:e.candidate},++f){var h=b.b[f];if(0>h||h>=
c.length)return a.l.error("Receiver selected invalid index ("+h+" < "+c.length+") in ANSWER: "+JSON.stringify(b)),[];e.candidate=c[h];if(d.some(function(a){return function(b){return b.af==a.candidate.af}}(e)))return a.l.error("Receiver selected same RTP stream twice in ANSWER: "+JSON.stringify(b)),[];e.candidate.params.payload.feedbackSsrc=b.f[h];if(d.some(function(a){return function(b){return b.params.payload.feedbackSsrc==a.candidate.params.payload.feedbackSsrc}}(e)))return a.l.error("Receiver provided same SSRC for two different RTP streams in ANSWER: "+
JSON.stringify(b)),[];d.push(e.candidate)}return d},mz=function(a,b,c){var d=null,e=function(){d&&(dz.rtpStream.onStarted.removeListener(d),d=null)};return(new Promise(function(e,h){var f=b.j||2344;a.l.info(function(){return"Starting RTP streams to receiver at "+(a.u+":"+f)+(" for selected offers: "+JSON.stringify(c))});var n=a.o||-1;a.h.dscpEnabled&&(a.l.info("Enabled DSCP in sender."),dz.udpTransport.setOptions(n,{DSCP:!0}));dz.udpTransport.setDestination(n,{address:a.u,port:f});var u=new Set(c.map(function(a){return a.af}));
d=function(a){u.delete(a);0==u.size&&e()};dz.rtpStream.onStarted.addListener(d);n=ma(c);for(var z=n.next();!z.done;z=n.next())z=z.value,dz.rtpStream.toggleLogging(z.af,a.h.enableLogging),dz.rtpStream.start(z.af,z.params);setTimeout(function(){h(Error("Timeout: RTP streams failed to start."))},1E4)})).then(e).catch(function(a){e();throw a;})},ez=function(a,b,c){var d=this;return a&&b in a?function(){try{a[b](c)}catch(e){d.l.error("Error from testHooks."+b,e)}}:function(){}},pz=function(a,b){this.af=
a;this.params=b},gz=function(){};var sz=function(a,b,c,d,e,f){this.m=a;this.C=qz(b,this.m.wb);this.L=new fz(this.m.wb,c,d,e,f);this.B=e;this.j=new Xy;this.h=new rz;this.A=new mojo.Binding(mojo.MirrorServiceRemoter,this,null);this.l=tb("mr.mirror.cast.MediaRemoter");this.u=this.b=this.s=this.g=this.F=null;this.f=!0;this.o=this.D.bind(this)};
sz.prototype.Xa=function(a,b){var c=this;return Zy(this.j,1,function(d){c.F=a;c.g=b;var e=c.A.createInterfacePtrAndBind();c.A.setConnectionErrorHandler(function(){c.l.info("Remoter mojo pipe connection error.");tz(c)});c.b=new mojo.MirrorServiceRemotingSourcePtr;var f=Gg(c.m.mediaSource||"");if(!f)throw Error("Failed to parse tab ID from source:\n          "+c.m.mediaSource);c.l.info("Connecting remoter to browser: tabId="+f);(og.get("mr.ProviderManager")||null).onMediaRemoterCreated(f,e,mojo.makeRequest(c.b));
c.b.ptr.setConnectionErrorHandler(function(){c.l.info("RemotingSource mojo pipe connection error.");tz(c)});return uz(c).then(function(){if(c.f)c.b.onSinkAvailable(c.C);cz(d,2)})})};
var tz=function(a){return az(a.j,function(b){a.b&&(a.b.ptr.reset(),a.b=null);var c=a.s;a.s=null;a.g=null;a.F=null;a.A.close();chrome.settingsPrivate.onPrefsChanged.hasListener(a.o)&&chrome.settingsPrivate.onPrefsChanged.removeListener(a.o);return new Promise(function(d){window.setTimeout(function(){vz(a).then(function(){cz(b,1);d();c&&c()})},250)})})};sz.prototype.Jp=function(a){wz(this.h,a)};sz.prototype.sendMessageToSink=sz.prototype.Jp;sz.prototype.tf=function(a){this.g&&this.g.tf(a)};
sz.prototype.ag=function(){return this.g?this.g.ag():Promise.resolve()};sz.prototype.de=function(a,b){this.l.error("Error during streaming: "+a,b);if(this.b)this.b.onError();tz(this)};
sz.prototype.start=function(){var a=this,b=!1;this.l.info(function(){b=!0;return"Starting next media remoting session."});b&&xz(this.h,function(b){return a.l.info(b)});yz(this.h);Zy(this.j,2,function(b){return(0,a.F)().then(function(c){a.s=c;Uy(a.B,"RPC",function(b){if(b.rpc){var c=a.h;b=b.rpc;c.s&&(++c.m,c.f+=b.length,c.s(b))}});cz(b,3)}).catch(function(c){return vz(a).then(function(){cz(b);throw c;})})}).then(function(){a.l.info("Remoting started successfully.")}).catch(function(b){a.l.error("Failed to start remoting",
b);a.b.onError()})};sz.prototype.start=sz.prototype.start;
sz.prototype.Zp=function(a,b){var c=this;return Zy(this.j,3,function(d){return c.L.start(a?new gz:null,b?new gz:null,c).then(function(a){zz(c.h,function(a){return c.B.sendMessage(a)},function(a){c.b.onMessageFromSink(a)});cz(d,4);return{audio_stream_id:a.xn||-1,video_stream_id:a.jq||-1}}).catch(function(a){return vz(c).then(function(){cz(d);throw a;})})}).catch(function(a){c.l.error("Failed to start remoting streams",a);tz(c);return{audio_stream_id:-1,video_stream_id:-1}})};
sz.prototype.startDataStreams=sz.prototype.Zp;sz.prototype.stop=function(a){var b=this;$y(this.j,function(c){b.b.onStopped(a);return vz(b).then(function(){b.l.info("Remoting stopped.");cz(c,5);(0,b.s)().then(function(){return Zy(b.j,5,function(a){if(b.b&&b.f)b.b.onSinkAvailable(b.C);cz(a,2);return Promise.resolve()})}).catch(function(a){throw a;});b.s=null})}).catch(function(a){b.l.error("Failed to stop remoting: ",a);tz(b)})};sz.prototype.stop=sz.prototype.stop;
sz.prototype.On=function(){null===this.u&&(this.u=Le(this.m.wb.Vf).then(function(a){return a.f||!1}));return this.u.then(function(a){return{rate:(a?1E7:5E6)/8}})};sz.prototype.estimateTransmissionCapacity=sz.prototype.On;
var vz=function(a){return a.L.stop().then(function(){Vy(a.B,"RPC");Az(a.h);Bz(a.h)})},uz=function(a){return new Promise(function(b){chrome.settingsPrivate.getPref("media_router.media_remoting.enabled",function(c){chrome.runtime.lastError?a.l.error("Encountered error getting media remoting pref: "+JSON.stringify(chrome.runtime.lastError)):c.type!=chrome.settingsPrivate.PrefType.BOOLEAN?a.l.error("Pref value not a boolean: "+JSON.stringify(c)):(a.f=!!c.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);b()})})};
sz.prototype.D=function(a){if(this.b){a=ma(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.l.error("Pref value not a boolean: "+JSON.stringify(b));break}a=!!b.value;if(this.f==a)break;this.f=a;this.l.info("mediaRemotingEnabled_ changed to: "+this.f);if(this.f)this.b.onSinkAvailable(this.C);else this.b.onStopped(mojo.RemotingStopReason.USER_DISABLED);break}}};
var qz=function(a,b){var c=this,d=new mojo.RemotingSinkMetadata;d.features=[];d.friendly_name=b.Yp||"";d.audio_capabilities=[];d.video_capabilities=[];var e=mojo.RemotingSinkAudioCapability,f=mojo.RemotingSinkVideoCapability,h=d.audio_capabilities,k=d.video_capabilities,n=b.je||"";(a.b||[]).forEach(function(a){switch(a){case "audio":h.push(e.CODEC_BASELINE_SET);break;case "aac":h.push(e.CODEC_AAC);break;case "opus":h.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":n.startsWith("Chromecast Ultra")&&k.push(f.CODEC_VP9);break;case "hevc":n.startsWith("Chromecast Ultra")&&k.push(f.CODEC_HEVC);break;default:c.l.info("Unknown mediaCap name: "+a)}});b.je&&"Chromecast Ultra"==b.je&&k.push(f.SUPPORT_4K);return d},rz=function(){this.s=this.j=this.b=null;this.u=this.f=this.m=this.h=this.o=0;this.g=null},yz=function(a){a.b=[];Cz(a,performance.now())},zz=function(a,b,c){a.j=b;a.s=
c;a.b?(b=a.b,a.b=null,b.forEach(function(b){return wz(a,b.data).then(b.Lp,b.el)})):Cz(a,performance.now())},Az=function(a){if(a.b){var b=Error("Stop before delivering pending message");a.b.forEach(function(a){return a.el(b)});a.b=null}a.j=null;a.s=null},wz=function(a,b){if(a.j){var c=btoa(String.fromCharCode.apply(null,b));++a.o;a.h+=b.length;return a.j({type:"RPC",rpc:c})}return a.b?new Promise(function(c,e){a.b.push({data:b,Lp:c,el:e})}):Promise.reject(Error("RPC pipe not started"))},xz=function(a,
b){Bz(a);a.g=setInterval(function(){if(a.b)var c=a.b.length+" messages are waiting to send.";else{c=performance.now();var d=(c-a.u)/1E3;d="Over the past "+d.toFixed(1)+" seconds, sent "+(a.o+" messages ("+Math.round(a.h/d)+" bytes/sec) and ")+("received "+a.m+" messages ("+Math.round(a.f/d)+" ")+"bytes/sec).";Cz(a,c);c=d}b(c)},3E4)},Bz=function(a){null!=a.g&&(clearInterval(a.g),a.g=null)},Cz=function(a,b){a.o=0;a.h=0;a.m=0;a.f=0;a.u=b};var Dz=function(a){return a&&a.getAudioTracks()&&0<a.getAudioTracks().length?a.getAudioTracks()[0]:null},Ez=function(a){return a&&a.getVideoTracks()&&0<a.getVideoTracks().length?a.getVideoTracks()[0]:null};var Fz=function(a,b,c,d,e){this.h=new fz(a,b,c,d,void 0===e?null:e);this.l=tb("mr.mirror.cast.MediaStreamer");this.j=new Xy;this.g=this.f=this.b=this.s=null};Fz.prototype.start=function(a,b){var c=this;return Zy(this.j,1,function(d){c.s=a;c.b=Dz(a);c.b&&"ended"==c.b.readyState&&(c.b=null);c.f=Ez(a);c.f&&"ended"==c.f.readyState&&(c.f=null);if(!c.b&&!c.f)return cz(d),Promise.reject(Error("No MediaStream tracks to stream."));c.g=b;return c.h.start(c.b,c.f,c.g).then(function(){return cz(d,2)})})};
Fz.prototype.stop=function(){var a=this;return az(this.j,function(b){return a.h.stop().then(function(){a.b=null;a.f=null;a.s=null;a.g=null;cz(b,1)})})};var Gz=function(a){return Zy(a.j,2,function(b){a.l.info("Suspending media streaming...");return a.h.stop().then(function(){a.l.info("Suspended media streaming.");cz(b,3)})})};
Fz.prototype.resume=function(){var a=this;return Zy(this.j,3,function(b){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.h.start(a.b,a.f,a.g).then(function(){a.l.info("Resumed media streaming.");cz(b,2)})})};var Hz=function(a,b,c){this.j=a;this.g=b;this.h=c;this.l=tb("mr.mirror.cast.WifiStatusMonitor");this.b=null;this.f=[]};Hz.prototype.start=function(){var a=this;null==this.b&&(Ab(this.l,"Starting Wifi Status Monitoring."),this.f=[],Uy(this.h,"STATUS_RESPONSE",function(b){return Iz(a,b)}),this.b=setInterval(function(){return Jz(a)},12E4),Jz(this))};Hz.prototype.stop=function(){null!=this.b&&(Ab(this.l,"Stopping Wifi Status Monitoring."),clearInterval(this.b),this.b=null,Vy(this.h,"STATUS_RESPONSE"))};
var Iz=function(a,b){if(null!=a.b)if(b.status){var c={};null!=b.status.b&&(c.wifiSnr=b.status.b);null!=b.status.f&&(c.wifiSpeed=b.status.f[3]);0==Object.keys(c).length?v(a.l,function(){return"No status fields populated in response: "+JSON.stringify(b)}):(c.timestamp=Date.now(),30==a.f.length&&a.f.shift(),a.f.push(c),a.l.info(function(){return"Current Wifi status: "+JSON.stringify(c)}))}else v(a.l,function(){return"Ignoring response without status: "+JSON.stringify(b)})},Jz=function(a){a.h.sendMessage({type:"GET_STATUS",
sessionId:a.j,seqNum:yl(a.g),get_status:["wifiSnr","wifiSpeed"]})};var Kz=function(a,b,c,d){this.C=b.Vf;this.m={extVersion:chrome.runtime.getManifest().version,extChannel:"public",mirrorSettings:Wg(a),sender:navigator.userAgent||"UNKNOWN",receiverProductName:b.je};this.F=c;this.B=d;this.g=this.f=this.o=this.s=this.j=this.u=this.h=null;this.b=[]};Kz.prototype.tf=function(a){null!=this.f&&clearInterval(this.f);this.h=a;this.u=Date.now();this.f=setInterval(this.A.bind(this,a),9E5)};
Kz.prototype.ag=function(){null!=this.f&&(clearInterval(this.f),this.f=null);if(null!=this.h){var a=this.A(this.h);this.h=null;return a}return Promise.resolve()};Kz.prototype.de=function(a,b){null==this.j&&(this.j=Date.now(),"function"===typeof a?this.s=a():"string"===typeof a&&(this.s=a),b&&"string"===typeof b.stack&&(this.o=b.stack))};
var Mz=function(a,b){return(null==a.h?Promise.resolve():a.A(a.h)).then(function(){var c=b.map(function(b){b=Lz(a,b);var c=b.map(function(a){return a.events}).filter(function(a){return null!=a}),d=["["];b.map(function(a){return a.Ze}).forEach(function(a,b){0<b&&d.push(",");d.push(a)});d.push("]");return{events:new Blob(c,{type:"application/gzip"}),Ze:new Blob(d,{type:"application/json"})}});a.b=[];return c})};
Kz.prototype.A=function(a){var b=this;if(null!=this.g)return this.g;var c=Le(this.C).then(function(c){c={receiverVersion:c.b,receiverConnected:c.g,receiverOnEthernet:c.f,receiverHasUpdatePending:c.h,receiverUptimeSeconds:c.j};Object.assign(c,b.m);var d=Date.now();Object.assign(c,{startTime:b.u,endTime:d,activity:hz(a),receiverWifiStatus:Array.from(b.B.f)});b.u=d;null!=b.j&&(Object.assign(c,{streamingErrorTime:b.j,streamingErrorMessage:b.s,streamingErrorCause:b.o}),b.j=null,b.s=null,b.o=null);return c});
return(this.g=Promise.all([c.then(function(b){return nz(a,b)}),c,oz(a)]).then(function(a){var c=ma(a);a=c.next().value;var d=c.next().value;c=c.next().value;b.b.push({events:a,Ze:new Blob([JSON.stringify(Object.assign({tags:d},c))],{type:"application/json"})});b.b=Lz(b,b.F);b.g=null}))||Promise.resolve()};
var Lz=function(a,b){b-=2;for(var c=[],d=a.b.length-1;0<=d;--d){b-=a.b[d].Ze.size+1;if(0>b)break;c.push({events:null,Ze:a.b[d].Ze});if(null!=a.b[d].events){var e=a.b[d].events.size;b>=e&&(c[c.length-1].events=a.b[d].events,b-=e)}}return c.reverse()};var Nz=tb("mr.NetworkUtils"),Oz=function(a,b){return Zf?new Promise(function(c,d){chrome.networkingPrivate.setWifiTDLSEnabledState(a,b,function(a){chrome.runtime.lastError?(v(Nz,"Unable to set TDLS state: state = "+b+", error = "+chrome.runtime.lastError.message),d("Unable to set TDLS state to "+b+".")):(Nz.info("TDLS state changed: state = "+b+", status = "+a),c(a))})}):Promise.reject("TDLS feature not enabled.")};var Pz=function(a,b,c,d){d=void 0===d?null:d;Tg.call(this,b);var e=b.wb;this.A=e.sessionId;this.C=e.Vf;this.F=a;this.D=d;this.l=tb("mr.mirror.cast.Session");this.o=new Xy;this.m=new xl("mirror.cast.SeqNumGenerator");this.s=new Ty(b.id);this.j=new Fz(e,this.F,this.m,this.s,this.D);this.g=null;this.b=new Kz(a,e,c,new Hz(this.A,this.m,this.s));this.f=!1;this.B=null};l(Pz,Tg);g=Pz.prototype;
g.start=function(a){var b=this;return Zy(this.o,1,function(c){var d=new Fb("MediaRouter.CastStreaming.Session.Launch");return Qz(b).then(function(c){b.f=c;return b.j.start(a,b)}).then(function(){if(b.j.h.B){var a=b.b;a.m.tdlsIsOn=b.f;a.B.start();Rz(b)}else b.b.m.tdlsIsOn=b.f;d.b();b.B=new Lb("MediaRouter.CastStreaming.Session.Length");cz(c,2);return b})})};
g.stop=function(){var a=this;return az(this.o,function(b){a.B&&(a.B.b(),a.B=null);a.b.B.stop();return a.j.stop().then(function(){return a.g?tz(a.g):Promise.resolve()}).then(function(){a.g=null;return a.f?Sz(a):Promise.resolve()}).then(function(){a.f=!1;cz(b,4)})})};g.cl=function(){var a={sessionId:this.A,seqNum:yl(this.m),type:"PRESENTATION",icons:[],title:Rg(this.Wb)};this.l.info("Sending session metadata update to receiver: "+this.A);this.s.sendMessage(a)};g.tf=function(a){this.b.tf(a)};g.ag=function(){return this.b.ag()};
g.de=function(a,b){this.b.de(a,b);this.l.error(a,b);this.stop()};
var Tz=function(a,b){return Mz(a.b,b)},Qz=function(a){return a.F.useTdls?Oz(a.C,!0).then(function(b){if("Connected"==b)return a.l.info("Successfully enabled TDLS."),!0;v(a.l,"Did not enable TDLS: result="+b);return!1}).catch(function(b){v(a.l,"Error while calling enableTDLS()",b);return!1}):Promise.resolve(!1)},Sz=function(a){return Oz(a.C,!1).catch(function(b){return a.l.error("Error while turning TDLS back off",b)})},Rz=function(a){Uz(a).then(function(b){(b.b||[]).includes("video")?Vz(a,b):v(a.l,
function(){return"Receiver incapable of Media Remoting: "+JSON.stringify(b)})}).catch(function(b){v(a.l,"None/Invalid capabilites response. Media Remoting disabled.",b)})},Uz=function(a){return new Promise(function(b,c){var d={type:"GET_CAPABILITIES",sessionId:a.A,seqNum:yl(a.m)};a.l.info(function(){return"Sending GET_CAPABILITIES message: "+JSON.stringify(d)});Wy(a.s,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.f!=d.seqNum)return a.l.info(function(){return"Ignoring CAPABILITIES_RESPONSE with different seqNum: "+JSON.stringify(e)}),!1;Ab(a.l,function(){return"Received CAPABILITIES_RESPONSE: "+JSON.stringify(e)});b(e.capabilities);return!0})})},Vz=function(a,b){Zy(a.o,2,function(c){var d=a.h.wb.je||"<UNKNOWN>";if(!d.startsWith("Chromecast")&&!d.startsWith("Eureka Dongle"))return v(a.l,"HACK: Media Remoting disabled because the receiver model--"+('"'+d+'" according to discovery--is not a Chromecast.')),
cz(c),Promise.resolve();a.g=new sz(a.h,b,a.F,a.m,a.s,a.D);return a.g.Xa(a.K.bind(a),a).catch(function(b){a.l.error("Media Remoting start failed: "+b.message,b)}).then(function(){return cz(c)})})};Pz.prototype.K=function(){var a=this;return Zy(this.o,2,function(b){return new Promise(function(c,d){Gz(a.j).then(function(){cz(b,3);a.L=!0;Og(a);c(a.M.bind(a))}).catch(function(b){a.de("Failed to suspend MediaStreamer before starting remoting",b);d(b)})})})};
Pz.prototype.M=function(){var a=this;return Zy(this.o,3,function(b){return new Promise(function(c,d){a.j.resume().then(function(){cz(b,2);a.L=!1;Og(a);c()}).catch(function(b){a.de("Failed resume MediaStreamer after ending remoting mode",b);d(b)})})})};var Wz=function(){Hg.call(this,"cast_streaming")};l(Wz,Hg);g=Wz.prototype;g.getName=function(){return"cast_streaming"};g.tg=function(a,b){return new Pz(a,b,20969472,null)};g.eh=function(){ty(0)};g.ah=function(){ty(1)};g.ui=function(){ty(2)};g.bh=function(){Qb("MediaRouter.CastStreaming.Session.End")};g.dh=function(a){Rb("MediaRouter.CastStreaming.Start.Failure",a,Vf)};g.Qf=function(){Qb("MediaRouter.CastStreaming.Stream.End")};
g.rh=function(a){var b=this;return(new Promise(function(a){return chrome.metricsPrivate.getIsCrashReportingEnabled(a)})).then(function(c){var d=c&&Ay(),e=[9351424];d&&e.push(20969472);return Tz(a,e).then(function(a){var e=a[a.length-1];a=zj(a[0].events).catch(function(a){b.J.error("Failed to persist events Blob.",a)});d&&0<e.events.size?wy(e.events,void 0,b.Co.bind(b)):c&&vy("stats.json",e.Ze,void 0,void 0);return a})})};g.Co=function(a){a&&(zy().b=Date.now())};
g.di=function(a){this.J.info("Received message to upload logs for "+a);return this.b?Tz(this.b,[20969472]).then(function(b){b=ma(b).next().value;return 0==b.events.size?"":wy(b.events,a)}):Promise.resolve(Xz(this,a))};
var Xz=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 zj(new Blob),a.J.info("Uploading saved logs for feedback."),wy(c,b)},Yz=new Wz;xg("mr.mirror.cast.Service",Yz);
