flv-header.js 1.7 KB

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