All files mp4Muxer.js

86.99% Statements 408/469
68.09% Branches 175/257
92.55% Functions 87/94
86.99% Lines 408/469

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042  270x   270x 270x 270x 19202x     270x 13272x 13272x   270x 48x   48x   270x 1106x 1106x 1106x   270x 4824x 4824x   270x 270x 270x 56x   270x 76x 76x   270x 4x 4x   270x 52x 52x   270x 2210x 2210x   270x       270x         270x 8x 8x   270x 60x 60x   270x 24x 24x   270x 24x 24x 4x 24x   270x 1874x   270x 12x 12x 5532x 5532x     12x   270x 2778x 2778x   270x 270x 12x 2x 12x 8x 12x   2x     270x 24x   270x         270x         270x 2x 2x                     270x 270x         270x 4x     4x 4x     4x 4x 4x 4x                                                 270x       270x 4x 4x       4x 4x 4x 4x                                                             270x         270x 4x 4x       4x 4x 4x                             270x                           270x         270x                   270x     270x           270x 270x 4x   4x                   270x           270x                                                                 270x               270x               270x                   270x                       270x       270x 4x                       270x 4x   4x   4x             270x 4x                           270x               270x 4x               4x             270x                         270x           270x 270x 270x 270x   270x 270x   2x 2x     270x 270x   2x 2x 2x 2x       40x     68x 68x               68x 272x 272x     68x 68x       48x 48x 28x 28x   20x 20x 20x 6x 20x 18x 46x 42x   20x 20x 20x 20x 20x       68x 68x 68x       46x     46x 26x 26x   20x 20x 6x 20x 18x 46x 42x   20x       270x 270x 270x 270x   2x 2x 2x 2x 2x 2x 2x     1092x 1092x 1092x 1092x       2x 2x       270x 270x 270x 270x 270x 270x 1094x 1094x   1094x 1094x             270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x       2x 2x     922x     922x     922x         922x           922x 922x 922x                   922x     922x     922x     922x     922x     922x           922x 922x   922x           922x                 2x     2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 32x 32x 922x 922x     2x 2x       2x 2x 2x 2x 2x 32x 922x 922x       2x       2x 2x     270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 2x     2x     2x 2x     2x         2x         2x 2x       2x             2x                   2x             2x       270x 270x 2x       2x 2x 2x         270x 270x 2x 2x                                                 270x 270x     922x 922x 922x 922x         922x 922x 922x 2x 2x         922x                   922x   270x 270x 922x 922x       922x 920x 920x 920x 920x 920x 920x 920x 2x 2x 918x 882x   36x 36x         920x 920x       920x                 2x 2x       2x         922x 922x 922x 2x   920x   920x   922x 32x 30x   32x         922x   270x 270x 922x   922x 922x 922x         922x                                     922x           922x 922x   270x 270x 32x   32x 32x 32x         4x           32x 32x     270x 270x   270x 270x 922x         270x        
 
