parse-trun.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var parseSampleFlags = require('./parse-sample-flags.js');
  2. var trun = function(data) {
  3. var
  4. result = {
  5. version: data[0],
  6. flags: new Uint8Array(data.subarray(1, 4)),
  7. samples: []
  8. },
  9. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  10. // Flag interpretation
  11. dataOffsetPresent = result.flags[2] & 0x01, // compare with 2nd byte of 0x1
  12. firstSampleFlagsPresent = result.flags[2] & 0x04, // compare with 2nd byte of 0x4
  13. sampleDurationPresent = result.flags[1] & 0x01, // compare with 2nd byte of 0x100
  14. sampleSizePresent = result.flags[1] & 0x02, // compare with 2nd byte of 0x200
  15. sampleFlagsPresent = result.flags[1] & 0x04, // compare with 2nd byte of 0x400
  16. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08, // compare with 2nd byte of 0x800
  17. sampleCount = view.getUint32(4),
  18. offset = 8,
  19. sample;
  20. if (dataOffsetPresent) {
  21. // 32 bit signed integer
  22. result.dataOffset = view.getInt32(offset);
  23. offset += 4;
  24. }
  25. // Overrides the flags for the first sample only. The order of
  26. // optional values will be: duration, size, compositionTimeOffset
  27. if (firstSampleFlagsPresent && sampleCount) {
  28. sample = {
  29. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  30. };
  31. offset += 4;
  32. if (sampleDurationPresent) {
  33. sample.duration = view.getUint32(offset);
  34. offset += 4;
  35. }
  36. if (sampleSizePresent) {
  37. sample.size = view.getUint32(offset);
  38. offset += 4;
  39. }
  40. if (sampleCompositionTimeOffsetPresent) {
  41. if (result.version === 1) {
  42. sample.compositionTimeOffset = view.getInt32(offset);
  43. } else {
  44. sample.compositionTimeOffset = view.getUint32(offset);
  45. }
  46. offset += 4;
  47. }
  48. result.samples.push(sample);
  49. sampleCount--;
  50. }
  51. while (sampleCount--) {
  52. sample = {};
  53. if (sampleDurationPresent) {
  54. sample.duration = view.getUint32(offset);
  55. offset += 4;
  56. }
  57. if (sampleSizePresent) {
  58. sample.size = view.getUint32(offset);
  59. offset += 4;
  60. }
  61. if (sampleFlagsPresent) {
  62. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  63. offset += 4;
  64. }
  65. if (sampleCompositionTimeOffsetPresent) {
  66. if (result.version === 1) {
  67. sample.compositionTimeOffset = view.getInt32(offset);
  68. } else {
  69. sample.compositionTimeOffset = view.getUint32(offset);
  70. }
  71. offset += 4;
  72. }
  73. result.samples.push(sample);
  74. }
  75. return result;
  76. };
  77. module.exports = trun;