parse-trun.js 2.5 KB

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