(() => {
  // build/mp4Muxer.transformed.js
  (() => {
    "use strict";
    var __accessCheck = (obj, member, msg) => {
      if (!member.has(obj))
        throw TypeError("Cannot " + msg);
    };
    var __privateGet = (obj, member, getter) => {
      __accessCheck(obj, member, "read from private field");
      return getter ? getter.call(obj) : member.get(obj);
    };
    var __privateAdd = (obj, member, value) => {
      if (member.has(obj))
        throw TypeError("Cannot add the same private member more than once");
      member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
    };
    var __privateSet = (obj, member, value, setter) => {
      __accessCheck(obj, member, "write to private field");
      setter ? setter.call(obj, value) : member.set(obj, value);
      return value;
    };
    var __privateMethod = (obj, member, method) => {
      __accessCheck(obj, member, "access private method");
      return method;
    };
    var bytes = new Uint8Array(8);
    var view = new DataView(bytes.buffer);
    var u8 = (value) => {
      return [(value % 256 + 256) % 256];
    };
    var u16 = (value) => {
      view.setUint16(0, value, false);
      return [bytes[0], bytes[1]];
    };
    var i16 = (value) => {
      view.setInt16(0, value, false);
      return [bytes[0], bytes[1]];
    };
    var u24 = (value) => {
      view.setUint32(0, value, false);
      return [bytes[1], bytes[2], bytes[3]];
    };
    var u32 = (value) => {
      view.setUint32(0, value, false);
      return [bytes[0], bytes[1], bytes[2], bytes[3]];
    };
    var i32 = (value) => {
      view.setInt32(0, value, false);
      return [bytes[0], bytes[1], bytes[2], bytes[3]];
    };
    var u64 = (value) => {
      view.setUint32(0, Math.floor(value / 2 ** 32), false);
      view.setUint32(4, value, false);
      return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
    };
    var fixed_8_8 = (value) => {
      view.setInt16(0, 2 ** 8 * value, false);
      return [bytes[0], bytes[1]];
    };
    var fixed_16_16 = (value) => {
      view.setInt32(0, 2 ** 16 * value, false);
      return [bytes[0], bytes[1], bytes[2], bytes[3]];
    };
    var fixed_2_30 = (value) => {
      view.setInt32(0, 2 ** 30 * value, false);
      return [bytes[0], bytes[1], bytes[2], bytes[3]];
    };
    var ascii = (text, nullTerminated = false) => {
      let bytes2 = Array(text.length).fill(null).map((_, i) => text.charCodeAt(i));
      if (nullTerminated)
        bytes2.push(0);
      return bytes2;
    };
    var last = (arr) => {
      return arr && arr[arr.length - 1];
    };
    var lastPresentedSample = (samples) => {
      let result = void 0;
      for (let sample of samples) {
        if (!result || sample.presentationTimestamp > result.presentationTimestamp) {
          result = sample;
        }
      }
      return result;
    };
    var intoTimescale = (timeInSeconds, timescale, round = true) => {
      let value = timeInSeconds * timescale;
      return round ? Math.round(value) : value;
    };
    var IDENTITY_MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1];
    var deepClone = (x) => {
      if (!x)
        return x;
      if (typeof x !== "object")
        return x;
      if (Array.isArray(x))
        return x.map(deepClone);
      return Object.fromEntries(
        Object.entries(x).map(([key, value]) => [key, deepClone(value)]));
    };
    var isU32 = (value) => {
      return value >= 0 && value < 2 ** 32;
    };
    var box = (type, contents, children) => ({
      type,
      contents: contents && new Uint8Array(contents.flat(10)),
      children
    });
    var fullBox = (type, version, flags, contents, children) => box(
      type,
      [u8(version), u24(flags), contents ?? []],
      children
    );
    var ftyp = (details) => {
      let minorVersion = 512;
      return box("ftyp", [
        ascii("isom"),
        // Major brand
        u32(minorVersion),
        // Minor version
        // Compatible brands
        ascii("isom"),
        details.holdsAvc ? ascii("avc1") : [],
        ascii("mp41")
      ]);
    };
    var mdat = (reserveLargeSize) => ({ type: "mdat", largeSize: reserveLargeSize });
    var moov = (tracks, creationTime, fragmented = false) => box("moov", null, [
      mvhd(creationTime, tracks),
      ...tracks.map((x) => trak(x, creationTime)),
      null
    ]);
    var mvhd = (creationTime, tracks) => {
      let duration = intoTimescale(Math.max(
        0,
        ...tracks.filter((x) => x.samples.length > 0).map((x) => {
          const lastSample = lastPresentedSample(x.samples);
          return lastSample.presentationTimestamp + lastSample.duration;
        })
      ), GLOBAL_TIMESCALE);
      let nextTrackId = Math.max(...tracks.map((x) => x.id)) + 1;
      let needsU64 = !isU32(creationTime) || !isU32(duration);
      let u32OrU64 = needsU64 ? u64 : u32;
      return fullBox("mvhd", +needsU64, 0, [
        u32OrU64(creationTime),
        // Creation time
        u32OrU64(creationTime),
        // Modification time
        u32(GLOBAL_TIMESCALE),
        // Timescale
        u32OrU64(duration),
        // Duration
        fixed_16_16(1),
        // Preferred rate
        fixed_8_8(1),
        // Preferred volume
        Array(10).fill(0),
        // Reserved
        [fixed_16_16(1), fixed_16_16(0), fixed_2_30(0),
         fixed_16_16(0), fixed_16_16(1), fixed_2_30(0),
         fixed_16_16(0), fixed_16_16(0), fixed_2_30(1)],
        // Matrix
        Array(24).fill(0),
        // Pre-defined
        u32(nextTrackId)
        // Next track ID
      ]);
    };
    var trak = (track, creationTime) => box("trak", null, [
      tkhd(track, creationTime),
      mdia(track, creationTime)
    ]);
    var tkhd = (track, creationTime) => {
      let lastSample = lastPresentedSample(track.samples);
      let durationInGlobalTimescale = intoTimescale(
        lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
        GLOBAL_TIMESCALE
      );
      let needsU64 = !isU32(creationTime) || !isU32(durationInGlobalTimescale);
      let u32OrU64 = needsU64 ? u64 : u32;
      let matrix = IDENTITY_MATRIX;
      return fullBox("tkhd", +needsU64, 3, [
        u32OrU64(creationTime),
        // Creation time
        u32OrU64(creationTime),
        // Modification time
        u32(track.id),
        // Track ID
        u32(0),
        // Reserved
        u32OrU64(durationInGlobalTimescale),
        // Duration
        Array(8).fill(0),
        // Reserved
        u16(0),
        // Layer
        u16(0),
        // Alternate group
        fixed_8_8(track.info.type === "audio" ? 1 : 0),
        // Volume
        u16(0),
        // Reserved
        [fixed_16_16(1), fixed_16_16(0), fixed_2_30(0),
         fixed_16_16(0), fixed_16_16(1), fixed_2_30(0),
         fixed_16_16(0), fixed_16_16(0), fixed_2_30(1)],
        // Matrix
        fixed_16_16(track.info.type === "video" ? track.info.width : 0),
        // Track width
        fixed_16_16(track.info.type === "video" ? track.info.height : 0)
        // Track height
      ]);
    };
    var mdia = (track, creationTime) => box("mdia", null, [
      mdhd(track, creationTime),
      hdlr(track.info.type === "video" ? "vide" : "soun"),
      minf(track)
    ]);
    var mdhd = (track, creationTime) => {
      let lastSample = lastPresentedSample(track.samples);
      let localDuration = intoTimescale(
        lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
        track.timescale
      );
      let needsU64 = !isU32(creationTime) || !isU32(localDuration);
      let u32OrU64 = needsU64 ? u64 : u32;
      return fullBox("mdhd", +needsU64, 0, [
        u32OrU64(creationTime),
        // Creation time
        u32OrU64(creationTime),
        // Modification time
        u32(track.timescale),
        // Timescale
        u32OrU64(localDuration),
        // Duration
        u16(21956),
        // Language ("und", undetermined)
        u16(0)
        // Quality
      ]);
    };
    var hdlr = (componentSubtype) => fullBox("hdlr", 0, 0, [
      ascii("mhlr"),
      // Component type
      ascii(componentSubtype),
      // Component subtype
      u32(0),
      // Component manufacturer
      u32(0),
      // Component flags
      u32(0),
      // Component flags mask
      ascii("mp4-muxer-hdlr", true)
      // Component name
    ]);
    var minf = (track) => box("minf", null, [
      vmhd(),
      dinf(),
      stbl(track)
    ]);
    var vmhd = () => fullBox("vmhd", 0, 1, [
      u16(0),
      // Graphics mode
      u16(0),
      // Opcolor R
      u16(0),
      // Opcolor G
      u16(0)
      // Opcolor B
    ]);
    var dinf = () => box("dinf", null, [
      dref()
    ]);
    var dref = () => fullBox("dref", 0, 0, [
      u32(1)
      // Entry count
    ], [
      url()
    ]);
    var url = () => fullBox("url ", 0, 1);
    var stbl = (track) => {
      const needsCtts = track.compositionTimeOffsetTable.length > 1 ||
        track.compositionTimeOffsetTable.some((x) => x.sampleCompositionTimeOffset !== 0);
      return box("stbl", null, [
        stsd(track),
        stts(track),
        stss(track),
        stsc(track),
        stsz(track),
        stco(track),
        needsCtts ? ctts(track) : null
      ]);
    };
    var stsd = (track) => fullBox("stsd", 0, 0, [
      u32(1)
      // Entry count
    ], [
      videoSampleDescription(VIDEO_CODEC_TO_BOX_NAME[track.info.codec], track)
    ]);
    var videoSampleDescription = (compressionType, track) => box(compressionType, [
      Array(6).fill(0),
      // Reserved
      u16(1),
      // Data reference index
      u16(0),
      // Pre-defined
      u16(0),
      // Reserved
      Array(12).fill(0),
      // Pre-defined
      u16(track.info.width),
      // Width
      u16(track.info.height),
      // Height
      u32(4718592),
      // Horizontal resolution
      u32(4718592),
      // Vertical resolution
      u32(0),
      // Reserved
      u16(1),
      // Frame count
      Array(32).fill(0),
      // Compressor name
      u16(24),
      // Depth
      i16(65535)
      // Pre-defined
    ], [
      VIDEO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track),
      track.info.decoderConfig.colorSpace ? colr(track) : null
    ]);
    var COLOR_PRIMARIES_MAP = {
      "bt709": 1,
      // ITU-R BT.709
      "bt470bg": 5,
      // ITU-R BT.470BG
      "smpte170m": 6
      // ITU-R BT.601 525 - SMPTE 170M
    };
    var TRANSFER_CHARACTERISTICS_MAP = {
      "bt709": 1,
      // ITU-R BT.709
      "smpte170m": 6,
      // SMPTE 170M
      "iec61966-2-1": 13
      // IEC 61966-2-1
    };
    var MATRIX_COEFFICIENTS_MAP = {
      "rgb": 0,
      // Identity
      "bt709": 1,
      // ITU-R BT.709
      "bt470bg": 5,
      // ITU-R BT.470BG
      "smpte170m": 6
      // SMPTE 170M
    };
    var colr = (track) => box("colr", [
      ascii("nclx"),
      // Colour type
      u16(COLOR_PRIMARIES_MAP[track.info.decoderConfig.colorSpace.primaries]),
      // Colour primaries
      u16(TRANSFER_CHARACTERISTICS_MAP[track.info.decoderConfig.colorSpace.transfer]),
      // Transfer characteristics
      u16(MATRIX_COEFFICIENTS_MAP[track.info.decoderConfig.colorSpace.matrix]),
      // Matrix coefficients
      u8((track.info.decoderConfig.colorSpace.fullRange ? 1 : 0) << 7)
      // Full range flag
    ]);
    var avcC = (track) => track.info.decoderConfig && box("avcC", [
      // For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here
      ...new Uint8Array(track.info.decoderConfig.description)
    ]);
    var stts = (track) => {
      return fullBox("stts", 0, 0, [
        u32(track.timeToSampleTable.length),
        // Number of entries
        track.timeToSampleTable.map((x) => [
          // Time-to-sample table
          u32(x.sampleCount),
          // Sample count
          u32(x.sampleDelta)
          // Sample duration
        ])
      ]);
    };
    var stss = (track) => {
      if (track.samples.every((x) => x.type === "key"))
        return null;
      let keySamples = [...track.samples.entries()]
        .filter(([, sample]) => sample.type === "key");
      return fullBox("stss", 0, 0, [
        u32(keySamples.length),
        // Number of entries
        keySamples.map(([index]) => u32(index + 1))
        // Sync sample table
      ]);
    };
    var stsc = (track) => {
      return fullBox("stsc", 0, 0, [
        u32(track.compactlyCodedChunkTable.length),
        // Number of entries
        track.compactlyCodedChunkTable.map((x) => [
          // Sample-to-chunk table
          u32(x.firstChunk),
          // First chunk
          u32(x.samplesPerChunk),
          // Samples per chunk
          u32(1)
          // Sample description index
        ])
      ]);
    };
    var stsz = (track) => fullBox("stsz", 0, 0, [
      u32(0),
      // Sample size (0 means non-constant size)
      u32(track.samples.length),
      // Number of entries
      track.samples.map((x) => u32(x.size))
      // Sample size table
    ]);
    var stco = (track) => {
      if (track.finalizedChunks.length > 0 && last(track.finalizedChunks).offset >= 2 ** 32) {
        return fullBox("co64", 0, 0, [
          u32(track.finalizedChunks.length),
          // Number of entries
          track.finalizedChunks.map((x) => u64(x.offset))
          // Chunk offset table
        ]);
      }
      return fullBox("stco", 0, 0, [
        u32(track.finalizedChunks.length),
        // Number of entries
        track.finalizedChunks.map((x) => u32(x.offset))
        // Chunk offset table
      ]);
    };
    var ctts = (track) => {
      return fullBox("ctts", 0, 0, [
        u32(track.compositionTimeOffsetTable.length),
        // Number of entries
        track.compositionTimeOffsetTable.map((x) => [
          // Time-to-sample table
          u32(x.sampleCount),
          // Sample count
          u32(x.sampleCompositionTimeOffset)
          // Sample offset
        ])
      ]);
    };
    var VIDEO_CODEC_TO_BOX_NAME = {
      "avc": "avc1",
      "hevc": "hvc1",
      "vp9": "vp09",
      "av1": "av01"
    };
    var VIDEO_CODEC_TO_CONFIGURATION_BOX = { "avc": avcC };
    var AUDIO_CODEC_TO_CONFIGURATION_BOX = {};
    var isTarget = Symbol("isTarget");
    var Target = class {
    };
    isTarget;
    var ArrayBufferTarget = class extends Target {
      constructor() {
        super(...arguments);
        this.buffer = null;
      }
    };
    var _helper, _helperView;
    var Writer = class {
      constructor() {
        this.pos = 0;
        __privateAdd(this, _helper, new Uint8Array(8));
        __privateAdd(this, _helperView, new DataView(__privateGet(this, _helper).buffer));
        this.offsets = /* @__PURE__ */ new WeakMap();
      }
      /** Sets the current position for future writes to a new one. */
      seek(newPos) {
        this.pos = newPos;
      }
      writeU32(value) {
        __privateGet(this, _helperView).setUint32(0, value, false);
        this.write(__privateGet(this, _helper).subarray(0, 4));
      }
      writeU64(value) {
        __privateGet(this, _helperView).setUint32(0, Math.floor(value / 2 ** 32), false);
        __privateGet(this, _helperView).setUint32(4, value, false);
        this.write(__privateGet(this, _helper).subarray(0, 8));
      }
      writeAscii(text) {
        for (let i = 0; i < text.length; i++) {
          __privateGet(this, _helperView).setUint8(i % 8, text.charCodeAt(i));
          if (i % 8 === 7)
            this.write(__privateGet(this, _helper));
        }
        if (text.length % 8 !== 0) {
          this.write(__privateGet(this, _helper).subarray(0, text.length % 8));
        }
      }
      writeBox(box2) {
        this.offsets.set(box2, this.pos);
        if (box2.contents && !box2.children) {
          this.writeBoxHeader(box2, box2.size ?? box2.contents.byteLength + 8);
          this.write(box2.contents);
        } else {
          let startPos = this.pos;
          this.writeBoxHeader(box2, 0);
          if (box2.contents)
            this.write(box2.contents);
          if (box2.children) {
            for (let child of box2.children)
              if (child)
                this.writeBox(child);
          }
          let endPos = this.pos;
          let size = box2.size ?? endPos - startPos;
          this.seek(startPos);
          this.writeBoxHeader(box2, size);
          this.seek(endPos);
        }
      }
      writeBoxHeader(box2, size) {
        this.writeU32(box2.largeSize ? 1 : size);
        this.writeAscii(box2.type);
        if (box2.largeSize)
          this.writeU64(size);
      }
      measureBoxHeader(box2) {
        return 8 + (box2.largeSize ? 8 : 0);
      }
      measureBox(box2) {
        if (box2.contents && !box2.children) {
          let headerSize = this.measureBoxHeader(box2);
          return headerSize + box2.contents.byteLength;
        } else {
          let result = this.measureBoxHeader(box2);
          if (box2.contents)
            result += box2.contents.byteLength;
          if (box2.children) {
            for (let child of box2.children)
              if (child)
                result += this.measureBox(child);
          }
          return result;
        }
      }
    };
    _helper = /* @__PURE__ */ new WeakMap();
    _helperView = /* @__PURE__ */ new WeakMap();
    var _target, _buffer, _bytes, _maxPos, _ensureSize, ensureSize_fn;
    var ArrayBufferTargetWriter = class extends Writer {
      constructor(target) {
        super();
        __privateAdd(this, _ensureSize);
        __privateAdd(this, _target, void 0);
        __privateAdd(this, _buffer, new ArrayBuffer(2 ** 16));
        __privateAdd(this, _bytes, new Uint8Array(__privateGet(this, _buffer)));
        __privateAdd(this, _maxPos, 0);
        __privateSet(this, _target, target);
      }
      write(data) {
        __privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos + data.byteLength);
        __privateGet(this, _bytes).set(data, this.pos);
        this.pos += data.byteLength;
        __privateSet(this, _maxPos,
          Math.max(__privateGet(this, _maxPos), this.pos));
      }
      finalize() {
        __privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos);
        __privateGet(this, _target).buffer = __privateGet(this, _buffer).slice(0,
          Math.max(__privateGet(this, _maxPos), this.pos));
      }
    };
    _target = /* @__PURE__ */ new WeakMap();
    _buffer = /* @__PURE__ */ new WeakMap();
    _bytes = /* @__PURE__ */ new WeakMap();
    _maxPos = /* @__PURE__ */ new WeakMap();
    _ensureSize = /* @__PURE__ */ new WeakSet();
    ensureSize_fn = function(size) {
      let newLength = __privateGet(this, _buffer).byteLength;
      while (newLength < size)
        newLength *= 2;
      if (newLength === __privateGet(this, _buffer).byteLength)
        return;
      let newBuffer = new ArrayBuffer(newLength);
      let newBytes = new Uint8Array(newBuffer);
      newBytes.set(__privateGet(this, _bytes), 0);
      __privateSet(this, _buffer, newBuffer);
      __privateSet(this, _bytes, newBytes);
    };
    var DEFAULT_CHUNK_SIZE = 2 ** 24;
    var MAX_CHUNKS_AT_ONCE = 2;
    var GLOBAL_TIMESCALE = 1e3;
    var SUPPORTED_VIDEO_CODECS = ["avc", "hevc", "vp9", "av1"];
    var TIMESTAMP_OFFSET = 2082844800;
    var FIRST_TIMESTAMP_BEHAVIORS = ["strict", "offset", "cross-track-offset"];
    var _options, _writer, _ftypSize, _mdat, _videoTrack, _creationTime;
    var _finalizedChunks, _finalized;
    var _validateOptions, validateOptions_fn;
    var _writeHeader, writeHeader_fn;
    var _prepareTracks, prepareTracks_fn;
    var _createSampleForTrack, createSampleForTrack_fn;
    var _addSampleToTrack, addSampleToTrack_fn;
    var _validateTimestamp, validateTimestamp_fn;
    var _finalizeCurrentChunk, finalizeCurrentChunk_fn;
    var _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn;
    var _ensureNotFinalized, ensureNotFinalized_fn;
    var Muxer = class {
      constructor(options) {
        __privateAdd(this, _validateOptions);
        __privateAdd(this, _writeHeader);
        __privateAdd(this, _prepareTracks);
        __privateAdd(this, _createSampleForTrack);
        __privateAdd(this, _addSampleToTrack);
        __privateAdd(this, _validateTimestamp);
        __privateAdd(this, _finalizeCurrentChunk);
        __privateAdd(this, _maybeFlushStreamingTargetWriter);
        __privateAdd(this, _ensureNotFinalized);
        __privateAdd(this, _options, void 0);
        __privateAdd(this, _writer, void 0);
        __privateAdd(this, _ftypSize, void 0);
        __privateAdd(this, _mdat, void 0);
        __privateAdd(this, _videoTrack, null);
        __privateAdd(this, _creationTime, Math.floor(Date.now() / 1e3) + TIMESTAMP_OFFSET);
        __privateAdd(this, _finalizedChunks, []);
        __privateAdd(this, _finalized, false);
        __privateMethod(this, _validateOptions, validateOptions_fn).call(this, options);
        options.video = deepClone(options.video);
        options.audio = deepClone(options.audio);
        options.fastStart = deepClone(options.fastStart);
        this.target = options.target;
        __privateSet(this, _options, {
          firstTimestampBehavior: "strict",
          ...options
        });
        if (options.target instanceof ArrayBufferTarget) {
          __privateSet(this, _writer, new ArrayBufferTargetWriter(options.target));
        } else {
          throw new Error(`Invalid target: ${options.target}`);
        }
        __privateMethod(this, _prepareTracks, prepareTracks_fn).call(this);
        __privateMethod(this, _writeHeader, writeHeader_fn).call(this);
      }
      addVideoChunk(sample, meta, timestamp, compositionTimeOffset) {
        if (!(sample instanceof EncodedVideoChunk)) {
          throw new TypeError("sample must be EncodedVideoChunk");
        }
        if (meta && typeof meta !== "object") {
          throw new TypeError("meta must be object");
        }
        if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
          throw new TypeError(
            "timestamp must be non-negative"
          );
        }
        if (compositionTimeOffset !== void 0 &&
            !Number.isFinite(compositionTimeOffset)) {
          throw new TypeError(
            "compositionTimeOffset must be number"
          );
        }
        let data = new Uint8Array(sample.byteLength);
        sample.copyTo(data);
        this.addVideoChunkRaw(
          data,
          sample.type,
          timestamp ?? sample.timestamp,
          sample.duration,
          meta,
          compositionTimeOffset
        );
      }
      addVideoChunkRaw(data, type, timestamp, duration, meta, compositionTimeOffset) {
        if (!(data instanceof Uint8Array)) {
          throw new TypeError("data must be Uint8Array");
        }
        if (type !== "key" && type !== "delta") {
          throw new TypeError("type must be 'key'|'delta'");
        }
        if (!Number.isFinite(timestamp) || timestamp < 0) {
          throw new TypeError("timestamp must be non-negative");
        }
        if (!Number.isFinite(duration) || duration < 0) {
          throw new TypeError("duration must be non-negative");
        }
        if (meta && typeof meta !== "object") {
          throw new TypeError("meta must be object");
        }
        if (compositionTimeOffset !== void 0 &&
            !Number.isFinite(compositionTimeOffset)) {
          throw new TypeError(
            "compositionTimeOffset must be number"
          );
        }
        __privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
        if (!__privateGet(this, _options).video)
          throw new Error("No video track declared.");
        let videoSample = __privateMethod(
          this, _createSampleForTrack, createSampleForTrack_fn
        ).call(
          this, __privateGet(this, _videoTrack), data, type,
          timestamp, duration, meta, compositionTimeOffset
        );
        __privateMethod(
          this, _addSampleToTrack, addSampleToTrack_fn
        ).call(this, __privateGet(this, _videoTrack), videoSample);
      }
      /**
       * Finalizes the file, making it ready for use.
       * Must be called after all video and audio chunks have been added.
       */
      finalize() {
        if (__privateGet(this, _finalized)) {
          throw new Error("Cannot finalize a muxer more than once.");
        }
        if (__privateGet(this, _videoTrack))
          __privateMethod(
            this, _finalizeCurrentChunk, finalizeCurrentChunk_fn
          ).call(this, __privateGet(this, _videoTrack));
        let tracks = [__privateGet(this, _videoTrack)].filter(Boolean);
        if (__privateGet(this, _options).fastStart === "in-memory") {
          let mdatSize;
          for (let i = 0; i < 2; i++) {
            let movieBox2 = moov(tracks, __privateGet(this, _creationTime));
            let movieBoxSize = __privateGet(this, _writer).measureBox(movieBox2);
            mdatSize = __privateGet(this, _writer).measureBox(__privateGet(this, _mdat));
            let currentChunkPos = __privateGet(this, _writer).pos + movieBoxSize + mdatSize;
            for (let chunk of __privateGet(this, _finalizedChunks)) {
              chunk.offset = currentChunkPos;
              for (let { data } of chunk.samples) {
                currentChunkPos += data.byteLength;
                mdatSize += data.byteLength;
              }
            }
            if (currentChunkPos < 2 ** 32)
              break;
            if (mdatSize >= 2 ** 32)
              __privateGet(this, _mdat).largeSize = true;
          }
          let movieBox = moov(tracks, __privateGet(this, _creationTime));
          __privateGet(this, _writer).writeBox(movieBox);
          __privateGet(this, _mdat).size = mdatSize;
          __privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
          for (let chunk of __privateGet(this, _finalizedChunks)) {
            for (let sample of chunk.samples) {
              __privateGet(this, _writer).write(sample.data);
              sample.data = null;
            }
          }
        }
        __privateMethod(
          this, _maybeFlushStreamingTargetWriter,
          maybeFlushStreamingTargetWriter_fn
        ).call(this);
        __privateGet(this, _writer).finalize();
        __privateSet(this, _finalized, true);
      }
    };
    _options = /* @__PURE__ */ new WeakMap();
    _writer = /* @__PURE__ */ new WeakMap();
    _ftypSize = /* @__PURE__ */ new WeakMap();
    _mdat = /* @__PURE__ */ new WeakMap();
    _videoTrack = /* @__PURE__ */ new WeakMap();
    _creationTime = /* @__PURE__ */ new WeakMap();
    _finalizedChunks = /* @__PURE__ */ new WeakMap();
    _finalized = /* @__PURE__ */ new WeakMap();
    _validateOptions = /* @__PURE__ */ new WeakSet();
    validateOptions_fn = function(options) {
      if (typeof options !== "object") {
        throw new TypeError("options required");
      }
      if (!(options.target instanceof Target)) {
        throw new TypeError("target must be Target instance");
      }
      if (options.video) {
        if (!SUPPORTED_VIDEO_CODECS.includes(options.video.codec)) {
          throw new TypeError(`Unsupported video codec: ${options.video.codec}`);
        }
        if (!Number.isInteger(options.video.width) || options.video.width <= 0) {
          throw new TypeError(
            `Invalid video width: ${options.video.width}. Must be a positive integer.`
          );
        }
        if (!Number.isInteger(options.video.height) || options.video.height <= 0) {
          throw new TypeError(
            `Invalid video height: ${options.video.height}. Must be a positive integer.`
          );
        }
        const videoRotation = options.video.rotation;
        if (typeof videoRotation === "number" && ![0, 90, 180, 270].includes(videoRotation)) {
          throw new TypeError(
            `Invalid video rotation: ${videoRotation}. Has to be 0, 90, 180 or 270.`
          );
        } else if (
          Array.isArray(videoRotation) &&
          (videoRotation.length !== 9 ||
           videoRotation.some((value) => typeof value !== "number"))
        ) {
          throw new TypeError(`Invalid video transformation matrix: ${videoRotation.join()}`);
        }
        if (
          options.video.frameRate !== void 0 &&
          (!Number.isInteger(options.video.frameRate) ||
           options.video.frameRate <= 0)
        ) {
          throw new TypeError(
            `Invalid video frame rate: ${options.video.frameRate}. Must be a positive integer.`
          );
        }
      }
      if (
        options.firstTimestampBehavior &&
        !FIRST_TIMESTAMP_BEHAVIORS.includes(options.firstTimestampBehavior)
      ) {
        throw new TypeError(
          `Invalid first timestamp behavior: ${options.firstTimestampBehavior}`);
      }
      if (options.fastStart !== "in-memory") {
        throw new TypeError(`'fastStart' must be 'in-memory'.`);
      }
    };
    _writeHeader = /* @__PURE__ */ new WeakSet();
    writeHeader_fn = function() {
      __privateGet(this, _writer).writeBox(ftyp({
        holdsAvc: __privateGet(this, _options).video?.codec === "avc",
        fragmented: false
      }));
      __privateSet(this, _ftypSize, __privateGet(this, _writer).pos);
      __privateSet(this, _mdat, mdat(false));
      __privateMethod(
        this, _maybeFlushStreamingTargetWriter,
        maybeFlushStreamingTargetWriter_fn
      ).call(this);
    };
    _prepareTracks = /* @__PURE__ */ new WeakSet();
    prepareTracks_fn = function() {
      if (__privateGet(this, _options).video) {
        __privateSet(this, _videoTrack, {
          id: 1,
          info: {
            type: "video",
            codec: __privateGet(this, _options).video.codec,
            width: __privateGet(this, _options).video.width,
            height: __privateGet(this, _options).video.height,
            rotation: __privateGet(this, _options).video.rotation ?? 0,
            decoderConfig: null
          },
          // The fallback contains many common frame rates as factors
          timescale: __privateGet(this, _options).video.frameRate ?? 57600,
          samples: [],
          finalizedChunks: [],
          currentChunk: null,
          firstDecodeTimestamp: void 0,
          lastDecodeTimestamp: -1,
          timeToSampleTable: [],
          compositionTimeOffsetTable: [],
          lastTimescaleUnits: null,
          lastSample: null,
          compactlyCodedChunkTable: []
        });
      }
    };
    _createSampleForTrack = /* @__PURE__ */ new WeakSet();
    createSampleForTrack_fn = function(
      track, data, type, timestamp, duration, meta, compositionTimeOffset
    ) {
      let presentationTimestampInSeconds = timestamp / 1e6;
      let decodeTimestampInSeconds = (timestamp - (compositionTimeOffset ?? 0)) / 1e6;
      let durationInSeconds = duration / 1e6;
      let adjusted = __privateMethod(
        this, _validateTimestamp, validateTimestamp_fn
      ).call(
        this, presentationTimestampInSeconds, decodeTimestampInSeconds, track
      );
      presentationTimestampInSeconds = adjusted.presentationTimestamp;
      decodeTimestampInSeconds = adjusted.decodeTimestamp;
      if (meta?.decoderConfig) {
        if (track.info.decoderConfig === null) {
          track.info.decoderConfig = meta.decoderConfig;
        } else {
          Object.assign(track.info.decoderConfig, meta.decoderConfig);
        }
      }
      let sample = {
        presentationTimestamp: presentationTimestampInSeconds,
        decodeTimestamp: decodeTimestampInSeconds,
        duration: durationInSeconds,
        data,
        size: data.byteLength,
        type,
        // Will be refined once the next sample comes in
        timescaleUnitsToNextSample: intoTimescale(durationInSeconds, track.timescale)
      };
      return sample;
    };
    _addSampleToTrack = /* @__PURE__ */ new WeakSet();
    addSampleToTrack_fn = function(track, sample) {
      track.samples.push(sample);
      const sampleCompositionTimeOffset = intoTimescale(
        sample.presentationTimestamp - sample.decodeTimestamp,
        track.timescale
      );
      if (track.lastTimescaleUnits !== null) {
        let timescaleUnits = intoTimescale(sample.decodeTimestamp, track.timescale, false);
        let delta = Math.round(timescaleUnits - track.lastTimescaleUnits);
        track.lastTimescaleUnits += delta;
        track.lastSample.timescaleUnitsToNextSample = delta;
        if (__privateGet(this, _options).fastStart !== "fragmented") {
          let lastTableEntry = last(track.timeToSampleTable);
          if (lastTableEntry.sampleCount === 1) {
            lastTableEntry.sampleDelta = delta;
            lastTableEntry.sampleCount++;
          } else if (lastTableEntry.sampleDelta === delta) {
            lastTableEntry.sampleCount++;
          } else {
            lastTableEntry.sampleCount--;
            track.timeToSampleTable.push({
              sampleCount: 2,
              sampleDelta: delta
            });
          }
          const lastCompositionTimeOffsetTableEntry = last(track.compositionTimeOffsetTable);
          if (
            lastCompositionTimeOffsetTableEntry.sampleCompositionTimeOffset ===
            sampleCompositionTimeOffset
          ) {
            lastCompositionTimeOffsetTableEntry.sampleCount++;
          } else {
            track.compositionTimeOffsetTable.push({
              sampleCount: 1,
              sampleCompositionTimeOffset
            });
          }
        }
      } else {
        track.lastTimescaleUnits = 0;
        track.timeToSampleTable.push({
          sampleCount: 1,
          sampleDelta: intoTimescale(sample.duration, track.timescale)
        });
        track.compositionTimeOffsetTable.push({
          sampleCount: 1,
          sampleCompositionTimeOffset
        });
      }
      track.lastSample = sample;
      let beginNewChunk = false;
      if (!track.currentChunk) {
        beginNewChunk = true;
      } else {
        let currentChunkDuration = sample.presentationTimestamp -
          track.currentChunk.startTimestamp;
        beginNewChunk = currentChunkDuration >= 0.5;
      }
      if (beginNewChunk) {
        if (track.currentChunk) {
          __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, track);
        }
        track.currentChunk = {
          startTimestamp: sample.presentationTimestamp,
          samples: []
        };
      }
      track.currentChunk.samples.push(sample);
    };
    _validateTimestamp = /* @__PURE__ */ new WeakSet();
    validateTimestamp_fn = function(presentationTimestamp, decodeTimestamp, track) {
      const strictTimestampBehavior =
        __privateGet(this, _options).firstTimestampBehavior === "strict";
      const noLastDecodeTimestamp = track.lastDecodeTimestamp === -1;
      const timestampNonZero = decodeTimestamp !== 0;
      if (strictTimestampBehavior && noLastDecodeTimestamp && timestampNonZero) {
        throw new Error(
          `First chunk must have timestamp 0 (got DTS=${decodeTimestamp}). ` +
          `Use firstTimestampBehavior:"offset" to auto-fix.`
        );
      } else if (
        __privateGet(this, _options).firstTimestampBehavior === "offset" ||
        __privateGet(this, _options).firstTimestampBehavior === "cross-track-offset"
      ) {
        if (track.firstDecodeTimestamp === void 0) {
          track.firstDecodeTimestamp = decodeTimestamp;
        }
        let baseDecodeTimestamp;
        if (__privateGet(this, _options).firstTimestampBehavior === "offset") {
          baseDecodeTimestamp = track.firstDecodeTimestamp;
        } else {
          baseDecodeTimestamp = Math.min(
            __privateGet(this, _videoTrack)?.firstDecodeTimestamp ?? Infinity,
            Infinity
          );
        }
        decodeTimestamp -= baseDecodeTimestamp;
        presentationTimestamp -= baseDecodeTimestamp;
      }
      if (decodeTimestamp < track.lastDecodeTimestamp) {
        throw new Error(
          `Timestamps must be monotonically increasing ` +
          `(DTS went from ${track.lastDecodeTimestamp * 1e6} to ${decodeTimestamp * 1e6}).`
        );
      }
      track.lastDecodeTimestamp = decodeTimestamp;
      return { presentationTimestamp, decodeTimestamp };
    };
    _finalizeCurrentChunk = /* @__PURE__ */ new WeakSet();
    finalizeCurrentChunk_fn = function(track) {
      if (!track.currentChunk)
        return;
      track.finalizedChunks.push(track.currentChunk);
      __privateGet(this, _finalizedChunks).push(track.currentChunk);
      if (
        track.compactlyCodedChunkTable.length === 0 ||
        last(track.compactlyCodedChunkTable).samplesPerChunk !==
        track.currentChunk.samples.length
      ) {
        track.compactlyCodedChunkTable.push({
          firstChunk: track.finalizedChunks.length,
          // 1-indexed
          samplesPerChunk: track.currentChunk.samples.length
        });
      }
      if (__privateGet(this, _options).fastStart === "in-memory") {
        track.currentChunk.offset = 0;
      }
    };
    _maybeFlushStreamingTargetWriter = /* @__PURE__ */ new WeakSet();
    maybeFlushStreamingTargetWriter_fn = function() {
    };
    _ensureNotFinalized = /* @__PURE__ */ new WeakSet();
    ensureNotFinalized_fn = function() {
      if (__privateGet(this, _finalized)) {
        throw new Error(
          "Cannot add new video or audio chunks after the file has been finalized.");
      }
    };
    window.Mp4Muxer = { Muxer, ArrayBufferTarget };
  })();
})();