riff-helpers.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { toUint8, stringToBytes, bytesMatch } from './byte-helpers.js';
  2. var CONSTANTS = {
  3. LIST: toUint8([0x4c, 0x49, 0x53, 0x54]),
  4. RIFF: toUint8([0x52, 0x49, 0x46, 0x46]),
  5. WAVE: toUint8([0x57, 0x41, 0x56, 0x45])
  6. };
  7. var normalizePath = function normalizePath(path) {
  8. if (typeof path === 'string') {
  9. return stringToBytes(path);
  10. }
  11. if (typeof path === 'number') {
  12. return path;
  13. }
  14. return path;
  15. };
  16. var normalizePaths = function normalizePaths(paths) {
  17. if (!Array.isArray(paths)) {
  18. return [normalizePath(paths)];
  19. }
  20. return paths.map(function (p) {
  21. return normalizePath(p);
  22. });
  23. };
  24. export var findFourCC = function findFourCC(bytes, paths) {
  25. paths = normalizePaths(paths);
  26. bytes = toUint8(bytes);
  27. var results = [];
  28. if (!paths.length) {
  29. // short-circuit the search for empty paths
  30. return results;
  31. }
  32. var i = 0;
  33. while (i < bytes.length) {
  34. var type = bytes.subarray(i, i + 4);
  35. var size = (bytes[i + 7] << 24 | bytes[i + 6] << 16 | bytes[i + 5] << 8 | bytes[i + 4]) >>> 0; // skip LIST/RIFF and get the actual type
  36. if (bytesMatch(type, CONSTANTS.LIST) || bytesMatch(type, CONSTANTS.RIFF) || bytesMatch(type, CONSTANTS.WAVE)) {
  37. type = bytes.subarray(i + 8, i + 12);
  38. i += 4;
  39. size -= 4;
  40. }
  41. var data = bytes.subarray(i + 8, i + 8 + size);
  42. if (bytesMatch(type, paths[0])) {
  43. if (paths.length === 1) {
  44. // this is the end of the path and we've found the box we were
  45. // looking for
  46. results.push(data);
  47. } else {
  48. // recursively search for the next box along the path
  49. var subresults = findFourCC(data, paths.slice(1));
  50. if (subresults.length) {
  51. results = results.concat(subresults);
  52. }
  53. }
  54. }
  55. i += 8 + data.length;
  56. } // we've finished searching all of bytes
  57. return results;
  58. };