'use strict';var ey={TAB:0,ll:1,aq:2},fy=function(){return new kb("MediaRouter.CastStreaming.Session.Launch")},gy=function(){return new qb("MediaRouter.CastStreaming.Session.Length")},hy=function(a){ub("MediaRouter.CastStreaming.Start.Success",a,ey)};var iy=$a("mr.mirror.cast.LogUploader"),ky=function(a,b,c){jy("raw_events.log.gz",a,b,c);return b?"https://crash.corp.google.com/samples?reportid=&q="+encodeURIComponent("UserComments='"+b+"'"):""},jy=function(a,b,c,d){if(0==b.size)iy.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);Tv("https://clients2.google.com/cr/report",function(f){f=f.target;
var g=null;cw(f)?(g=ew(f),iy.info("Upload to Crash succeeded: "+g)):iy.info("Upload to Crash failed. HTTP status: "+f.Ja());d&&d(g)},"POST",e,void 0,3E4)}};var ly=function(){this.g=0;km(this)},ny=function(){my||(my=new ly);return my},oy=function(){var a=ny(),b={fraction:.01,autoSubmitTimeLimitMillis:6048E5},c=b.autoSubmitTimeLimitMillis,d=Date.now();return a.g&&c&&d-a.g<c?!1:Math.random()<b.fraction};ly.prototype.Ua=function(){return"mirror.cast.LogUtils"};ly.prototype.Ib=function(){return[void 0,{lastAutoSubmitMillis:this.g}]};ly.prototype.Hb=function(){var a=im(this);this.g=a&&a.lastAutoSubmitMillis||0};var my=null;$a("mr.mirror.cast.LogUtils");var py={WE:"OFFER",Ax:"ANSWER",HF:"PRESENTATION",sB:"GET_STATUS",wI:"STATUS_RESPONSE",nB:"GET_CAPABILITIES",Vy:"CAPABILITIES_RESPONSE",yH:"RPC"};var qy=function(){this.capabilities=this.status=this.g=this.error=this.rpc=this.result=this.type=this.h=this.sessionId=null},ty=function(a){try{if("string"!==typeof a)throw SyntaxError("Cannot parse non-string as JSON");var b;ry(JSON.parse(a),function(d){b=sy(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);},sy=function(a){var b=new qy;null!=a.sessionId&&(b.sessionId=String(a.sessionId));uy(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(py)),e=d.next();!e.done;e=d.next())if(py[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)}))}ry(a.error,function(f){b.error=vy(f)},function(){throw Error('"error" must be an Object');});ry(a.answer,function(f){b.g=wy(f)},function(){throw Error('"answer" must be an Object');});ry(a.status,function(f){b.status=xy(f)},function(){throw Error('"status" must be an Object');
});ry(a.capabilities,function(f){b.capabilities=yy(f)},function(){throw Error('"capabilities" must be an Object');});return b},ry=function(a,b,c){void 0!==a&&(a instanceof Object?b(a):c())},uy=function(a,b,c){void 0!==a&&("number"!==typeof a?c():b(a))},zy=function(a,b,c){void 0!==a&&(a instanceof Array&&a.every(function(d){return"number"===typeof d})?b(a):c())},Ay=function(a,b,c){void 0!==a&&(a instanceof Array?b(a.map(function(d){return String(d)})):c())},By=function(){this.C=null;this.g=[];this.h=
[];this.j=this.l=this.m=null},wy=function(a){var b=new By;uy(a.udpPort,function(c){b.C=c},function(){throw Error('"answer.udpPort" must be a number');});zy(a.sendIndexes,function(c){b.g=c},function(){throw Error('"answer.sendIndexes" must be an array of numbers');});zy(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},Cy=function(){this.details=this.description=this.code=null},vy=function(a){var b=new Cy;uy(a.code,function(c){b.code=c},function(){throw Error('"error.code" must be a number');});"description"in a&&(b.description=String(a.description));ry(a.details,function(c){b.details=c},function(){throw Error('"error.details" must be an Object');});return b},Dy=function(){this.h=this.g=null},xy=function(a){var b=new Dy;uy(a.wifiSnr,function(c){b.g=c},function(){throw Error('"status.wifiSnr" must be a number');
});zy(a.wifiSpeed,function(c){b.h=c},function(){throw Error('"status.wifiSpeed" must be an array of numbers');});return b},Ey=function(){this.h=this.g=null},yy=function(a){var b=new Ey;Ay(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;ry(c,function(e){d=Fy(e)},function(){throw Error('"capabilities.keySystems" entries must be *Objects');
});return d})}return b},Gy=function(){this.h=this.m=this.C=this.l=this.u=this.g=this.o=this.codecs=this.initDataTypes=this.j=null},Fy=function(a){var b=new Gy;"keySystemName"in a&&(b.j=String(a.keySystemName));Ay(a.initDataTypes,function(c){b.initDataTypes=c},function(){throw Error('"capabilities.initDataTypes" must be an array');});Ay(a.codecs,function(c){b.codecs=c},function(){throw Error('"capabilities.codecs" must be an array');});Ay(a.secureCodecs,function(c){b.o=c},function(){throw Error('"capabilities.secureCodecs" must be an array');
});Ay(a.audioRobustness,function(c){b.g=c},function(){throw Error('"capabilities.audioRobustness" must be an array');});Ay(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 Hy=function(a){this.s=$a("mr.mirror.cast.MessageDispatcher");this.l=a;this.g=null;this.h=new Map;this.j=0},Iy=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;gb(a.s,"Added subscriber for "+b+"-type messages.");a.g||(a.g=$w(a.l),a.g.onMessage=a.C.bind(a))},Jy=function(a,b){a.h.delete(b)&&gb(a.s,function(){return"Removed subscriber of "+b+"-type messages."});0==a.h.size&&a.g&&(a.g.dispose(),a.g=null)};
Hy.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 Ky=function(a,b,c,d,e){var f=null,g=function(){Jy(a,c);null!=f&&(clearTimeout(f),f=null)};try{Iy(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)})};
Hy.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=ty(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.s.K(b):gb(this.s,b);++this.j}};var Ly=function(){this.g=Promise.resolve(1)},Ny=function(a,b,c){return My(a,function(d){return d==b},c)},Oy=function(a,b){var c=[3,4];return My(a,function(d){return-1!=c.indexOf(d)},b)},Py=function(a,b){a.g=a.g.catch(function(){return 1});return My(a,function(){return!0},b)},My=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 Qy(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},Qy=function(a){this.h=a;this.g=null},Ry=function(a,b){a.g="number"===typeof b?b:a.h};var Sy=chrome.cast.streaming,Ty=$a("mr.mirror.cast.StreamingLaunchWorkflow"),Vy=function(a,b,c,d,e){this.L=a.sessionId;this.F=a.Yg;this.V=a.ge;this.j=b;this.J=c;this.M=d;this.X=Uy(e,"onAnswer",this.F);this.ub=Uy(e,"onSessionStop",this.F);this.s=Ty;this.D=new Ly;this.o=this.G=this.u=this.h=this.g=this.m=this.C=this.l=null};
Vy.prototype.start=function(a,b,c){var d=this;if(!a&&!b)return Promise.reject(Error("No tracks to stream"));var e=a instanceof Wy,f=b instanceof Wy;(e&&b&&!f||f&&a&&!e)&&Eb("Mixing remoting and non-remoting tracks");return Ny(this.D,1,function(g){d.l=a;d.C=b;d.m=c;d.s.info(function(){return"Launching streaming for "+Xy(d)+" to a "+(d.V+".")});return Yy(d).then(d.H.bind(d)).then(function(h){return Zy(d,h).then(function(m){d.X();var q=$y(d,m,h);d.g=az(d,d.g,q);d.h=az(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.o=function(r,u){r==d.g?d.m.Ge("Audio stream (id="+r+") error: "+u):r==d.h&&d.m.Ge("Video stream (id="+r+") error: "+u)};Sy.rtpStream.onError.addListener(d.o);return bz(d,m,q)})}).then(function(){d.s.info(function(){return"Launched streaming for "+Xy(d)});d.m.pg(d);Ry(g,2);return{er:d.g,Yw:d.h}})})};
Vy.prototype.stop=function(){var a=this;return Py(this.D,function(b){if(!a.l&&!a.C)return Ry(b,1),Promise.resolve();a.s.info(function(){return"Stopping streaming for "+Xy(a)+"."});a.o&&(Sy.rtpStream.onError.removeListener(a.o),a.o=null);if(a.m){var c=a.m.dh();a.m=null}else c=Promise.resolve();return c.then(function(){a.g&&(Sy.rtpStream.stop(a.g),Sy.rtpStream.destroy(a.g),a.g=null);a.h&&(Sy.rtpStream.stop(a.h),Sy.rtpStream.destroy(a.h),a.h=null);a.u&&(Sy.udpTransport.destroy(a.u),a.u=null);a.ub();
a.s.info(function(){return"Stopped streaming for "+Xy(a)+"."});a.l=null;a.C=null;Ry(b,1)})})};
var cz=function(a,b){var c=JSON.stringify(b);return Promise.all([a.g&&new Promise(function(d){return Sy.rtpStream.getRawEvents(a.g,c,d)}),a.h&&new Promise(function(d){return Sy.rtpStream.getRawEvents(a.h,c,d)})]).catch(function(d){a.s.error("Unexpected error when calling getRawEvents()",d);return[]}).then(function(d){return new Blob(d.filter(function(e){return!!e}),{type:"application/gzip"})})},dz=function(a){return Promise.all([a.g&&new Promise(function(b){return Sy.rtpStream.getStats(a.g,b)}),a.h&&
new Promise(function(b){return Sy.rtpStream.getStats(a.h,b)})]).catch(function(b){a.s.error("Unexpected error when calling getStats()",b);return[]}).then(function(b){return Object.assign.apply(Object,[{}].concat(p(b.filter(function(c){return!!c}))))})},Xy=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 Wy||a.C instanceof Wy?b+"remoting":b+"streaming"},Yy=function(a){return new Promise(function(b){var c=
function(d,e,f){d&&!a.l&&(Sy.rtpStream.destroy(d),d=null);e&&!a.C&&(Sy.rtpStream.destroy(e),e=null);a.s.info(function(){return"Created Cast Streaming session: audioStreamId="+d+", videoStreamId="+e+"."});a.g=d;a.h=e;a.u=f;b()};a.l instanceof Wy||a.C instanceof Wy?Sy.session.create(null,null,c):Sy.session.create(a.l,a.C,c)})};
Vy.prototype.H=function(){for(var a=ek(),b=ek(),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(Sy.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 ez(e,r));return c};
var az=function(a,b,c){b&&!c.some(function(d){return d.Kf==b})&&(a.s.K("Destroying RTP stream not selected by the receiver: id="+b),Sy.rtpStream.destroy(b),b=null);return b},Zy=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 Wy||a.C instanceof Wy?"remoting":"mirroring",q={type:"OFFER",sessionId:a.L,seqNum:vn(a.J),offer:{castMode:m,receiverGetStatus:!0,supportedStreams:e}};a.s.info(function(){return"Sending OFFER message: "+JSON.stringify(q)});Ky(a.M,q,"ANSWER",1E4,function(r,u){if(null==r)d(u);else if("ok"==r.result&&r.g){if(r.h!=q.seqNum)return a.s.K("Ignoring ANSWER for OFFER with different seqNum: "+
JSON.stringify(r)),!1;((u=r.g.j)&&u!=m||!u&&"mirroring"!=m)&&a.s.error("Expected receiver to ANSWER with castMode="+m+", but got: "+u);gb(a.s,function(){return"Received ANSWER: "+JSON.stringify(r)});c(r.g)}else d(Error("Non-OK ANSWER received: "+JSON.stringify(r)));return!0})})},$y=function(a,b,c){if(b.g.length!=b.h.length)return a.s.error("sendIndexes.length != ssrcs.length in ANSWER: "+JSON.stringify(b)),[];for(var d=[],e={},f=0;f<b.g.length;e={cf:e.cf},++f){var g=b.g[f];if(0>g||g>=c.length)return a.s.error("Receiver selected invalid index ("+
g+" < "+c.length+") in ANSWER: "+JSON.stringify(b)),[];e.cf=c[g];if(d.some(function(h){return function(m){return m.Kf==h.cf.Kf}}(e)))return a.s.error("Receiver selected same RTP stream twice in ANSWER: "+JSON.stringify(b)),[];e.cf.params.payload.feedbackSsrc=b.h[g];if(d.some(function(h){return function(m){return m.params.payload.feedbackSsrc==h.cf.params.payload.feedbackSsrc}}(e)))return a.s.error("Receiver provided same SSRC for two different RTP streams in ANSWER: "+JSON.stringify(b)),[];d.push(e.cf)}return d},
bz=function(a,b,c){var d=null,e=function(){d&&(Sy.rtpStream.onStarted.removeListener(d),d=null)};return(new Promise(function(f,g){var h=b.C||2344;a.s.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.s.info("Enabled DSCP in sender."),Sy.udpTransport.setOptions(m,{DSCP:!0}));Sy.udpTransport.setDestination(m,{address:a.F,port:h});var q=new Set(c.map(function(u){return u.Kf}));d=function(u){q.delete(u);
0==q.size&&f()};Sy.rtpStream.onStarted.addListener(d);m=n(c);for(var r=m.next();!r.done;r=m.next())r=r.value,Sy.rtpStream.toggleLogging(r.Kf,a.j.enableLogging),Sy.rtpStream.start(r.Kf,r.params);setTimeout(function(){g(Error("Timeout: RTP streams failed to start."))},1E4)})).then(e).catch(function(f){e();throw f;})},Uy=function(a,b,c){return a&&b in a?function(){try{a[b](c)}catch(d){Ty.error("Error from testHooks."+b,d)}}:function(){}},ez=function(a,b){this.Kf=a;this.params=b},Wy=function(){};var fz=$a("mr.mirror.cast.MediaRemoter"),iz=function(a,b,c,d,e,f){this.o=a;this.M=gz(b,this.o.sb);this.J=new Vy(this.o.sb,c,d,e,f);this.G=e;this.C=new Ly;this.j=new hz;this.D=new mojo.Binding(mojo.MirrorServiceRemoter,this,null);this.s=fz;this.F=this.g=this.m=this.l=this.H=null;this.h=!0;this.u=this.L.bind(this)},lz=function(a,b,c){return Ny(a.C,1,function(d){a.H=b;a.l=c;var e=a.D.createInterfacePtrAndBind();a.D.setConnectionErrorHandler(function(){a.s.info("Remoter mojo pipe connection error.");
jz(a)});a.g=new mojo.MirrorServiceRemotingSourcePtr;var f=uj(a.o.mediaSource||"");if(!f)throw Error("Failed to parse tab ID from source:\n          "+a.o.mediaSource);a.s.info("Connecting remoter to browser: tabId="+f);(dj.get("mr.ProviderManager")||null).onMediaRemoterCreated(f,e,mojo.makeRequest(a.g));a.g.ptr.setConnectionErrorHandler(function(){a.s.info("RemotingSource mojo pipe connection error.");jz(a)});return kz(a).then(function(){if(a.h)a.g.onSinkAvailable(a.M);Ry(d,2)})})},jz=function(a){return Py(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(){mz(a).then(function(){Ry(b,1);d();c&&c()})},250)})})};k=iz.prototype;k.fw=function(a){nz(this.j,a)};k.pg=function(a){this.l&&this.l.pg(a)};k.dh=function(){return this.l?this.l.dh():Promise.resolve()};
k.Ge=function(a,b){this.s.error("Error during streaming: "+a,b);if(this.g)this.g.onError();jz(this)};
k.start=function(){var a=this,b=!1;this.s.info(function(){b=!0;return"Starting next media remoting session."});b&&oz(this.j,function(c){return a.s.info(c)});pz(this.j);Ny(this.C,2,function(c){return(0,a.H)().then(function(d){a.m=d;Iy(a.G,"RPC",function(e){if(e.rpc){var f=a.j;e=e.rpc;f.m&&(++f.o,f.h+=e.length,f.m(e))}});Ry(c,3)}).catch(function(d){return mz(a).then(function(){Ry(c);throw d;})})}).then(function(){a.s.info("Remoting started successfully.")}).catch(function(c){a.s.error("Failed to start remoting",c);
a.g.onError()})};k.Gw=function(a,b){var c=this;return Ny(this.C,3,function(d){return c.J.start(a?new Wy:null,b?new Wy:null,c).then(function(e){qz(c.j,function(f){return c.G.sendMessage(f)},function(f){c.g.onMessageFromSink(f)});Ry(d,4);return{audio_stream_id:e.er||-1,video_stream_id:e.Yw||-1}}).catch(function(e){return mz(c).then(function(){Ry(d);throw e;})})}).catch(function(d){c.s.error("Failed to start remoting streams",d);jz(c);return{audio_stream_id:-1,video_stream_id:-1}})};
k.stop=function(a){var b=this;Oy(this.C,function(c){b.g.onStopped(a);return mz(b).then(function(){b.s.info("Remoting stopped.");Ry(c,5);(0,b.m)().then(function(){return Ny(b.C,5,function(d){if(b.g&&b.h)b.g.onSinkAvailable(b.M);Ry(d,2);return Promise.resolve()})}).catch(function(d){throw d;});b.m=null})}).catch(function(c){b.s.error("Failed to stop remoting: ",c);jz(b)})};
k.Er=function(){null===this.F&&(this.F=zf(this.o.sb.Yg).then(function(a){return a.h||!1}));return this.F.then(function(a){return{rate:(a?1E7:5E6)/8}})};
var mz=function(a){return a.J.stop().then(function(){Jy(a.G,"RPC");rz(a.j);sz(a.j)})},kz=function(a){return new Promise(function(b){chrome.settingsPrivate.getPref("media_router.media_remoting.enabled",function(c){chrome.runtime.lastError?a.s.error("Encountered error getting media remoting pref: "+JSON.stringify(chrome.runtime.lastError)):c.type!=chrome.settingsPrivate.PrefType.BOOLEAN?a.s.error("Pref value not a boolean: "+JSON.stringify(c)):(a.h=!!c.value,a.s.info("Initializing mediaRemotingEnabled_ with value read from pref: "+
a.h));chrome.settingsPrivate.onPrefsChanged.hasListener(a.u)||chrome.settingsPrivate.onPrefsChanged.addListener(a.u);b()})})};
iz.prototype.L=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.s.error("Pref value not a boolean: "+JSON.stringify(b));break}a=!!b.value;if(this.h==a)break;this.h=a;this.s.info("mediaRemotingEnabled_ changed to: "+this.h);if(this.h)this.g.onSinkAvailable(this.M);else this.g.onStopped(mojo.RemotingStopReason.USER_DISABLED);break}}};
var gz=function(a,b){var c=new mojo.RemotingSinkMetadata;c.features=[];c.friendly_name=b.Cw||"";c.audio_capabilities=[];c.video_capabilities=[];var d=mojo.RemotingSinkAudioCapability,e=mojo.RemotingSinkVideoCapability,f=c.audio_capabilities,g=c.video_capabilities,h=b.ge||"";(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:fz.info("Unknown mediaCap name: "+m)}});b.ge&&"Chromecast Ultra"==b.ge&&g.push(e.SUPPORT_4K);return c};iz.prototype.estimateTransmissionCapacity=iz.prototype.Er;iz.prototype.stop=iz.prototype.stop;iz.prototype.startDataStreams=iz.prototype.Gw;iz.prototype.start=iz.prototype.start;
iz.prototype.sendMessageToSink=iz.prototype.fw;
var hz=function(){this.m=this.C=this.g=null;this.F=this.h=this.o=this.j=this.u=0;this.l=null},pz=function(a){a.g=[];tz(a,performance.now())},qz=function(a,b,c){a.C=b;a.m=c;a.g?(b=a.g,a.g=null,b.forEach(function(d){return nz(a,d.data).then(d.hw,d.ro)})):tz(a,performance.now())},rz=function(a){if(a.g){var b=Error("Stop before delivering pending message");a.g.forEach(function(c){return c.ro(b)});a.g=null}a.C=null;a.m=null},nz=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,hw:d,ro:e})}):Promise.reject(Error("RPC pipe not started"))},oz=function(a,b){sz(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.o+" messages ("+Math.round(a.h/d)+" bytes/sec).");tz(a,c);c=d}b(c)},3E4)},
sz=function(a){null!=a.l&&(clearInterval(a.l),a.l=null)},tz=function(a,b){a.u=0;a.j=0;a.o=0;a.h=0;a.F=b};var uz=function(a){return a&&a.getAudioTracks()&&0<a.getAudioTracks().length?a.getAudioTracks()[0]:null},vz=function(a){return a&&a.getVideoTracks()&&0<a.getVideoTracks().length?a.getVideoTracks()[0]:null};var wz=function(a,b,c,d,e){this.j=new Vy(a,b,c,d,void 0===e?null:e);this.s=$a("mr.mirror.cast.MediaStreamer");this.C=new Ly;this.l=this.h=this.g=this.m=null};wz.prototype.start=function(a,b){var c=this;return Ny(this.C,1,function(d){c.m=a;c.g=uz(a);c.g&&"ended"==c.g.readyState&&(c.g=null);c.h=vz(a);c.h&&"ended"==c.h.readyState&&(c.h=null);if(!c.g&&!c.h)return Ry(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 Ry(d,2)})})};
wz.prototype.stop=function(){var a=this;return Py(this.C,function(b){return a.j.stop().then(function(){a.g=null;a.h=null;a.m=null;a.l=null;Ry(b,1)})})};var xz=function(a){return Ny(a.C,2,function(b){a.s.info("Suspending media streaming...");return a.j.stop().then(function(){a.s.info("Suspended media streaming.");Ry(b,3)})})};
wz.prototype.resume=function(){var a=this;return Ny(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.s.info("Resuming media streaming...");return a.j.start(a.g,a.h,a.l).then(function(){a.s.info("Resumed media streaming.");Ry(b,2)})})};var yz=function(a,b,c){this.C=a;this.l=b;this.j=c;this.s=$a("mr.mirror.cast.WifiStatusMonitor");this.g=null;this.h=[]};yz.prototype.start=function(){var a=this;null==this.g&&(gb(this.s,"Starting Wifi Status Monitoring."),this.h=[],Iy(this.j,"STATUS_RESPONSE",function(b){return zz(a,b)}),this.g=setInterval(function(){return Az(a)},12E4),Az(this))};yz.prototype.stop=function(){null!=this.g&&(gb(this.s,"Stopping Wifi Status Monitoring."),clearInterval(this.g),this.g=null,Jy(this.j,"STATUS_RESPONSE"))};
var zz=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.s.K(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.s.info(function(){return"Current Wifi status: "+JSON.stringify(c)}))}else a.s.K(function(){return"Ignoring response without status: "+JSON.stringify(b)})},Az=function(a){a.j.sendMessage({type:"GET_STATUS",
sessionId:a.C,seqNum:vn(a.l),get_status:["wifiSnr","wifiSpeed"]})};var Bz=function(a,b,c,d){this.H=b.Yg;this.M={extVersion:chrome.runtime.getManifest().version,extChannel:"public",mirrorSettings:Kj(a),sender:navigator.userAgent||"UNKNOWN",receiverProductName:b.ge};this.G=c;this.D=d;this.l=this.h=this.o=this.m=this.C=this.u=this.j=null;this.g=[]};Bz.prototype.pg=function(a){null!=this.h&&clearInterval(this.h);this.j=a;this.u=Date.now();this.h=setInterval(this.F.bind(this,a),9E5)};
Bz.prototype.dh=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()};Bz.prototype.Ge=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.o=b.stack))};
var Dz=function(a,b){return(null==a.j?Promise.resolve():a.F(a.j)).then(function(){var c=b.map(function(d){d=Cz(a,d);var e=d.map(function(g){return g.events}).filter(function(g){return null!=g}),f=["["];d.map(function(g){return g.Jf}).forEach(function(g,h){0<h&&f.push(",");f.push(g)});f.push("]");return{events:new Blob(e,{type:"application/gzip"}),Jf:new Blob(f,{type:"application/json"})}});a.g=[];return c})};
Bz.prototype.F=function(a){var b=this;if(null!=this.l)return this.l;var c=zf(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.M);var e=Date.now();Object.assign(d,{startTime:b.u,endTime:e,activity:Xy(a),receiverWifiStatus:Array.from(b.D.h)});b.u=e;null!=b.C&&(Object.assign(d,{streamingErrorTime:b.C,streamingErrorMessage:b.m,streamingErrorCause:b.o}),b.C=null,b.m=null,b.o=null);return d});
return(this.l=Promise.all([c.then(function(d){return cz(a,d)}),c,dz(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,Jf:new Blob([JSON.stringify(Object.assign({tags:f},e))],{type:"application/json"})});b.g=Cz(b,b.G);b.l=null}))||Promise.resolve()};
var Cz=function(a,b){b-=2;for(var c=[],d=a.g.length-1;0<=d;--d){b-=a.g[d].Jf.size+1;if(0>b)break;c.push({events:null,Jf:a.g[d].Jf});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 Ez=function(a,b,c,d){d=void 0===d?null:d;Hj.call(this,b);var e=b.sb;this.F=e.sessionId;this.H=a;this.J=d;this.s=$a("mr.mirror.cast.Session");this.u=new Ly;this.o=new un("mirror.cast.SeqNumGenerator");this.m=new Hy(b.id);this.C=new wz(e,this.H,this.o,this.m,this.J);this.l=null;this.g=new Bz(a,e,c,new yz(this.F,this.o,this.m));this.D=null};t(Ez,Hj);k=Ez.prototype;
k.start=function(a){var b=this;return Ny(this.u,1,function(c){var d=fy();return b.C.start(a,b).then(function(){b.C.j.G&&(b.g.D.start(),Fz(b));d.end();b.D=gy();Ry(c,2);return b})})};k.stop=function(){var a=this;return Py(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?jz(a.l):Promise.resolve()}).then(function(){a.l=null;Ry(b,4)})})};
k.po=function(){var a=this,b={sessionId:this.F,seqNum:vn(this.o),type:"PRESENTATION",icons:[],title:Fj(this.tc)};this.s.info("Sending session metadata update to receiver: "+this.F);this.m.sendMessage(b).catch(function(c){a.s.K("Failed to send activity to sink: "+c.message)})};k.pg=function(a){this.g.pg(a)};k.dh=function(){return this.g.dh()};k.Ge=function(a,b){this.g.Ge(a,b);this.s.error(a,b);this.stop()};
var Gz=function(a,b){return Dz(a.g,b)},Fz=function(a){Hz(a).then(function(b){(b.g||[]).includes("video")?Iz(a,b):a.s.K(function(){return"Receiver incapable of Media Remoting: "+JSON.stringify(b)})}).catch(function(b){a.s.K("None/Invalid capabilites response. Media Remoting disabled.",b)})},Hz=function(a){return new Promise(function(b,c){var d={type:"GET_CAPABILITIES",sessionId:a.F,seqNum:vn(a.o)};a.s.info(function(){return"Sending GET_CAPABILITIES message: "+JSON.stringify(d)});Ky(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.s.info(function(){return"Ignoring CAPABILITIES_RESPONSE with different seqNum: "+JSON.stringify(e)}),!1;gb(a.s,function(){return"Received CAPABILITIES_RESPONSE: "+JSON.stringify(e)});b(e.capabilities);return!0})})},Iz=function(a,b){Ny(a.u,2,function(c){var d=a.h.sb.ge||"<UNKNOWN>";if(!d.startsWith("Chromecast")&&!d.startsWith("Eureka Dongle"))return a.s.K('HACK: Media Remoting disabled because the receiver model--"'+
(d+'" according to discovery--is not a Chromecast.')),Ry(c),Promise.resolve();a.l=new iz(a.h,b,a.H,a.o,a.m,a.J);return lz(a.l,a.L.bind(a),a).catch(function(e){a.s.error("Media Remoting start failed: "+e.message,e)}).then(function(){return Ry(c)})})};Ez.prototype.L=function(){var a=this;return Ny(this.u,2,function(b){return new Promise(function(c,d){xz(a.C).then(function(){Ry(b,3);a.G=!0;xj(a);c(a.V.bind(a))}).catch(function(e){a.Ge("Failed to suspend MediaStreamer before starting remoting",e);d(e)})})})};
Ez.prototype.V=function(){var a=this;return Ny(this.u,3,function(b){return new Promise(function(c,d){a.C.resume().then(function(){Ry(b,2);a.G=!1;xj(a);c()}).catch(function(e){a.Ge("Failed resume MediaStreamer after ending remoting mode",e);d(e)})})})};var Jz=function(){vj.call(this,"cast_streaming");this.m=this.F=this.M=this.H=this.l=null;this.ga=this.J="";this.na=this.u=!1;this.ua=this.Fa.bind(this);this.L=this.V=this.X=this.ub=this.C=null};t(Jz,vj);k=Jz.prototype;k.qg=function(a){this.u=a||!1;this.na=!0};k.getName=function(){return"cast_streaming"};
k.Wj=function(a,b,c,d,e){var f=this;if(!this.u)return vj.prototype.Wj.call(this,a,b,c,d,e);this.R.info("Start mirroring on route "+a.id);if(!this.na)return Ji(Error("Not initialized"));var g=new Promise(function(h,m){f.o().then(function(){if(tj(b)&&c.shouldCaptureVideo)return aj(!1).then(function(q){f.ga=q})}).then(function(){return e?e(a).g:a}).then(function(q){f.J=b;Kz(f,q);var r=f.H.createInterfacePtrAndBind(),u=f.M.createInterfacePtrAndBind(),A=Lz(q,c);Mz(f,q,b,d);if(!f.l)throw new Ni("Error to get mirroring service host");
f.F=new mojo.MirroringCastMessageChannelPtr;f.ub=fy();f.l.start(A,r,u,mojo.makeRequest(f.F));f.C=new Hj(a,f.j.L.bind(f.j));xj(f.C);Nz(f,q,b);f.V=function(){return h(q)};f.L=m}).catch(function(q){f.R.error("Mirroring launch error: "+q);f.Ef(void 0===q.reason?9:q.reason);m(q)})});return Ki(g)};k.wh=function(a,b){return new Ez(a,b,20969472,null)};k.Ug=function(){hy(0)};k.Rg=function(){hy(1)};k.Yh=function(){hy(2)};k.Sg=function(){tb("MediaRouter.CastStreaming.Session.End")};
k.Ef=function(a){ub("MediaRouter.CastStreaming.Start.Failure",a,Mi)};k.Tg=function(){tb("MediaRouter.CastStreaming.Stream.End")};
k.Ii=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&&oy(),e=[9351424];d&&e.push(20969472);return Gz(a,e).then(function(f){var g=f[f.length-1];f=tm(f[0].events).catch(function(h){b.R.error("Failed to persist events Blob.",h)});d&&0<g.events.size?ky(g.events,void 0,b.ou.bind(b)):c&&jy("stats.json",g.Jf,void 0,void 0);return f})})};
k.ou=function(a){if(a){a=ny();var b=Date.now();a.g=b}};k.Vj=function(a){if(this.u)return Xa();this.R.info("Received message to upload logs for "+a);return this.g?Gz(this.g,[20969472]).then(function(b){b=n(b).next().value;return 0==b.events.size?"":ky(b.events,a)}):Promise.resolve(Oz(this,a))};
var Oz=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 tm(new Blob),a.R.info("Uploading saved logs for feedback."),ky(c,b)};k=Jz.prototype;
k.onError=function(a){this.L&&(this.L(a),this.V=this.L=null,this.Ef(9));this.R.info("Mirroring service error: "+a);this.o()};k.didStart=function(){this.V&&(this.V(),this.V=this.L=null);this.ub&&(this.ub.end(),this.ub=null);this.X=gy();sj(this.J)?this.Ug():tj(this.J)?this.Rg():qj(this.J)&&this.Yh()};k.didStop=function(){this.o()};k.send=function(a){if(this.m){var b=JSON.parse(a.jsonFormatData);gb(this.R,function(){return"Sending message: "+JSON.stringify(b)});this.m.sendMessage(a.jsonFormatData,{namespace:a.messageNamespace})}};
k.pu=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.R.info("Received non-string as JSON"):(b.jsonFormatData=a.data,this.F.send(b))}};
var Kz=function(a,b){a.H=new mojo.Binding(mojo.MirroringSessionObserver,a,null);a.M=new mojo.Binding(mojo.MirroringCastMessageChannel,a,null);a.m=$w(b.id);a.m.onMessage=a.pu.bind(a)},Lz=function(a,b){var c=new mojo.MirroringSessionParameters;c.receiverAddress=new mojo.IPAddress;c.receiverAddress.addressBytes=a.sb.Yg.split(".").map(function(d){return parseInt(d,10)});c.receiverModelName=a.sb.ge;a=Pz(a.mediaSource);c.targetPlayoutDelay=Qz(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},Qz=function(a){if(!a)return null;a=Number(a.searchParams.get("streamingTargetPlayoutDelayMillis"));return isNaN(a)||0>=a?null:new mojo.TimeDelta({microseconds:1E3*a})},Pz=function(a){if(!a)return null;try{return new URL(a)}catch(b){return null}},Mz=function(a,b,c,d){a.l=new mojo.MirroringServiceHostPtr;b=b.sb.tabId||-1;sj(c)?a.j.getMirroringServiceHostForTab(b,
mojo.makeRequest(a.l)):tj(c)?a.j.getMirroringServiceHostForDesktop(-1,a.ga,mojo.makeRequest(a.l)):qj(c)?(b=new mojo.Url,b.url=c,a.j.getMirroringServiceHostForOffscreenTab(b,d||"",mojo.makeRequest(a.l))):a.l=null},Nz=function(a,b,c){sj(c)&&!chrome.tabs.onUpdated.hasListener(a.ua)&&chrome.tabs.onUpdated.addListener(a.ua);(sj(c)||qj(c))&&Aj(a.C,b.sb.tabId)};Jz.prototype.Fa=function(a,b,c){pj(14);this.C&&Cj(this.C,a,b,c)};
Jz.prototype.o=function(){chrome.tabs.onUpdated.removeListener(this.ua);return this.u?this.na?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.M&&(this.M.close(),this.M=null),Bj(this.j,this.C.h.id),this.C=null,this.ga=this.J="",this.X&&(this.X.end(),this.X=null),this.Sg(),Promise.resolve(!0)):Promise.resolve(!1):Promise.reject("Not initialized"):vj.prototype.o.call(this)};
Jz.prototype.pa=function(a,b,c,d,e,f){return this.u?Ji(Error("Mirroring service does not support updating stream")):vj.prototype.pa.call(this,a,b,c,d,e,f)};Jz.prototype.send=Jz.prototype.send;Jz.prototype.didStop=Jz.prototype.didStop;Jz.prototype.didStart=Jz.prototype.didStart;Jz.prototype.onError=Jz.prototype.onError;var Rz=new Jz;mj("mr.mirror.cast.Service",Rz);
