All files / audio AudioPool.ts

100% Statements 84/84
100% Branches 17/17
100% Functions 25/25
100% Lines 81/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267                                                58x 58x 58x 58x 58x     58x 58x 58x             58x 226x               41x   41x   41x   5x 2x   3x 3x       38x 38x             6x 1x 1x     5x 5x 5x 5x               3x 6x 6x 6x   3x             20x                           5x 5x       228x 228x       3x 3x               105x 105x                           48x 48x 1x     47x   47x   197x 197x 197x 197x     5x 5x         47x 47x             3x             21x 21x 1x 1x   20x             3x 3x 1x 1x   2x             2x             6x 6x             15x 15x 4x   15x                 2x 2x 1x 1x 1x   1x             3x 1x             7x             4x      
/**
 * AudioPool - Object pooling for audio instances
 * Reduces memory allocation overhead for frequently played sounds
 */
 
export interface PoolStatistics {
  readonly available: number;
  readonly inUse: number;
  readonly total: number;
  readonly acquisitions: number;
  readonly releases: number;
  readonly created: number;
}
 
export interface PoolConfig {
  readonly initialSize?: number;
  readonly maxSize?: number;
  readonly autoExpand?: boolean;
}
 
/**
 * Generic object pool implementation
 */
export class ObjectPool<T> {
  private available: T[] = [];
  private inUse = new Set<T>();
  private acquisitionCount = 0;
  private releaseCount = 0;
  private createdCount = 0;
 
  constructor(
    private readonly factory: () => T,
    private readonly reset: (obj: T) => void,
    private readonly config: Required<PoolConfig> = {
      initialSize: 10,
      maxSize: 100,
      autoExpand: true,
    }
  ) {
    // Pre-populate pool
    for (let i = 0; i < config.initialSize; i++) {
      this.available.push(this.createObject());
    }
  }
 
  /**
   * Acquire an object from the pool
   */
  acquire(): T | null {
    this.acquisitionCount++;
 
    let obj = this.available.pop();
 
    if (!obj) {
      // Pool is empty
      if (this.config.autoExpand && this.canExpand()) {
        obj = this.createObject();
      } else {
        console.warn("Pool exhausted and cannot expand");
        return null;
      }
    }
 
    this.inUse.add(obj);
    return obj;
  }
 
  /**
   * Release an object back to the pool
   */
  release(obj: T): void {
    if (!this.inUse.has(obj)) {
      console.warn("Attempted to release object not in use");
      return;
    }
 
    this.releaseCount++;
    this.reset(obj);
    this.inUse.delete(obj);
    this.available.push(obj);
  }
 
  /**
   * Release all objects back to the pool
   * Resets all in-use objects and returns them to the available pool
   */
  releaseAll(): void {
    this.inUse.forEach((obj) => {
      this.releaseCount++;
      this.reset(obj);
      this.available.push(obj);
    });
    this.inUse.clear();
  }
 
  /**
   * Get pool statistics
   */
  getStatistics(): PoolStatistics {
    return {
      available: this.available.length,
      inUse: this.inUse.size,
      total: this.available.length + this.inUse.size,
      acquisitions: this.acquisitionCount,
      releases: this.releaseCount,
      created: this.createdCount,
    };
  }
 
  /**
   * Clear the pool and dispose all objects
   */
  clear(): void {
    this.available = [];
    this.inUse.clear();
  }
 
  private createObject(): T {
    this.createdCount++;
    return this.factory();
  }
 
  private canExpand(): boolean {
    const total = this.available.length + this.inUse.size;
    return total < this.config.maxSize;
  }
}
 
/**
 * Specialized audio pool for HTMLAudioElement instances
 */
export class AudioElementPool {
  private pools: Map<string, ObjectPool<HTMLAudioElement>> = new Map();
  private defaultConfig: Required<PoolConfig> = {
    initialSize: 5,
    maxSize: 20,
    autoExpand: true,
  };
 
  /**
   * Create a pool for a specific audio asset
   */
  createPool(
    assetId: string,
    audioSrc: string,
    config?: PoolConfig
  ): ObjectPool<HTMLAudioElement> {
    const existingPool = this.pools.get(assetId);
    if (existingPool) {
      return existingPool;
    }
 
    const poolConfig = { ...this.defaultConfig, ...config };
 
    const pool = new ObjectPool<HTMLAudioElement>(
      () => {
        const audio = new Audio(audioSrc);
        audio.preload = "auto";
        audio.load();
        return audio;
      },
      (audio) => {
        audio.pause();
        audio.currentTime = 0;
      },
      poolConfig
    );
 
    this.pools.set(assetId, pool);
    return pool;
  }
 
  /**
   * Get pool for an asset (creates if doesn't exist)
   */
  getPool(assetId: string): ObjectPool<HTMLAudioElement> | undefined {
    return this.pools.get(assetId);
  }
 
  /**
   * Acquire audio element from pool
   */
  acquire(assetId: string): HTMLAudioElement | null {
    const pool = this.pools.get(assetId);
    if (!pool) {
      console.warn(`No pool exists for asset: ${assetId}`);
      return null;
    }
    return pool.acquire();
  }
 
  /**
   * Release audio element back to pool
   */
  release(assetId: string, audio: HTMLAudioElement): void {
    const pool = this.pools.get(assetId);
    if (!pool) {
      console.warn(`No pool exists for asset: ${assetId}`);
      return;
    }
    pool.release(audio);
  }
 
  /**
   * Release all audio elements in all pools
   */
  releaseAll(): void {
    this.pools.forEach((pool) => pool.releaseAll());
  }
 
  /**
   * Get statistics for a specific pool
   */
  getPoolStatistics(assetId: string): PoolStatistics | undefined {
    const pool = this.pools.get(assetId);
    return pool?.getStatistics();
  }
 
  /**
   * Get statistics for all pools
   */
  getAllStatistics(): Map<string, PoolStatistics> {
    const stats = new Map<string, PoolStatistics>();
    this.pools.forEach((pool, assetId) => {
      stats.set(assetId, pool.getStatistics());
    });
    return stats;
  }
 
  /**
   * Remove a pool and dispose its resources
   * @param assetId - The ID of the asset whose pool should be removed
   * @returns true if the pool existed and was removed, false if no pool was found for the asset
   */
  removePool(assetId: string): boolean {
    const pool = this.pools.get(assetId);
    if (pool) {
      pool.clear();
      this.pools.delete(assetId);
      return true;
    }
    return false;
  }
 
  /**
   * Clear all pools
   */
  clearAll(): void {
    this.pools.forEach((pool) => pool.clear());
    this.pools.clear();
  }
 
  /**
   * Check if pool exists for asset
   */
  hasPool(assetId: string): boolean {
    return this.pools.has(assetId);
  }
 
  /**
   * Get total number of pools
   */
  getPoolCount(): number {
    return this.pools.size;
  }
}