is rendering right now, so we provide a
// stateOverride to evaluate the condition in that context.
liveConfig = getOverriddenConfig(
this.conditionsManagerEpoch.manager,
{ live: this.nonOverriddenLiveConfig },
{
configOverrides: this.overrides,
stateOverrides: { camera: cameraID },
schema: liveConfigAbsoluteRootSchema,
},
).live;
} catch (ev) {
return dispatchFrigateCardErrorEvent(this, ev);
}
const cameraMetadata = this.cameraManager.getCameraMetadata(cameraID);
const view = this.viewManagerEpoch?.manager.getView();
return html`
this.cameraManager?.getCameraEndpoints(cameraID) ?? undefined,
)}
.label=${cameraMetadata?.title ?? ''}
.liveConfig=${liveConfig}
.hass=${this.hass}
.cardWideConfig=${this.cardWideConfig}
.zoomSettings=${view?.context?.zoom?.[cameraID]?.requested}
@frigate-card:zoom:change=${(ev: CustomEvent) =>
handleZoomSettingsObservedEvent(
ev,
this.viewManagerEpoch?.manager,
cameraID,
)}
>
`;
}
protected _getCameraIDsOfNeighbors(): [string | null, string | null] {
const cameraIDs = this.cameraManager
? [...this.cameraManager?.getStore().getCameraIDsWithCapability('live')]
: [];
const view = this.viewManagerEpoch?.manager.getView();
if (this.viewFilterCameraID || cameraIDs.length <= 1 || !view || !this.hass) {
return [null, null];
}
const cameraID = this.viewFilterCameraID ?? view.camera;
const currentIndex = cameraIDs.indexOf(cameraID);
if (currentIndex < 0) {
return [null, null];
}
return [
cameraIDs[currentIndex > 0 ? currentIndex - 1 : cameraIDs.length - 1],
cameraIDs[currentIndex + 1 < cameraIDs.length ? currentIndex + 1 : 0],
];
}
protected _getSubstreamCameraID(cameraID: string, view?: View | null): string {
return view?.context?.live?.overrides?.get(cameraID) ?? cameraID;
}
protected render(): TemplateResult | void {
const view = this.viewManagerEpoch?.manager.getView();
if (!this.overriddenLiveConfig || !this.hass || !view || !this.cameraManager) {
return;
}
const [slides, cameraToSlide] = this._getSlides();
this._cameraToSlide = cameraToSlide;
if (!slides.length) {
return;
}
const hasMultipleCameras = slides.length > 1;
const [prevID, nextID] = this._getCameraIDsOfNeighbors();
const cameraMetadataPrevious = prevID
? this.cameraManager.getCameraMetadata(this._getSubstreamCameraID(prevID, view))
: null;
const cameraMetadataNext = nextID
? this.cameraManager.getCameraMetadata(this._getSubstreamCameraID(nextID, view))
: null;
const forcePTZVisibility =
!this._mediaHasLoaded ||
(!!this.viewFilterCameraID && this.viewFilterCameraID !== view.camera) ||
view.context?.ptzControls?.enabled === false
? false
: view.context?.ptzControls?.enabled;
// Notes on the below:
// - guard() is used to avoid reseting the carousel unless the
// options/plugins actually change.
return html`
{
this._mediaHasLoaded = true;
}}
@frigate-card:media:unloaded=${() => {
this._mediaHasLoaded = false;
}}
>
{
this._setViewCameraID(prevID);
stopEventFromActivatingCardWideActions(ev);
}}
>
${slides}
{
this._setViewCameraID(nextID);
stopEventFromActivatingCardWideActions(ev);
}}
>
`;
}
protected _setMediaTarget(): void {
const view = this.viewManagerEpoch?.manager.getView();
const selectedCameraIndex = this._getSelectedCameraIndex();
if (this.viewFilterCameraID) {
this._mediaActionsController.setTarget(
selectedCameraIndex,
// Camera in this carousel is only selected if the camera from the
// view matches the filtered camera.
view?.camera === this.viewFilterCameraID,
);
} else {
// Carousel is not filtered, so the targeted camera is always selected.
this._mediaActionsController.setTarget(selectedCameraIndex, true);
}
}
public updated(changedProperties: PropertyValues): void {
super.updated(changedProperties);
let initialized = false;
if (!this._mediaActionsController.hasRoot() && this._refCarousel.value) {
this._mediaActionsController.initialize(this._refCarousel.value);
initialized = true;
}
// If the view has changed, or if the media actions controller has just been
// initialized, then call the necessary media action.
// See: https://github.com/dermotduffy/frigate-hass-card/issues/1626
if (initialized || changedProperties.has('viewManagerEpoch')) {
this._setMediaTarget();
}
}
static get styles(): CSSResultGroup {
return unsafeCSS(liveCarouselStyle);
}
}
@customElement(FRIGATE_CARD_LIVE_PROVIDER)
export class FrigateCardLiveProvider
extends LitElement
implements FrigateCardMediaPlayer
{
@property({ attribute: false })
public hass?: ExtendedHomeAssistant;
@property({ attribute: false })
public cameraConfig?: CameraConfig;
@property({ attribute: false })
public cameraEndpoints?: CameraEndpoints;
@property({ attribute: false })
public liveConfig?: LiveConfig;
// Whether or not to load the video for this camera. If `false`, no contents
// are rendered until this attribute is set to `true` (this is useful for lazy
// loading).
@property({ attribute: true, type: Boolean })
public load = false;
// Label that is used for ARIA support and as tooltip.
@property({ attribute: false })
public label = '';
@property({ attribute: false })
public cardWideConfig?: CardWideConfig;
@property({ attribute: false })
public microphoneStream?: MediaStream;
@property({ attribute: false })
public zoomSettings?: PartialZoomSettings | null;
@state()
protected _isVideoMediaLoaded = false;
protected _refProvider: Ref = createRef();
// A note on dynamic imports:
//
// We gather the dynamic live provider import promises and do not consider the
// update of the element complete until these imports have returned. Without
// this behavior calls to the media methods (e.g. `mute()`) may throw if the
// underlying code is not yet loaded.
//
// Test case: A card with a non-live view, but live pre-loaded, attempts to
// call mute() when the element first renders in the
// background. These calls fail without waiting for loading here.
protected _importPromises: Promise[] = [];
public async play(): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
await playMediaMutingIfNecessary(this, this._refProvider.value);
}
public async pause(): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
await this._refProvider.value?.pause();
}
public async mute(): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
await this._refProvider.value?.mute();
}
public async unmute(): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
await this._refProvider.value?.unmute();
}
public isMuted(): boolean {
return this._refProvider.value?.isMuted() ?? true;
}
public async seek(seconds: number): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
await this._refProvider.value?.seek(seconds);
}
public async setControls(controls?: boolean): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
await this._refProvider.value?.setControls(controls);
}
public isPaused(): boolean {
return this._refProvider.value?.isPaused() ?? true;
}
public async getScreenshotURL(): Promise {
await this.updateComplete;
await this._refProvider.value?.updateComplete;
return (await this._refProvider.value?.getScreenshotURL()) ?? null;
}
/**
* Get the fully resolved live provider.
* @returns A live provider (that is not 'auto').
*/
protected _getResolvedProvider(): Omit {
if (this.cameraConfig?.live_provider === 'auto') {
if (
this.cameraConfig?.webrtc_card?.entity ||
this.cameraConfig?.webrtc_card?.url
) {
return 'webrtc-card';
} else if (this.cameraConfig?.camera_entity) {
return 'ha';
} else if (this.cameraConfig?.frigate.camera_name) {
return 'jsmpeg';
}
return frigateCardConfigDefaults.cameras.live_provider;
}
return this.cameraConfig?.live_provider || 'image';
}
/**
* Determine if a camera image should be shown in lieu of the real stream
* whilst loading.
* @returns`true` if an image should be shown.
*/
protected _shouldShowImageDuringLoading(): boolean {
return (
!!this.cameraConfig?.camera_entity &&
!!this.hass &&
!!this.liveConfig?.show_image_during_load
);
}
public disconnectedCallback(): void {
this._isVideoMediaLoaded = false;
}
protected _videoMediaShowHandler(): void {
this._isVideoMediaLoaded = true;
}
protected willUpdate(changedProps: PropertyValues): void {
if (changedProps.has('load')) {
if (!this.load) {
this._isVideoMediaLoaded = false;
dispatchMediaUnloadedEvent(this);
}
}
if (changedProps.has('liveConfig')) {
if (this.liveConfig?.show_image_during_load) {
this._importPromises.push(import('./live-image.js'));
}
if (this.liveConfig?.zoomable) {
this._importPromises.push(import('./../zoomer.js'));
}
}
if (changedProps.has('cameraConfig')) {
const provider = this._getResolvedProvider();
if (provider === 'jsmpeg') {
this._importPromises.push(import('./live-jsmpeg.js'));
} else if (provider === 'ha') {
this._importPromises.push(import('./live-ha.js'));
} else if (provider === 'webrtc-card') {
this._importPromises.push(import('./live-webrtc-card.js'));
} else if (provider === 'image') {
this._importPromises.push(import('./live-image.js'));
} else if (provider === 'go2rtc') {
this._importPromises.push(import('./live-go2rtc.js'));
}
updateElementStyleFromMediaLayoutConfig(
this,
this.cameraConfig?.dimensions?.layout,
);
this.style.aspectRatio = aspectRatioToString({
ratio: this.cameraConfig?.dimensions?.aspect_ratio,
});
}
}
override async getUpdateComplete(): Promise {
// See 'A note on dynamic imports' above for explanation of why this is
// necessary.
const result = await super.getUpdateComplete();
await Promise.all(this._importPromises);
this._importPromises = [];
return result;
}
protected _useZoomIfRequired(template: TemplateResult): TemplateResult {
return this.liveConfig?.zoomable
? html`
this.cameraConfig?.dimensions?.layout
? {
pan: this.cameraConfig.dimensions.layout.pan,
zoom: this.cameraConfig.dimensions.layout.zoom,
}
: undefined,
)}
.settings=${this.zoomSettings}
@frigate-card:zoom:zoomed=${() => this.setControls(false)}
@frigate-card:zoom:unzoomed=${() => this.setControls()}
>
${template}
`
: template;
}
protected render(): TemplateResult | void {
if (!this.load || !this.hass || !this.liveConfig || !this.cameraConfig) {
return;
}
// Set title and ariaLabel from the provided label property.
this.title = this.label;
this.ariaLabel = this.label;
const provider = this._getResolvedProvider();
const showImageDuringLoading =
!this._isVideoMediaLoaded && this._shouldShowImageDuringLoading();
const providerClasses = {
hidden: showImageDuringLoading,
};
if (provider === 'ha' || provider === 'image') {
const stateObj = getStateObjOrDispatchError(this, this.hass, this.cameraConfig);
if (!stateObj) {
return;
}
if (stateObj.state === 'unavailable') {
dispatchMediaUnloadedEvent(this);
// An unavailable camera gets a message rendered in place vs dispatched,
// as this may be a common occurrence (e.g. Frigate cameras that stop
// receiving frames). Otherwise a single temporarily unavailable camera
// would render a whole carousel inoperable.
return renderMessage({
message: `${localize('error.live_camera_unavailable')}${
this.label ? `: ${this.label}` : ''
}`,
type: 'info',
icon: 'mdi:cctv-off',
dotdotdot: true,
});
}
}
return html`${this._useZoomIfRequired(html`
${showImageDuringLoading || provider === 'image'
? html` {
if (provider === 'image') {
// Only count the media has loaded if the required provider is
// the image (not just the temporary image shown during
// loading).
this._videoMediaShowHandler();
} else {
ev.stopPropagation();
}
}}
>
`
: html``}
${provider === 'ha'
? html`
`
: provider === 'go2rtc'
? html`
`
: provider === 'webrtc-card'
? html`
`
: provider === 'jsmpeg'
? html`
`
: html``}
`)}
${showImageDuringLoading && !this._isVideoMediaLoaded
? html``
: ''} `;
}
static get styles(): CSSResultGroup {
return unsafeCSS(liveProviderStyle);
}
}
declare global {
interface HTMLElementTagNameMap {
'frigate-card-live-provider': FrigateCardLiveProvider;
'frigate-card-live-carousel': FrigateCardLiveCarousel;
'frigate-card-live-grid': FrigateCardLiveGrid;
'frigate-card-live': FrigateCardLive;
}
}