Home Reference Source

src/demux/chunk-cache.ts

  1. export default class ChunkCache {
  2. private chunks: Array<Uint8Array> = [];
  3. public dataLength: number = 0;
  4.  
  5. push(chunk: Uint8Array) {
  6. this.chunks.push(chunk);
  7. this.dataLength += chunk.length;
  8. }
  9.  
  10. flush(): Uint8Array {
  11. const { chunks, dataLength } = this;
  12. let result;
  13. if (!chunks.length) {
  14. return new Uint8Array(0);
  15. } else if (chunks.length === 1) {
  16. result = chunks[0];
  17. } else {
  18. result = concatUint8Arrays(chunks, dataLength);
  19. }
  20. this.reset();
  21. return result;
  22. }
  23.  
  24. reset() {
  25. this.chunks.length = 0;
  26. this.dataLength = 0;
  27. }
  28. }
  29.  
  30. function concatUint8Arrays(
  31. chunks: Array<Uint8Array>,
  32. dataLength: number
  33. ): Uint8Array {
  34. const result = new Uint8Array(dataLength);
  35. let offset = 0;
  36. for (let i = 0; i < chunks.length; i++) {
  37. const chunk = chunks[i];
  38. result.set(chunk, offset);
  39. offset += chunk.length;
  40. }
  41. return result;
  42. }