flv-header.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * mux.js
  3. *
  4. * Copyright (c) Brightcove
  5. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6. */
  7. 'use strict';
  8. var FlvTag = require('./flv-tag.js');
  9. // For information on the FLV format, see
  10. // http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
  11. // Technically, this function returns the header and a metadata FLV tag
  12. // if duration is greater than zero
  13. // duration in seconds
  14. // @return {object} the bytes of the FLV header as a Uint8Array
  15. var getFlvHeader = function(duration, audio, video) { // :ByteArray {
  16. var
  17. headBytes = new Uint8Array(3 + 1 + 1 + 4),
  18. head = new DataView(headBytes.buffer),
  19. metadata,
  20. result,
  21. metadataLength;
  22. // default arguments
  23. duration = duration || 0;
  24. audio = audio === undefined ? true : audio;
  25. video = video === undefined ? true : video;
  26. // signature
  27. head.setUint8(0, 0x46); // 'F'
  28. head.setUint8(1, 0x4c); // 'L'
  29. head.setUint8(2, 0x56); // 'V'
  30. // version
  31. head.setUint8(3, 0x01);
  32. // flags
  33. head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
  34. // data offset, should be 9 for FLV v1
  35. head.setUint32(5, headBytes.byteLength);
  36. // init the first FLV tag
  37. if (duration <= 0) {
  38. // no duration available so just write the first field of the first
  39. // FLV tag
  40. result = new Uint8Array(headBytes.byteLength + 4);
  41. result.set(headBytes);
  42. result.set([0, 0, 0, 0], headBytes.byteLength);
  43. return result;
  44. }
  45. // write out the duration metadata tag
  46. metadata = new FlvTag(FlvTag.METADATA_TAG);
  47. metadata.pts = metadata.dts = 0;
  48. metadata.writeMetaDataDouble('duration', duration);
  49. metadataLength = metadata.finalize().length;
  50. result = new Uint8Array(headBytes.byteLength + metadataLength);
  51. result.set(headBytes);
  52. result.set(head.byteLength, metadataLength);
  53. return result;
  54. };
  55. module.exports = getFlvHeader;