import{DataGrid,SortableDataGrid}from'../data_grid/data_grid.js';import{Widget,Utils,Toolbar,ListModel,SoftDropDown,TabbedPane,TreeOutline,Icon,Panel}from'../ui/ui.js';import{SDKModel}from'../sdk/sdk.js';import{Color,Settings,ObjectWrapper,UIString}from'../common/common.js';import{Platform}from'../host/host.js';import{FlameChart}from'../perf_ui/perf_ui.js';let PlayerEvent;const ProtocolTriggers={PlayerPropertiesChanged:Symbol('PlayerPropertiesChanged'),PlayerEventsAdded:Symbol('PlayerEventsAdded'),PlayerMessagesLogged:Symbol('PlayerMessagesLogged'),PlayerErrorsRaised:Symbol('PlayerErrorsRaised'),PlayersCreated:Symbol('PlayersCreated')};class MediaModel extends SDKModel.SDKModel{constructor(target){super(target);this._enabled=false;this._agent=target.mediaAgent();target.registerMediaDispatcher(this);}
resumeModel(){if(!this._enabled){return Promise.resolve();}
return this._agent.enable();}
ensureEnabled(){this._agent.enable();this._enabled=true;}
playerPropertiesChanged(playerId,properties){this.dispatchEventToListeners(ProtocolTriggers.PlayerPropertiesChanged,{playerId:playerId,properties:properties});}
playerEventsAdded(playerId,events){this.dispatchEventToListeners(ProtocolTriggers.PlayerEventsAdded,{playerId:playerId,events:events});}
playerMessagesLogged(playerId,messages){this.dispatchEventToListeners(ProtocolTriggers.PlayerMessagesLogged,{playerId:playerId,messages:messages});}
playerErrorsRaised(playerId,errors){this.dispatchEventToListeners(ProtocolTriggers.PlayerErrorsRaised,{playerId:playerId,errors:errors});}
playersCreated(playerIds){this.dispatchEventToListeners(ProtocolTriggers.PlayersCreated,playerIds);}}
SDKModel.SDKModel.register(MediaModel,SDKModel.Capability.DOM,false);var MediaModel$1=Object.freeze({__proto__:null,PlayerEvent:PlayerEvent,ProtocolTriggers:ProtocolTriggers,MediaModel:MediaModel});let EventDisplayColumnConfig;const MediaEventColumnKeys={Timestamp:'displayTimestamp',Event:'event',Value:'value'};class EventNode extends DataGrid.DataGridNode{constructor(event){super(event,false);this._expandableElement=null;}
createCell(columnId){const cell=this.createTD(columnId);const cellData=(this.data[columnId]);if(columnId===MediaEventColumnKeys.Value){const enclosed=cell.createChild('div','event-display-table-contents-json-wrapper');this._expandableElement=new SourceFrame.JSONView(new SourceFrame.ParsedJSON(cellData,'',''),true);this._expandableElement.markAsRoot();this._expandableElement.show(enclosed);}else{cell.classList.add('event-display-table-basic-text-table-entry');cell.createTextChild(cellData);}
return cell;}}
class PlayerEventsView extends Widget.VBox{constructor(){super();this.registerRequiredCSS('media/eventDisplayTable.css');this.contentElement.classList.add('event-display-table-contents-table-container');this._dataGrid=this._createDataGrid([{id:MediaEventColumnKeys.Timestamp,title:ls`Timestamp`,weight:1,sortingFunction:SortableDataGrid.SortableDataGrid.NumericComparator.bind(null,MediaEventColumnKeys.Timestamp)},{id:MediaEventColumnKeys.Event,title:ls`Event Name`,weight:2},{id:MediaEventColumnKeys.Value,title:ls`Value`,weight:7}]);this._firstEventTime=0;this._dataGrid.setStriped(true);this._dataGrid.asWidget().show(this.contentElement);}
_createDataGrid(headers){const gridColumnDescs=[];for(const headerDesc of headers){gridColumnDescs.push(PlayerEventsView._convertToGridDescriptor(headerDesc));}
const datagrid=new DataGrid.DataGridImpl({displayName:ls`Event Display`,columns:gridColumnDescs});datagrid.asWidget().contentElement.classList.add('no-border-top-datagrid');return datagrid;}
onEvent(event){if(this._firstEventTime===0){this._firstEventTime=event.timestamp;}
event=this._subtractFirstEventTime(event);const stringified=(event.value);try{const json=JSON.parse(stringified);event.event=json.event;delete json['event'];event.value=json;const node=new EventNode(event);this._dataGrid.rootNode().appendChild(node);}catch(e){}}
_subtractFirstEventTime(event){event.displayTimestamp=(event.timestamp-this._firstEventTime).toFixed(3);return event;}
static _convertToGridDescriptor(columnConfig){return({id:columnConfig.id,title:columnConfig.title,sortable:columnConfig.sortable,weight:columnConfig.weight||0,sort:DataGrid.Order.Ascending});}}
var EventDisplayTable=Object.freeze({__proto__:null,EventDisplayColumnConfig:EventDisplayColumnConfig,MediaEventColumnKeys:MediaEventColumnKeys,EventNode:EventNode,PlayerEventsView:PlayerEventsView});function FormatMillisecondsToSeconds(ms,decimalPlaces){const roundPower=Math.pow(10,3-decimalPlaces);const denominatorPower=Math.pow(10,Math.max(0,decimalPlaces));return`${Math.round(ms / roundPower) / denominatorPower} s`;}
class Bounds{constructor(initialLow,initialHigh,maxRange,minRange){this._min=initialLow;this._max=initialHigh;this._low=this._min;this._high=this._max;this._maxRange=maxRange;this._minRange=minRange;}
get low(){return this._low;}
get high(){return this._high;}
get min(){return this._min;}
get max(){return this._max;}
get range(){return this._high-this._low;}
_reassertBounds(){let needsAdjustment=true;while(needsAdjustment){needsAdjustment=false;if(this.range<this._minRange){needsAdjustment=true;const delta=(this._minRange-this.range)/2;this._high+=delta;this._low-=delta;}
if(this._low<this._min){needsAdjustment=true;this._low=this._min;}
if(this._high>this._max){needsAdjustment=true;this._high=this._max;}}}
zoomOut(amount,position){const range=this._high-this._low;const growSize=range*Math.pow(1.1,amount)-range;const lowEnd=growSize*position;const highEnd=growSize-lowEnd;this._low-=lowEnd;this._high+=highEnd;this._reassertBounds();}
zoomIn(amount,position){const range=this._high-this._low;if(this.range<=this._minRange){return;}
const shrinkSize=range-range/Math.pow(1.1,amount);const lowEnd=shrinkSize*position;const highEnd=shrinkSize-lowEnd;this._low+=lowEnd;this._high-=highEnd;this._reassertBounds();}
addMax(amount){const range=this._high-this._low;const isAtHighEnd=this._high===this._max;const isZoomedOut=this._low===this._min||range>=this._maxRange;this._max+=amount;if(isAtHighEnd&&isZoomedOut){this._high=this._max;}
this._reassertBounds();}
pushMaxAtLeastTo(time){if(this._max<time){this.addMax(time-this._max);return true;}
return false;}}
var TickingFlameChartHelpers=Object.freeze({__proto__:null,FormatMillisecondsToSeconds:FormatMillisecondsToSeconds,Bounds:Bounds});const defaultFont='11px '+Platform.fontFamily();const defaultColor='#444';const DefaultStyle={height:20,padding:2,collapsible:false,font:defaultFont,color:defaultColor,backgroundColor:'rgba(100 0 0 / 10%)',nestingLevel:0,itemsHeight:20,shareHeaderLine:false,useFirstLineForOverview:false,useDecoratorsForOverview:false};const HotColorScheme=['#ffba08','#faa307','#f48c06','#e85d04','#dc2f02','#d00000','#9d0208'];const ColdColorScheme=['#7400b8','#6930c3','#5e60ce','#5390d9','#4ea8de','#48bfe3','#56cfe1','#64dfdf'];function calculateFontColor(backgroundColor){if(Color.Color.parse(backgroundColor).hsla()[2]<0.5){return'#eee';}
return'#444';}
let EventHandlers;let EventProperties;class Event{constructor(timelineData,eventHandlers,eventProperties={}){this._timelineData=timelineData;this._setLive=eventHandlers.setLive;this._setComplete=eventHandlers.setComplete;this._updateMaxTime=eventHandlers.updateMaxTime;this._selfIndex=this._timelineData.entryLevels.length;this._live=false;const duration=eventProperties['duration']===undefined?0:eventProperties['duration'];this._timelineData.entryLevels.push(eventProperties['level']||0);this._timelineData.entryStartTimes.push(eventProperties['startTime']||0);this._timelineData.entryTotalTimes.push(duration);if(duration===-1){this.endTime=-1;}
this._title=eventProperties['name']||'';this._color=eventProperties['color']||HotColorScheme[0];this._fontColor=calculateFontColor(this._color);this._hoverData=eventProperties['hoverData']||{};}
decorate(htmlElement){htmlElement.createChild('span').textContent=`Name: ${this._title}`;htmlElement.createChild('br');const startTimeReadable=FormatMillisecondsToSeconds(this.startTime,2);if(this._live){htmlElement.createChild('span').textContent=`Duration: ${startTimeReadable} - LIVE!`;}else if(!isNaN(this.duration)){const durationReadable=FormatMillisecondsToSeconds(this.duration+this.startTime,2);htmlElement.createChild('span').textContent=`Duration: ${startTimeReadable} - ${durationReadable}`;}else{htmlElement.createChild('span').textContent=`Time: ${startTimeReadable}`;}}
set endTime(time){if(time===-1){this._timelineData.entryTotalTimes[this._selfIndex]=this._setLive(this._selfIndex);this._live=true;}else{this._live=false;const duration=time-this._timelineData.entryStartTimes[this._selfIndex];this._timelineData.entryTotalTimes[this._selfIndex]=duration;this._setComplete(this._selfIndex);this._updateMaxTime(time);}}
get id(){return this._selfIndex;}
set level(level){this._timelineData.entryLevels[this._selfIndex]=level;}
set title(text){this._title=text;}
get title(){return this._title;}
set color(color){this._color=color;this._fontColor=calculateFontColor(this._color);}
get color(){return this._color;}
get fontColor(){return this._fontColor;}
get startTime(){return this._timelineData.entryStartTimes[this._selfIndex];}
get duration(){return this._timelineData.entryTotalTimes[this._selfIndex];}
get live(){return this._live;}}
class TickingFlameChart extends Widget.VBox{constructor(){super();this._intervalTimer=null;this._lastTimestamp=0;this._canTick=true;this._ticking=false;this._isShown=false;this._bounds=new Bounds(0,1000,30000,1000);this._dataProvider=new TickingFlameChartDataProvider(this._bounds,this._updateMaxTime.bind(this));this._delegate=new TickingFlameChartDelegate();this._chartGroupExpansionSetting=Settings.Settings.instance().createSetting('mediaFlameChartGroupExpansion',{});this._chart=new FlameChart.FlameChart(this._dataProvider,this._delegate,this._chartGroupExpansionSetting);this._chart.disableRangeSelection();this._chart.bindCanvasEvent('wheel',this._onScroll.bind(this));this._chart.show(this.contentElement);}
addMarker(properties){properties['duration']=NaN;this.startEvent(properties);}
startEvent(properties){if(properties['duration']===undefined){properties['duration']=-1;}
const time=properties['startTime']||0;const event=this._dataProvider.startEvent(properties);this._updateMaxTime(time);return event;}
addGroup(name,depth){this._dataProvider.addGroup(name,depth);}
_updateMaxTime(time){if(this._bounds.pushMaxAtLeastTo(time)){this._updateRender();}}
_onScroll(e){const scrollTickCount=Math.round(e.deltaY/50);const scrollPositionRatio=e.offsetX/e.srcElement.clientWidth;if(scrollTickCount>0){this._bounds.zoomOut(scrollTickCount,scrollPositionRatio);}else{this._bounds.zoomIn(-scrollTickCount,scrollPositionRatio);}
this._updateRender();}
willHide(){this._isShown=false;if(this._ticking){this._stop();}}
wasShown(){this._isShown=true;if(this._canTick&&!this._ticking){this._start();}}
set canTick(allowed){this._canTick=allowed;if(this._ticking&&!allowed){this._stop();}
if(!this._ticking&&this._isShown&&allowed){this._start();}}
_start(){if(this._lastTimestamp===0){this._lastTimestamp=Date.now();}
if(this._intervalTimer!==null||this._stoppedPermanently){return;}
this._intervalTimer=setInterval(this._updateRender.bind(this),16);this._ticking=true;}
_stop(permanently=false){clearInterval(this._intervalTimer);this._intervalTimer=null;if(permanently){this._stoppedPermanently=true;}
this._ticking=false;}
_updateRender(){if(this._ticking){const currentTimestamp=Date.now();const duration=currentTimestamp-this._lastTimestamp;this._lastTimestamp=currentTimestamp;this._bounds.addMax(duration);}
this._dataProvider.updateMaxTime(this._bounds);this._chart.setWindowTimes(this._bounds.low,this._bounds.high,true);this._chart.scheduleUpdate();}}
class TickingFlameChartDelegate{constructor(){}
windowChanged(windowStartTime,windowEndTime,animate){}
updateRangeSelection(startTime,endTime){}
updateSelectedGroup(flameChart,group){}}
class TickingFlameChartDataProvider{constructor(initialBounds,updateMaxTime){this._updateMaxTimeHandle=updateMaxTime;this._bounds=initialBounds;this._liveEvents=new Set();this._eventMap=new Map();this._timelineData=new FlameChart.TimelineData([],[],[],[]);this._maxLevel=0;}
addGroup(name,depth){this._timelineData.groups.push({name:name,startLevel:this._maxLevel,expanded:true,selectable:false,style:DefaultStyle});this._maxLevel+=depth;}
startEvent(properties){properties['level']=properties['level']||0;if(properties['level']>this._maxLevel){throw`level ${properties['level']} is above the maximum allowed of ${this._maxLevel}`;}
const event=new Event(this._timelineData,{setLive:this._setLive.bind(this),setComplete:this._setComplete.bind(this),updateMaxTime:this._updateMaxTimeHandle},properties);this._eventMap.set(event.id,event);return event;}
_setLive(index){this._liveEvents.add(index);return this._bounds.max;}
_setComplete(index){this._liveEvents.delete(index);}
updateMaxTime(bounds){this._bounds=bounds;for(const eventID of this._liveEvents.entries()){this._eventMap.get(eventID[0]).endTime=-1;}}
maxStackDepth(){return this._maxLevel+1;}
timelineData(){return this._timelineData;}
minimumBoundary(){return this._bounds.low;}
totalTime(){return this._bounds.high;}
entryColor(index){return this._eventMap.get(index).color;}
textColor(index){return this._eventMap.get(index).fontColor;}
entryTitle(index){return this._eventMap.get(index).title;}
entryFont(index){return defaultFont;}
decorateEntry(index,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixelRatio){return false;}
forceDecoration(index){return false;}
prepareHighlightedEntryInfo(index){const element=createElement('div');this._eventMap.get(index).decorate(element);return element;}
formatValue(value,precision){value+=Math.round(this._bounds.low);if(this._bounds.range<2800){return FormatMillisecondsToSeconds(value,2);}
if(this._bounds.range<30000){return FormatMillisecondsToSeconds(value,1);}
return FormatMillisecondsToSeconds(value,0);}
canJumpToEntry(entryIndex){return false;}
navStartTimes(){return new Map();}}
var TickingFlameChart$1=Object.freeze({__proto__:null,HotColorScheme:HotColorScheme,ColdColorScheme:ColdColorScheme,TickingFlameChart:TickingFlameChart});const NO_NORMALIZED_TIMESTAMP=-1.5;class PlayerEventsTimeline extends TickingFlameChart{constructor(){super();this._normalizedTimestamp=NO_NORMALIZED_TIMESTAMP;this.addGroup('Playback Status',2);this.addGroup('Buffering Status',2);this._playbackStatusLastEvent=null;this._audioBufferingStateEvent=null;this._videoBufferingStateEvent=null;}
_ensureNoPreviousPlaybackEvent(normalizedTime){if(this._playbackStatusLastEvent!==null){this._playbackStatusLastEvent.endTime=normalizedTime;this._playbackStatusLastEvent=null;}}
_onPlaybackEvent(event,normalizedTime){switch(event.event){case'kPlay':this.canTick=true;this._ensureNoPreviousPlaybackEvent(normalizedTime);this._playbackStatusLastEvent=this.startEvent({level:0,startTime:normalizedTime,name:'Play'});break;case'kPause':this._ensureNoPreviousPlaybackEvent(normalizedTime);this._playbackStatusLastEvent=this.startEvent({level:0,startTime:normalizedTime,name:'Pause',color:HotColorScheme[1]});break;case'kWebMediaPlayerDestroyed':this.canTick=false;this._ensureNoPreviousPlaybackEvent(normalizedTime);this.addMarker({level:1,startTime:normalizedTime,name:'Destroyed',color:HotColorScheme[4]});break;case'kSuspended':this.canTick=false;this._ensureNoPreviousPlaybackEvent(normalizedTime);this._playbackStatusLastEvent=this.startEvent({level:1,startTime:normalizedTime,name:'Suspended',color:HotColorScheme[3]});break;case'kEnded':this._ensureNoPreviousPlaybackEvent(normalizedTime);this._playbackStatusLastEvent=this.startEvent({level:1,startTime:normalizedTime,name:'Ended',color:HotColorScheme[2]});break;default:throw`_onPlaybackEvent cant handle ${event.event}`;}}
_bufferedEnough(state){return state['state']==='BUFFERING_HAVE_ENOUGH';}
_onBufferingStatus(event,normalizedTime){let audioState=null;let videoState=null;switch(event.event){case'kBufferingStateChanged':audioState=event.value['audio_buffering_state'];videoState=event.value['video_buffering_state'];if(audioState){if(this._audioBufferingStateEvent!==null){this._audioBufferingStateEvent.endTime=normalizedTime;this._audioBufferingStateEvent=null;}
if(!this._bufferedEnough(audioState)){this._audioBufferingStateEvent=this.startEvent({level:3,startTime:normalizedTime,name:'Audio Buffering',color:ColdColorScheme[1],});}}
if(videoState){if(this._videoBufferingStateEvent!==null){this._videoBufferingStateEvent.endTime=normalizedTime;this._videoBufferingStateEvent=null;}
if(!this._bufferedEnough(videoState)){this._videoBufferingStateEvent=this.startEvent({level:2,startTime:normalizedTime,name:'Video Buffering',color:ColdColorScheme[0],});}}
break;default:throw`_onPlaybackEvent cant handle ${event.event}`;}}
onEvent(event){if(this._normalizedTimestamp===NO_NORMALIZED_TIMESTAMP){this._normalizedTimestamp=event.timestamp;}
const inMilliseconds=(event.timestamp-this._normalizedTimestamp)*1000;switch(event.event){case'kPlay':case'kPause':case'kWebMediaPlayerDestroyed':case'kSuspended':case'kEnded':return this._onPlaybackEvent(event,inMilliseconds);case'kBufferingStateChanged':return this._onBufferingStatus(event,inMilliseconds);default:}}}
const MessageLevelBitfield={Error:0b0001,Warning:0b0010,Info:0b0100,Debug:0b1000,Default:0b0111,All:0b1111,Custom:0};let SelectableLevel;class MessageLevelSelector extends ObjectWrapper.ObjectWrapper{constructor(items,view){super();this._items=items;this._view=view;this._itemMap=new Map();this._hiddenLevels=[];this._bitFieldValue=MessageLevelBitfield.Default;this._savedBitFieldValue=MessageLevelBitfield.Default;this._defaultTitle=ls`Default`;this._customTitle=ls`Custom`;this._allTitle=ls`All`;}
defaultTitle(){return this._defaultTitle;}
setDefault(dropdown){dropdown.selectItem(this._items.at(0));}
populate(){this._items.insert(this._items.length,{title:this._defaultTitle,overwrite:true,stringValue:'',value:MessageLevelBitfield.Default});this._items.insert(this._items.length,{title:this._allTitle,overwrite:true,stringValue:'',value:MessageLevelBitfield.All});this._items.insert(this._items.length,{title:ls`Error`,overwrite:false,stringValue:'error',value:MessageLevelBitfield.Error});this._items.insert(this._items.length,{title:ls`Warning`,overwrite:false,stringValue:'warning',value:MessageLevelBitfield.Warning});this._items.insert(this._items.length,{title:ls`Info`,overwrite:false,stringValue:'info',value:MessageLevelBitfield.Info});this._items.insert(this._items.length,{title:ls`Debug`,overwrite:false,stringValue:'debug',value:MessageLevelBitfield.Debug});}
_updateCheckMarks(){this._hiddenLevels=[];for(const[key,item]of this._itemMap){if(!item.overwrite){if(item.element.firstChild){item.element.firstChild.remove();}
if(key&this._bitFieldValue){item.element.createChild('div').createTextChild('✓');}else{this._hiddenLevels.push(item.stringValue);}}}}
titleFor(item){if(item.overwrite){this._bitFieldValue=item.value;}else{this._bitFieldValue^=item.value;}
if(this._bitFieldValue===MessageLevelBitfield.Default){return this._defaultTitle;}
if(this._bitFieldValue===MessageLevelBitfield.All){return this._allTitle;}
const potentialMatch=this._itemMap.get(this._bitFieldValue);if(potentialMatch){return potentialMatch.title;}
return this._customTitle;}
createElementForItem(item){const element=document.createElementWithClass('div');const shadowRoot=Utils.createShadowRootWithCoreStyles(element,'media/playerMessagesView.css');const container=shadowRoot.createChild('div','media-messages-level-dropdown-element');const checkBox=container.createChild('div','media-messages-level-dropdown-checkbox');const text=container.createChild('span','media-messages-level-dropdown-text');text.createTextChild(item.title);item.element=checkBox;this._itemMap.set(item.value,item);this._updateCheckMarks();this._view.regenerateMessageDisplayCss(this._hiddenLevels);return element;}
isItemSelectable(item){return true;}
itemSelected(item){this._updateCheckMarks();this._view.regenerateMessageDisplayCss(this._hiddenLevels);}
highlightedItemChanged(from,to,fromElement,toElement){}}
class PlayerMessagesView extends Widget.VBox{constructor(){super();this.registerRequiredCSS('media/playerMessagesView.css');this._headerPanel=this.contentElement.createChild('div','media-messages-header');this._bodyPanel=this.contentElement.createChild('div','media-messages-body');this._buildToolbar();}
_buildToolbar(){const toolbar=new Toolbar.Toolbar('media-messages-toolbar',this._headerPanel);toolbar.appendText(ls`Log Level:`);toolbar.appendToolbarItem(this._createDropdown());toolbar.appendSeparator();toolbar.appendToolbarItem(this._createFilterInput());}
_createDropdown(){const items=new ListModel.ListModel();this._messageLevelSelector=new MessageLevelSelector(items,this);const dropDown=new SoftDropDown.SoftDropDown(items,this._messageLevelSelector);dropDown.setRowHeight(18);this._messageLevelSelector.populate();this._messageLevelSelector.setDefault(dropDown);const dropDownItem=new Toolbar.ToolbarItem(dropDown.element);dropDownItem.element.classList.add('toolbar-has-dropdown');dropDownItem.setEnabled(true);dropDownItem.setTitle(this._messageLevelSelector.defaultTitle());return dropDownItem;}
_createFilterInput(){const filterInput=new Toolbar.ToolbarInput(ls`filter log messages`);filterInput.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,this._filterByString,this);return filterInput;}
regenerateMessageDisplayCss(hiddenLevels){const messages=this._bodyPanel.getElementsByClassName('media-messages-message-container');for(const message of messages){if(this._matchesHiddenLevels(message,hiddenLevels)){message.classList.add('media-messages-message-unselected');}else{message.classList.remove('media-messages-message-unselected');}}}
_matchesHiddenLevels(element,hiddenLevels){for(const level of hiddenLevels){if(element.classList.contains('media-message-'+level)){return true;}}
return false;}
_filterByString(userStringData){const userString=userStringData.data;const messages=this._bodyPanel.getElementsByClassName('media-messages-message-container');for(const message of messages){if(userString===''){message.classList.remove('media-messages-message-filtered');}else if(message.textContent.includes(userString)){message.classList.remove('media-messages-message-filtered');}else{message.classList.add('media-messages-message-filtered');}}}
addMessage(message){const container=this._bodyPanel.createChild('div','media-messages-message-container media-message-'+message.level);container.createTextChild(message.message);}}
const PlayerPropertyKeys={kResolution:'kResolution',kTotalBytes:'kTotalBytes',kBitrate:'kBitrate',kMaxDuration:'kMaxDuration',kStartTime:'kStartTime',kIsVideoEncrypted:'kIsVideoEncrypted',kIsStreaming:'kIsStreaming',kFrameUrl:'kFrameUrl',kFrameTitle:'kFrameTitle',kIsSingleOrigin:'kIsSingleOrigin',kIsRangeHeaderSupported:'kIsRangeHeaderSupported',kVideoDecoderName:'kVideoDecoderName',kAudioDecoderName:'kAudioDecoderName',kIsPlatformVideoDecoder:'kIsPlatformVideoDecoder',kIsPlatformAudioDecoder:'kIsPlatformAudioDecoder',kIsVideoDecryptingDemuxerStream:'kIsVideoDecryptingDemuxerStream',kIsAudioDecryptingDemuxerStream:'kIsAudioDecryptingDemuxerStream',kAudioTracks:'kAudioTracks',kVideoTracks:'kVideoTracks',kFramerate:'kFramerate',kVideoPlaybackRoughness:'kVideoPlaybackRoughness',};class PropertyRenderer extends Widget.VBox{constructor(title){super();this.contentElement.classList.add('media-property-renderer');this._title=this.contentElement.createChild('span','media-property-renderer-title');this._contents=this.contentElement.createChild('span','media-property-renderer-contents');this._title.createTextChild(title);this._title=title;this._value=null;this._pseudo_color_protection_element=null;this.contentElement.classList.add('media-property-renderer-hidden');}
updateData(propname,propvalue){if(propvalue===''||propvalue===null){return this._updateData(propname,null);}
try{propvalue=JSON.parse(propvalue);}catch(err){}
return this._updateData(propname,propvalue);}
_updateData(propname,propvalue){if(propvalue===null){this.changeContents(null);}else if(this._value===propvalue){return;}else{this._value=propvalue;this.changeContents(propvalue);}}
changeContents(value){if(value===null){this.contentElement.classList.add('media-property-renderer-hidden');if(this._pseudo_color_protection_element===null){this._pseudo_color_protection_element=document.createElement('div');this._pseudo_color_protection_element.classList.add('media-property-renderer');this._pseudo_color_protection_element.classList.add('media-property-renderer-hidden');this.contentElement.parentNode.insertBefore(this._pseudo_color_protection_element,this.contentElement);}}else{if(this._pseudo_color_protection_element!==null){this._pseudo_color_protection_element.remove();this._pseudo_color_protection_element=null;}
this.contentElement.classList.remove('media-property-renderer-hidden');this._contents.removeChildren();const spanElement=createElement('span');spanElement.textContent=value;this._contents.appendChild(spanElement);}}}
class FormattedPropertyRenderer extends PropertyRenderer{constructor(title,formatfunction){super(UIString.UIString(title));this._formatfunction=formatfunction;}
_updateData(propname,propvalue){if(propvalue===null){this.changeContents(null);}else{this.changeContents(this._formatfunction(propvalue));}}}
class DefaultPropertyRenderer extends PropertyRenderer{constructor(title,default_text){super(UIString.UIString(title));this.changeContents(default_text);}}
class DimensionPropertyRenderer extends PropertyRenderer{constructor(title){super(UIString.UIString(title));this._width=0;this._height=0;}
_updateData(propname,propvalue){let needsUpdate=false;if(propname==='width'&&propvalue!==this._width){this._width=propvalue;needsUpdate=true;}
if(propname==='height'&&propvalue!==this._height){this._height=propvalue;needsUpdate=true;}
if(this._width===0||this._height===0){this.changeContents(null);}else if(needsUpdate){this.changeContents(`${this._width}×${this._height}`);}}}
class AttributesView extends Widget.VBox{constructor(elements){super();this.contentElement.classList.add('media-attributes-view');for(const element of elements){element.show(this.contentElement);}}}
class TrackManager{constructor(propertiesView,type){this._type=type;this._view=propertiesView;this._previousTabs=[];}
updateData(name,value){const tabs=this._view.GetTabs(this._type);const newTabs=(JSON.parse(value));let enumerate=1;for(const tabData of newTabs){this.addNewTab(tabs,tabData,enumerate);enumerate++;}}
addNewTab(tabs,data,index){}}
class VideoTrackManager extends TrackManager{constructor(propertiesView){super(propertiesView,'video');}
addNewTab(tabs,tabData,tabNumber){const tabElements=[];for(const[name,data]of Object.entries(tabData)){tabElements.push(new DefaultPropertyRenderer(name,data));}
const newTab=new AttributesView(tabElements);tabs.addNewTab(tabNumber,newTab);}}
class AudioTrackManager extends TrackManager{constructor(propertiesView){super(propertiesView,'audio');}
addNewTab(tabs,tabData,tabNumber){const tabElements=[];for(const[name,data]of Object.entries(tabData)){tabElements.push(new DefaultPropertyRenderer(name,data));}
const newTab=new AttributesView(tabElements);tabs.addNewTab(tabNumber,newTab);}}
const TrackTypeLocalized={Video:UIString.UIString('Video'),Audio:UIString.UIString('Audio'),};class DecoderTrackMenu extends TabbedPane.TabbedPane{constructor(decoderName,informationalElement){super();this._decoderName=decoderName;const decoderLocalized=UIString.UIString('Decoder');const title=`${decoderName} ${decoderLocalized}`;const propertiesLocalized=UIString.UIString('Properties');const hoverText=`${title} ${propertiesLocalized}`;this.appendTab('DecoderProperties',title,informationalElement,hoverText);}
addNewTab(trackNumber,element){const localizedTrack=UIString.UIString('Track');const localizedTrackLower=UIString.UIString('track');this.appendTab(`Track${trackNumber}`,`${localizedTrack} #${trackNumber}`,element,`${this._decoderName} ${localizedTrackLower} #${trackNumber}`);}}
class PlayerPropertiesView extends Widget.VBox{constructor(){super();this.contentElement.classList.add('media-properties-frame');this.registerRequiredCSS('media/playerPropertiesView.css');this.populateAttributesAndElements();this._videoProperties=new AttributesView(this._mediaElements);this._videoDecoderProperties=new AttributesView(this._videoDecoderElements);this._audioDecoderProperties=new AttributesView(this._audioDecoderElements);this._videoProperties.show(this.contentElement);this._videoDecoderTabs=new DecoderTrackMenu(TrackTypeLocalized.Video,this._videoDecoderProperties);this._videoDecoderTabs.show(this.contentElement);this._audioDecoderTabs=new DecoderTrackMenu(TrackTypeLocalized.Audio,this._audioDecoderProperties);this._audioDecoderTabs.show(this.contentElement);}
GetTabs(type){if(type==='audio'){return this._audioDecoderTabs;}
if(type==='video'){return this._videoDecoderTabs;}
throw new Error('Unreachable');}
onProperty(property){const renderer=this._attributeMap.get(property.name);if(!renderer){throw new Error(`PlayerProperty ${property.name} not supported.`);}
renderer.updateData(property.name,property.value);}
formatKbps(bitsPerSecond){if(bitsPerSecond===''){return'0 kbps';}
const kbps=Math.floor(bitsPerSecond/1000);return`${kbps} kbps`;}
formatTime(seconds){if(seconds===''){return'0:00';}
const date=new Date(null);date.setSeconds(seconds);return date.toISOString().substr(11,8);}
formatFileSize(bytes){if(bytes===''){return'0 bytes';}
const power=Math.floor(Math.log(bytes)/Math.log(1024));const suffix=['bytes','kB','MB','GB','TB'][power];const bytesDecimal=(bytes/Math.pow(1000,power)).toFixed(2);return`${bytesDecimal} ${suffix}`;}
populateAttributesAndElements(){this._mediaElements=[];this._videoDecoderElements=[];this._audioDecoderElements=[];this._attributeMap=new Map();const resolution=new PropertyRenderer(ls`Resolution`);this._mediaElements.push(resolution);this._attributeMap.set(PlayerPropertyKeys.kResolution,resolution);const fileSize=new FormattedPropertyRenderer(ls`File Size`,this.formatFileSize);this._mediaElements.push(fileSize);this._attributeMap.set(PlayerPropertyKeys.kTotalBytes,fileSize);const bitrate=new FormattedPropertyRenderer(ls`Bitrate`,this.formatKbps);this._mediaElements.push(bitrate);this._attributeMap.set(PlayerPropertyKeys.kBitrate,bitrate);const duration=new FormattedPropertyRenderer(ls`Duration`,this.formatTime);this._mediaElements.push(duration);this._attributeMap.set(PlayerPropertyKeys.kMaxDuration,duration);const startTime=new PropertyRenderer(ls`Start Time`);this._mediaElements.push(startTime);this._attributeMap.set(PlayerPropertyKeys.kStartTime,startTime);const streaming=new PropertyRenderer(ls`Streaming`);this._mediaElements.push(streaming);this._attributeMap.set(PlayerPropertyKeys.kIsStreaming,streaming);const frameUrl=new PropertyRenderer(ls`Playback Frame URL`);this._mediaElements.push(frameUrl);this._attributeMap.set(PlayerPropertyKeys.kFrameUrl,frameUrl);const frameTitle=new PropertyRenderer(ls`Playback Frame Title`);this._mediaElements.push(frameTitle);this._attributeMap.set(PlayerPropertyKeys.kFrameTitle,frameTitle);const singleOrigin=new PropertyRenderer(ls`Is Single Origin Playback`);this._mediaElements.push(singleOrigin);this._attributeMap.set(PlayerPropertyKeys.kIsSingleOrigin,singleOrigin);const rangeHeaders=new PropertyRenderer(ls`Range Header Support`);this._mediaElements.push(rangeHeaders);this._attributeMap.set(PlayerPropertyKeys.kIsRangeHeaderSupported,rangeHeaders);const frameRate=new PropertyRenderer(ls`Frame Rate`);this._mediaElements.push(frameRate);this._attributeMap.set(PlayerPropertyKeys.kFramerate,frameRate);const roughness=new PropertyRenderer(ls`Video Playback Roughness`);this._mediaElements.push(roughness);this._attributeMap.set(PlayerPropertyKeys.kVideoPlaybackRoughness,roughness);const decoderName=new DefaultPropertyRenderer(ls`Decoder Name`,ls`No Decoder`);this._videoDecoderElements.push(decoderName);this._attributeMap.set(PlayerPropertyKeys.kVideoDecoderName,decoderName);const videoPlatformDecoder=new PropertyRenderer(ls`Hardware Decoder`);this._videoDecoderElements.push(videoPlatformDecoder);this._attributeMap.set(PlayerPropertyKeys.kIsPlatformVideoDecoder,videoPlatformDecoder);const videoDDS=new PropertyRenderer(ls`Decrypting Demuxer`);this._videoDecoderElements.push(videoDDS);this._attributeMap.set(PlayerPropertyKeys.kIsVideoDecryptingDemuxerStream,videoDDS);const videoTrackManager=new VideoTrackManager(this);this._attributeMap.set(PlayerPropertyKeys.kVideoTracks,videoTrackManager);const audioDecoder=new DefaultPropertyRenderer(ls`Decoder Name`,ls`No Decoder`);this._audioDecoderElements.push(audioDecoder);this._attributeMap.set(PlayerPropertyKeys.kAudioDecoderName,audioDecoder);const audioPlatformDecoder=new PropertyRenderer(ls`Hardware Decoder`);this._audioDecoderElements.push(audioPlatformDecoder);this._attributeMap.set(PlayerPropertyKeys.kIsPlatformAudioDecoder,audioPlatformDecoder);const audioDDS=new PropertyRenderer(ls`Decrypting Demuxer`);this._audioDecoderElements.push(audioDDS);this._attributeMap.set(PlayerPropertyKeys.kIsAudioDecryptingDemuxerStream,audioDDS);const audioTrackManager=new AudioTrackManager(this);this._attributeMap.set(PlayerPropertyKeys.kAudioTracks,audioTrackManager);}}
var PlayerPropertiesView$1=Object.freeze({__proto__:null,PlayerPropertyKeys:PlayerPropertyKeys,PropertyRenderer:PropertyRenderer,FormattedPropertyRenderer:FormattedPropertyRenderer,DefaultPropertyRenderer:DefaultPropertyRenderer,DimensionPropertyRenderer:DimensionPropertyRenderer,AttributesView:AttributesView,TrackManager:TrackManager,VideoTrackManager:VideoTrackManager,AudioTrackManager:AudioTrackManager,PlayerPropertiesView:PlayerPropertiesView});const PlayerDetailViewTabs={Events:'events',Properties:'properties',Messages:'messages',Timeline:'timeline'};class PlayerDetailView extends TabbedPane.TabbedPane{constructor(){super();this._eventView=new PlayerEventsView();this._propertyView=new PlayerPropertiesView();this._messageView=new PlayerMessagesView();this._timelineView=new PlayerEventsTimeline();this.appendTab(PlayerDetailViewTabs.Properties,UIString.UIString('Properties'),this._propertyView,UIString.UIString('Player properties'));this.appendTab(PlayerDetailViewTabs.Events,UIString.UIString('Events'),this._eventView,UIString.UIString('Player events'));this.appendTab(PlayerDetailViewTabs.Messages,UIString.UIString('Messages'),this._messageView,UIString.UIString('Player messages'));this.appendTab(PlayerDetailViewTabs.Timeline,UIString.UIString('Timeline'),this._timelineView,UIString.UIString('Player timeline'));}
onProperty(property){this._propertyView.onProperty(property);}
onError(error){}
onMessage(message){this._messageView.addMessage(message);}
onEvent(event){this._eventView.onEvent(event);this._timelineView.onEvent(event);}}
var PlayerDetailView$1=Object.freeze({__proto__:null,PlayerDetailViewTabs:PlayerDetailViewTabs,PlayerDetailView:PlayerDetailView});let PlayerStatus;let PlayerStatusMapElement;class PlayerEntryTreeElement extends TreeOutline.TreeElement{constructor(playerStatus,displayContainer){super(playerStatus.playerTitle,false);this.titleFromUrl=true;this._playerStatus=playerStatus;this._displayContainer=displayContainer;this.setLeadingIcons([Icon.Icon.create('smallicon-videoplayer-playing','media-player')]);this.listItemElement.classList.add('player-entry-tree-element');}
onselect(selectedByUser){this._displayContainer.renderMainPanel(this._playerStatus.playerID);return true;}}
class PlayerListView extends Widget.VBox{constructor(mainContainer){super(true);this._playerStatuses=new Map();this._mainContainer=mainContainer;this._sidebarTree=new TreeOutline.TreeOutlineInShadow();this.contentElement.appendChild(this._sidebarTree.element);this._sidebarTree.registerRequiredCSS('media/playerListView.css');this._audioDevices=this._addListSection(Common.UIString('Audio I/O'));this._videoDevices=this._addListSection(Common.UIString('Video Capture Devices'));this._playerList=this._addListSection(Common.UIString('Players'));this._playerList.listItemElement.classList.add('player-entry-header');}
_addListSection(title){const treeElement=new TreeOutline.TreeElement(title,true);treeElement.listItemElement.classList.add('storage-group-list-item');treeElement.setCollapsible(false);treeElement.selectable=false;this._sidebarTree.appendChild(treeElement);return treeElement;}
addMediaElementItem(playerID){const playerStatus={playerTitle:playerID,playerID:playerID,exists:true,playing:false,titleEdited:false};const playerElement=new PlayerEntryTreeElement(playerStatus,this._mainContainer);this._playerStatuses.set(playerID,playerElement);this._playerList.appendChild(playerElement);}
setMediaElementPlayerTitle(playerID,newTitle,isTitleExtractedFromUrl){if(this._playerStatuses.has(playerID)){const sidebarEntry=this._playerStatuses.get(playerID);if(!isTitleExtractedFromUrl||sidebarEntry.titleFromUrl){sidebarEntry.title=newTitle;sidebarEntry.titleFromUrl=isTitleExtractedFromUrl;}}}
setMediaElementPlayerIcon(playerID,iconName){if(this._playerStatuses.has(playerID)){const sidebarEntry=this._playerStatuses.get(playerID);sidebarEntry.setLeadingIcons([Icon.Icon.create('smallicon-videoplayer-'+iconName,'media-player')]);}}
onProperty(playerID,property){if(property.name===PlayerPropertyKeys.kFrameTitle&&property.value){this.setMediaElementPlayerTitle(playerID,(property.value),false);}
if(property.name===PlayerPropertyKeys.kFrameUrl){const url_path_component=property.value.substring(property.value.lastIndexOf('/')+1);this.setMediaElementPlayerTitle(playerID,url_path_component,true);}}
onError(playerID,error){}
onMessage(playerID,message){}
onEvent(playerID,event){if(event.value==='PLAY'){this.setMediaElementPlayerIcon(playerID,'playing');}else if(event.value==='PAUSE'){this.setMediaElementPlayerIcon(playerID,'paused');}else if(event.value==='WEBMEDIAPLAYER_DESTROYED'){this.setMediaElementPlayerIcon(playerID,'destroyed');}}}
var PlayerListView$1=Object.freeze({__proto__:null,PlayerStatus:PlayerStatus,PlayerStatusMapElement:PlayerStatusMapElement,PlayerEntryTreeElement:PlayerEntryTreeElement,PlayerListView:PlayerListView});class TriggerHandler{onProperty(property){}
onError(error){}
onMessage(message){}
onEvent(event){}}
class TriggerDispatcher{onProperty(playerID,property){}
onError(playerID,error){}
onMessage(playerID,message){}
onEvent(playerID,event){}}
class MainView extends Panel.PanelWithSidebar{constructor(){super('Media');this.registerRequiredCSS('media/mediaView.css');this._detailPanels=new Map();this._deletedPlayers=new Set();this._sidebar=new PlayerListView(this);this._sidebar.show(this.panelSidebarElement());SDKModel.TargetManager.instance().observeModels(MediaModel,this);}
renderMainPanel(playerID){if(!this._detailPanels.has(playerID)){return;}
this.splitWidget().mainWidget().detachChildWidgets();this._detailPanels.get(playerID).show(this.mainElement());}
wasShown(){super.wasShown();for(const model of SDKModel.TargetManager.instance().models(MediaModel)){this._addEventListeners(model);}}
willHide(){for(const model of SDKModel.TargetManager.instance().models(MediaModel)){this._removeEventListeners(model);}}
modelAdded(mediaModel){if(this.isShowing()){this._addEventListeners(mediaModel);}}
modelRemoved(mediaModel){this._removeEventListeners(mediaModel);}
_addEventListeners(mediaModel){mediaModel.ensureEnabled();mediaModel.addEventListener(ProtocolTriggers.PlayerPropertiesChanged,this._propertiesChanged,this);mediaModel.addEventListener(ProtocolTriggers.PlayerEventsAdded,this._eventsAdded,this);mediaModel.addEventListener(ProtocolTriggers.PlayerMessagesLogged,this._messagesLogged,this);mediaModel.addEventListener(ProtocolTriggers.PlayerErrorsRaised,this._errorsRaised,this);mediaModel.addEventListener(ProtocolTriggers.PlayersCreated,this._playersCreated,this);}
_removeEventListeners(mediaModel){mediaModel.removeEventListener(ProtocolTriggers.PlayerPropertiesChanged,this._propertiesChanged,this);mediaModel.removeEventListener(ProtocolTriggers.PlayerEventsAdded,this._eventsAdded,this);mediaModel.removeEventListener(ProtocolTriggers.PlayerMessagesLogged,this._messagesLogged,this);mediaModel.removeEventListener(ProtocolTriggers.PlayerErrorsRaised,this._errorsRaised,this);mediaModel.removeEventListener(ProtocolTriggers.PlayersCreated,this._playersCreated,this);}
_onPlayerCreated(playerID){this._sidebar.addMediaElementItem(playerID);this._detailPanels.set(playerID,new PlayerDetailView());}
_propertiesChanged(event){for(const property of event.data.properties){this.onProperty(event.data.playerId,property);}}
_eventsAdded(event){for(const ev of event.data.events){this.onEvent(event.data.playerId,ev);}}
_messagesLogged(event){for(const message of event.data.messages){this.onMessage(event.data.playerId,message);}}
_errorsRaised(event){for(const error of event.data.errors){this.onError(event.data.playerId,error);}}
_shouldPropagate(playerID){return!this._deletedPlayers.has(playerID)&&this._detailPanels.has(playerID);}
onProperty(playerID,property){if(!this._shouldPropagate(playerID)){return;}
this._sidebar.onProperty(playerID,property);this._detailPanels.get(playerID).onProperty(property);}
onError(playerID,error){if(!this._shouldPropagate(playerID)){return;}
this._sidebar.onError(playerID,error);this._detailPanels.get(playerID).onError(error);}
onMessage(playerID,message){if(!this._shouldPropagate(playerID)){return;}
this._sidebar.onMessage(playerID,message);this._detailPanels.get(playerID).onMessage(message);}
onEvent(playerID,event){if(!this._shouldPropagate(playerID)){return;}
this._sidebar.onEvent(playerID,event);this._detailPanels.get(playerID).onEvent(event);}
_playersCreated(event){const playerlist=(event.data);for(const playerID of playerlist){this._onPlayerCreated(playerID);}}}
var MainView$1=Object.freeze({__proto__:null,TriggerHandler:TriggerHandler,TriggerDispatcher:TriggerDispatcher,MainView:MainView});export{MainView$1 as MainView,MediaModel$1 as MediaModel,PlayerDetailView$1 as PlayerDetailView,EventDisplayTable as PlayerEventsView,PlayerListView$1 as PlayerListView,PlayerPropertiesView$1 as PlayerPropertiesView,TickingFlameChart$1 as TickingFlameChart,TickingFlameChartHelpers};