Home Reference Source

src/utils/chunker.ts

  1. import { appendUint8Array } from './mp4-tools';
  2. import { sliceUint8 } from './typed-array';
  3.  
  4. export default class Chunker {
  5. private chunkSize: number;
  6. public cache: Uint8Array | null = null;
  7. constructor(chunkSize = Math.pow(2, 19)) {
  8. this.chunkSize = chunkSize;
  9. }
  10.  
  11. public push(data: Uint8Array): Array<Uint8Array> {
  12. const { cache, chunkSize } = this;
  13. const result: Array<Uint8Array> = [];
  14.  
  15. let temp: Uint8Array | null = null;
  16. if (cache?.length) {
  17. temp = appendUint8Array(cache, data);
  18. this.cache = null;
  19. } else {
  20. temp = data;
  21. }
  22.  
  23. if (temp.length < chunkSize) {
  24. this.cache = temp;
  25. return result;
  26. }
  27.  
  28. if (temp.length > chunkSize) {
  29. let offset = 0;
  30. const len = temp.length;
  31. while (offset < len - chunkSize) {
  32. result.push(sliceUint8(temp, offset, offset + chunkSize));
  33. offset += chunkSize;
  34. }
  35. this.cache = sliceUint8(temp, offset);
  36. } else {
  37. result.push(temp);
  38. }
  39.  
  40. return result;
  41. }
  42. }