int scanForNextFrameHeader()

in pedalboard/juce_overrides/juce_PatchedMP3AudioFormat.cpp [2124:2186]


  int scanForNextFrameHeader(bool checkTypeAgainstLastFrame) noexcept {
    auto oldPos = stream.getPosition();
    int offset = -3;
    uint32 header = 0;
    bool isParsingFirstFrame = oldPos == 0;

    for (;;) {
      auto streamPos = stream.getPosition();

      if (stream.isExhausted() || streamPos > oldPos + 32768) {
        offset = -1;
        break;
      }

      header = (header << 8) | (uint8)stream.readByte();

      if (offset >= 0 && isValidHeader(header, frame.layer)) {
        if (!checkTypeAgainstLastFrame)
          break;

        const bool mpeg25 = (header & (1 << 20)) == 0;
        const uint32 lsf = mpeg25 ? 1 : ((header & (1 << 19)) ? 0 : 1);
        const uint32 sampleRateIndex = mpeg25
                                           ? (6 + ((header >> 10) & 3))
                                           : (((header >> 10) & 3) + (lsf * 3));
        const uint32 mode = (header >> 6) & 3;
        const uint32 numChannels = (mode == 3) ? 1 : 2;

        if (numChannels == (uint32)frame.numChannels &&
            lsf == (uint32)frame.lsf && mpeg25 == frame.mpeg25 &&
            sampleRateIndex == (uint32)frame.sampleRateIndex)
          break;
      }

      if (isParsingFirstFrame && offset == 0) {
        // If we're parsing the first frame of a file/stream, that frame must be
        // at the start of the stream (i.e.: the first four bytes must be a
        // valid MP3 header).
        //
        // If the first four bytes were a valid MP3 header, the above `if (...
        // isValidHeader)` check would have exited the `for` loop, and we'd
        // never get here.
        //
        // This prevents accidentally parsing .mp4 files (among others) as MP3
        // files that start with junk.
        offset = -1;
        break;
      }

      ++offset;
    }

    if (offset >= 0) {
      if ((currentFrameIndex & (storedStartPosInterval - 1)) == 0)
        frameStreamPositions.set(currentFrameIndex / storedStartPosInterval,
                                 oldPos + offset);

      ++currentFrameIndex;
    }

    stream.setPosition(oldPos);
    return offset;
  }