parse-trun.js 2.5 KB

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