Java Code Examples for com.google.android.exoplayer2.util.ParsableByteArray#getPosition()

The following examples show how to use com.google.android.exoplayer2.util.ParsableByteArray#getPosition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PsDurationReader.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private long readLastScrValueFromBuffer(ParsableByteArray packetBuffer) {
  int searchStartPosition = packetBuffer.getPosition();
  int searchEndPosition = packetBuffer.limit();
  for (int searchPosition = searchEndPosition - 4;
      searchPosition >= searchStartPosition;
      searchPosition--) {
    int nextStartCode = peekIntAtPosition(packetBuffer.data, searchPosition);
    if (nextStartCode == PsExtractor.PACK_START_CODE) {
      packetBuffer.setPosition(searchPosition + 4);
      long scrValue = readScrValueFromPack(packetBuffer);
      if (scrValue != C.TIME_UNSET) {
        return scrValue;
      }
    }
  }
  return C.TIME_UNSET;
}
 
Example 2
Source File: AtomParsers.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses a udta atom.
 *
 * @param udtaAtom The udta (user data) atom to decode.
 * @param isQuickTime True for QuickTime media. False otherwise.
 * @return Parsed metadata, or null.
 */
public static Metadata parseUdta(Atom.LeafAtom udtaAtom, boolean isQuickTime) {
  if (isQuickTime) {
    // Meta boxes are regular boxes rather than full boxes in QuickTime. For now, don't try and
    // decode one.
    return null;
  }
  ParsableByteArray udtaData = udtaAtom.data;
  udtaData.setPosition(Atom.HEADER_SIZE);
  while (udtaData.bytesLeft() >= Atom.HEADER_SIZE) {
    int atomPosition = udtaData.getPosition();
    int atomSize = udtaData.readInt();
    int atomType = udtaData.readInt();
    if (atomType == Atom.TYPE_meta) {
      udtaData.setPosition(atomPosition);
      return parseMetaAtom(udtaData, atomPosition + atomSize);
    }
    udtaData.skipBytes(atomSize - Atom.HEADER_SIZE);
  }
  return null;
}
 
Example 3
Source File: ProjectionDecoder.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private static @Nullable ArrayList<Mesh> parseProj(ParsableByteArray input) {
  input.skipBytes(8); // size and type.
  int position = input.getPosition();
  int limit = input.limit();
  while (position < limit) {
    int childEnd = position + input.readInt();
    if (childEnd <= position || childEnd > limit) {
      return null;
    }
    int childAtomType = input.readInt();
    // Some early files named the atom ytmp rather than mshp.
    if (childAtomType == TYPE_YTMP || childAtomType == TYPE_MSHP) {
      input.setLimit(childEnd);
      return parseMshp(input);
    }
    position = childEnd;
    input.setPosition(position);
  }
  return null;
}
 
Example 4
Source File: AtomParsers.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses encryption data from an audio/video sample entry, returning a pair consisting of the
 * unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common
 * encryption sinf atom was present.
 */
private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData(
    ParsableByteArray parent, int position, int size) {
  int childPosition = parent.getPosition();
  while (childPosition - position < size) {
    parent.setPosition(childPosition);
    int childAtomSize = parent.readInt();
    Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive");
    int childAtomType = parent.readInt();
    if (childAtomType == Atom.TYPE_sinf) {
      Pair<Integer, TrackEncryptionBox> result = parseCommonEncryptionSinfFromParent(parent,
          childPosition, childAtomSize);
      if (result != null) {
        return result;
      }
    }
    childPosition += childAtomSize;
  }
  return null;
}
 
Example 5
Source File: PsDurationReader.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private long readFirstScrValueFromBuffer(ParsableByteArray packetBuffer) {
  int searchStartPosition = packetBuffer.getPosition();
  int searchEndPosition = packetBuffer.limit();
  for (int searchPosition = searchStartPosition;
      searchPosition < searchEndPosition - 3;
      searchPosition++) {
    int nextStartCode = peekIntAtPosition(packetBuffer.data, searchPosition);
    if (nextStartCode == PsExtractor.PACK_START_CODE) {
      packetBuffer.setPosition(searchPosition + 4);
      long scrValue = readScrValueFromPack(packetBuffer);
      if (scrValue != C.TIME_UNSET) {
        return scrValue;
      }
    }
  }
  return C.TIME_UNSET;
}
 
Example 6
Source File: TsDurationReader.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private long readFirstPcrValueFromBuffer(ParsableByteArray packetBuffer, int pcrPid) {
  int searchStartPosition = packetBuffer.getPosition();
  int searchEndPosition = packetBuffer.limit();
  for (int searchPosition = searchStartPosition;
      searchPosition < searchEndPosition;
      searchPosition++) {
    if (packetBuffer.data[searchPosition] != TsExtractor.TS_SYNC_BYTE) {
      continue;
    }
    long pcrValue = TsUtil.readPcrFromPacket(packetBuffer, searchPosition, pcrPid);
    if (pcrValue != C.TIME_UNSET) {
      return pcrValue;
    }
  }
  return C.TIME_UNSET;
}
 
Example 7
Source File: WebvttDecoder.java    From K-Sonic with MIT License 6 votes vote down vote up
/**
 * Positions the input right before the next event, and returns the kind of event found. Does not
 * consume any data from such event, if any.
 *
 * @return The kind of event found.
 */
private static int getNextEvent(ParsableByteArray parsableWebvttData) {
  int foundEvent = EVENT_NONE;
  int currentInputPosition = 0;
  while (foundEvent == EVENT_NONE) {
    currentInputPosition = parsableWebvttData.getPosition();
    String line = parsableWebvttData.readLine();
    if (line == null) {
      foundEvent = EVENT_END_OF_FILE;
    } else if (STYLE_START.equals(line)) {
      foundEvent = EVENT_STYLE_BLOCK;
    } else if (COMMENT_START.startsWith(line)) {
      foundEvent = EVENT_COMMENT;
    } else {
      foundEvent = EVENT_CUE;
    }
  }
  parsableWebvttData.setPosition(currentInputPosition);
  return foundEvent;
}
 
Example 8
Source File: AdtsReader.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Peeks the Adts header of the current frame and checks if it is valid. If the header is valid,
 * transition to {@link #STATE_READING_ADTS_HEADER}; else, transition to {@link
 * #STATE_FINDING_SAMPLE}.
 */
private void checkAdtsHeader(ParsableByteArray buffer) {
  if (buffer.bytesLeft() == 0) {
    // Not enough data to check yet, defer this check.
    return;
  }
  // Peek the next byte of buffer into scratch array.
  adtsScratch.data[0] = buffer.data[buffer.getPosition()];

  adtsScratch.setPosition(2);
  int currentFrameSampleRateIndex = adtsScratch.readBits(4);
  if (firstFrameSampleRateIndex != C.INDEX_UNSET
      && currentFrameSampleRateIndex != firstFrameSampleRateIndex) {
    // Invalid header.
    resetSync();
    return;
  }

  if (!foundFirstFrame) {
    foundFirstFrame = true;
    firstFrameVersion = currentFrameVersion;
    firstFrameSampleRateIndex = currentFrameSampleRateIndex;
  }
  setReadingAdtsHeaderState();
}
 
Example 9
Source File: WebvttDecoder.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Positions the input right before the next event, and returns the kind of event found. Does not
 * consume any data from such event, if any.
 *
 * @return The kind of event found.
 */
private static int getNextEvent(ParsableByteArray parsableWebvttData) {
  int foundEvent = EVENT_NONE;
  int currentInputPosition = 0;
  while (foundEvent == EVENT_NONE) {
    currentInputPosition = parsableWebvttData.getPosition();
    String line = parsableWebvttData.readLine();
    if (line == null) {
      foundEvent = EVENT_END_OF_FILE;
    } else if (STYLE_START.equals(line)) {
      foundEvent = EVENT_STYLE_BLOCK;
    } else if (line.startsWith(COMMENT_START)) {
      foundEvent = EVENT_COMMENT;
    } else {
      foundEvent = EVENT_CUE;
    }
  }
  parsableWebvttData.setPosition(currentInputPosition);
  return foundEvent;
}
 
Example 10
Source File: CssParser.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private static String parsePropertyValue(ParsableByteArray input, StringBuilder stringBuilder) {
  StringBuilder expressionBuilder = new StringBuilder();
  String token;
  int position;
  boolean expressionEndFound = false;
  // TODO: Add support for "Strings in quotes with spaces".
  while (!expressionEndFound) {
    position = input.getPosition();
    token = parseNextToken(input, stringBuilder);
    if (token == null) {
      // Syntax error.
      return null;
    }
    if (RULE_END.equals(token) || ";".equals(token)) {
      input.setPosition(position);
      expressionEndFound = true;
    } else {
      expressionBuilder.append(token);
    }
  }
  return expressionBuilder.toString();
}
 
Example 11
Source File: TsDurationReader.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
private long readFirstPcrValueFromBuffer(ParsableByteArray packetBuffer, int pcrPid) {
  int searchStartPosition = packetBuffer.getPosition();
  int searchEndPosition = packetBuffer.limit();
  for (int searchPosition = searchStartPosition;
      searchPosition < searchEndPosition;
      searchPosition++) {
    if (packetBuffer.data[searchPosition] != TsExtractor.TS_SYNC_BYTE) {
      continue;
    }
    long pcrValue = readPcrFromPacket(packetBuffer, searchPosition, pcrPid);
    if (pcrValue != C.TIME_UNSET) {
      return pcrValue;
    }
  }
  return C.TIME_UNSET;
}
 
Example 12
Source File: AtomParsers.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
private static Metadata parseUdtaMeta(ParsableByteArray meta, int limit) {
  meta.skipBytes(Atom.FULL_HEADER_SIZE);
  while (meta.getPosition() < limit) {
    int atomPosition = meta.getPosition();
    int atomSize = meta.readInt();
    int atomType = meta.readInt();
    if (atomType == Atom.TYPE_ilst) {
      meta.setPosition(atomPosition);
      return parseIlst(meta, atomPosition + atomSize);
    }
    meta.setPosition(atomPosition + atomSize);
  }
  return null;
}
 
Example 13
Source File: AtomParsers.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
private static Metadata parseIlst(ParsableByteArray ilst, int limit) {
  ilst.skipBytes(Atom.HEADER_SIZE);
  ArrayList<Metadata.Entry> entries = new ArrayList<>();
  while (ilst.getPosition() < limit) {
    Metadata.Entry entry = MetadataUtil.parseIlstElement(ilst);
    if (entry != null) {
      entries.add(entry);
    }
  }
  return entries.isEmpty() ? null : new Metadata(entries);
}
 
Example 14
Source File: ScriptTagPayloadReader.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read a string from an AMF encoded buffer.
 *
 * @param data The buffer from which to read.
 * @return The value read from the buffer.
 */
private static String readAmfString(ParsableByteArray data) {
  int size = data.readUnsignedShort();
  int position = data.getPosition();
  data.skipBytes(size);
  return new String(data.data, position, size);
}
 
Example 15
Source File: MatroskaExtractor.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds initialization data for a {@link Format} from FourCC codec private data.
 *
 * <p>VC1 and H263 are the only supported compression types.
 *
 * @return The codec mime type and initialization data. If the compression type is not supported
 *     then the mime type is set to {@link MimeTypes#VIDEO_UNKNOWN} and the initialization data
 *     is {@code null}.
 * @throws ParserException If the initialization data could not be built.
 */
private static Pair<String, List<byte[]>> parseFourCcPrivate(ParsableByteArray buffer)
    throws ParserException {
  try {
    buffer.skipBytes(16); // size(4), width(4), height(4), planes(2), bitcount(2).
    long compression = buffer.readLittleEndianUnsignedInt();
    if (compression == FOURCC_COMPRESSION_DIVX) {
      return new Pair<>(MimeTypes.VIDEO_H263, null);
    } else if (compression == FOURCC_COMPRESSION_VC1) {
      // Search for the initialization data from the end of the BITMAPINFOHEADER. The last 20
      // bytes of which are: sizeImage(4), xPel/m (4), yPel/m (4), clrUsed(4), clrImportant(4).
      int startOffset = buffer.getPosition() + 20;
      byte[] bufferData = buffer.data;
      for (int offset = startOffset; offset < bufferData.length - 4; offset++) {
        if (bufferData[offset] == 0x00
            && bufferData[offset + 1] == 0x00
            && bufferData[offset + 2] == 0x01
            && bufferData[offset + 3] == 0x0F) {
          // We've found the initialization data.
          byte[] initializationData = Arrays.copyOfRange(bufferData, offset, bufferData.length);
          return new Pair<>(MimeTypes.VIDEO_VC1, Collections.singletonList(initializationData));
        }
      }
      throw new ParserException("Failed to find FourCC VC1 initialization data");
    }
  } catch (ArrayIndexOutOfBoundsException e) {
    throw new ParserException("Error parsing FourCC private data");
  }

  Log.w(TAG, "Unknown FourCC. Setting mimeType to " + MimeTypes.VIDEO_UNKNOWN);
  return new Pair<>(MimeTypes.VIDEO_UNKNOWN, null);
}
 
Example 16
Source File: AtomParsers.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the position of the esds box within a parent, or {@link C#POSITION_UNSET} if no esds
 * box is found
 */
private static int findEsdsPosition(ParsableByteArray parent, int position, int size) {
  int childAtomPosition = parent.getPosition();
  while (childAtomPosition - position < size) {
    parent.setPosition(childAtomPosition);
    int childAtomSize = parent.readInt();
    Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive");
    int childType = parent.readInt();
    if (childType == Atom.TYPE_esds) {
      return childAtomPosition;
    }
    childAtomPosition += childAtomSize;
  }
  return C.POSITION_UNSET;
}
 
Example 17
Source File: CssParser.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Takes a CSS style block and consumes up to the first empty line. Attempts to parse the contents
 * of the style block and returns a list of {@link WebvttCssStyle} instances if successful. If
 * parsing fails, it returns a list including only the styles which have been successfully parsed
 * up to the style rule which was malformed.
 *
 * @param input The input from which the style block should be read.
 * @return A list of {@link WebvttCssStyle}s that represents the parsed block, or a list
 *     containing the styles up to the parsing failure.
 */
public List<WebvttCssStyle> parseBlock(ParsableByteArray input) {
  stringBuilder.setLength(0);
  int initialInputPosition = input.getPosition();
  skipStyleBlock(input);
  styleInput.reset(input.data, input.getPosition());
  styleInput.setPosition(initialInputPosition);

  List<WebvttCssStyle> styles = new ArrayList<>();
  String selector;
  while ((selector = parseSelector(styleInput, stringBuilder)) != null) {
    if (!RULE_START.equals(parseNextToken(styleInput, stringBuilder))) {
      return styles;
    }
    WebvttCssStyle style = new WebvttCssStyle();
    applySelectorToStyle(style, selector);
    String token = null;
    boolean blockEndFound = false;
    while (!blockEndFound) {
      int position = styleInput.getPosition();
      token = parseNextToken(styleInput, stringBuilder);
      blockEndFound = token == null || RULE_END.equals(token);
      if (!blockEndFound) {
        styleInput.setPosition(position);
        parseStyleDeclaration(styleInput, style, stringBuilder);
      }
    }
    // Check that the style rule ended correctly.
    if (RULE_END.equals(token)) {
      styles.add(style);
    }
  }
  return styles;
}
 
Example 18
Source File: H264Reader.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void consume(ParsableByteArray data) {
  int offset = data.getPosition();
  int limit = data.limit();
  byte[] dataArray = data.data;

  // Append the data to the buffer.
  totalBytesWritten += data.bytesLeft();
  output.sampleData(data, data.bytesLeft());

  // Scan the appended data, processing NAL units as they are encountered
  while (true) {
    int nalUnitOffset = NalUnitUtil.findNalUnit(dataArray, offset, limit, prefixFlags);

    if (nalUnitOffset == limit) {
      // We've scanned to the end of the data without finding the start of another NAL unit.
      nalUnitData(dataArray, offset, limit);
      return;
    }

    // We've seen the start of a NAL unit of the following type.
    int nalUnitType = NalUnitUtil.getNalUnitType(dataArray, nalUnitOffset);

    // This is the number of bytes from the current offset to the start of the next NAL unit.
    // It may be negative if the NAL unit started in the previously consumed data.
    int lengthToNalUnit = nalUnitOffset - offset;
    if (lengthToNalUnit > 0) {
      nalUnitData(dataArray, offset, nalUnitOffset);
    }
    int bytesWrittenPastPosition = limit - nalUnitOffset;
    long absolutePosition = totalBytesWritten - bytesWrittenPastPosition;
    // Indicate the end of the previous NAL unit. If the length to the start of the next unit
    // is negative then we wrote too many bytes to the NAL buffers. Discard the excess bytes
    // when notifying that the unit has ended.
    endNalUnit(absolutePosition, bytesWrittenPastPosition,
        lengthToNalUnit < 0 ? -lengthToNalUnit : 0, pesTimeUs);
    // Indicate the start of the next NAL unit.
    startNalUnit(absolutePosition, nalUnitType, pesTimeUs);
    // Continue scanning the data.
    offset = nalUnitOffset + 3;
  }
}
 
Example 19
Source File: AtomParsers.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses a metadata meta atom if it contains metadata with handler 'mdta'.
 *
 * @param meta The metadata atom to decode.
 * @return Parsed metadata, or null.
 */
@Nullable
public static Metadata parseMdtaFromMeta(Atom.ContainerAtom meta) {
  Atom.LeafAtom hdlrAtom = meta.getLeafAtomOfType(Atom.TYPE_hdlr);
  Atom.LeafAtom keysAtom = meta.getLeafAtomOfType(Atom.TYPE_keys);
  Atom.LeafAtom ilstAtom = meta.getLeafAtomOfType(Atom.TYPE_ilst);
  if (hdlrAtom == null
      || keysAtom == null
      || ilstAtom == null
      || AtomParsers.parseHdlr(hdlrAtom.data) != TYPE_mdta) {
    // There isn't enough information to parse the metadata, or the handler type is unexpected.
    return null;
  }

  // Parse metadata keys.
  ParsableByteArray keys = keysAtom.data;
  keys.setPosition(Atom.FULL_HEADER_SIZE);
  int entryCount = keys.readInt();
  String[] keyNames = new String[entryCount];
  for (int i = 0; i < entryCount; i++) {
    int entrySize = keys.readInt();
    keys.skipBytes(4); // keyNamespace
    int keySize = entrySize - 8;
    keyNames[i] = keys.readString(keySize);
  }

  // Parse metadata items.
  ParsableByteArray ilst = ilstAtom.data;
  ilst.setPosition(Atom.HEADER_SIZE);
  ArrayList<Metadata.Entry> entries = new ArrayList<>();
  while (ilst.bytesLeft() > Atom.HEADER_SIZE) {
    int atomPosition = ilst.getPosition();
    int atomSize = ilst.readInt();
    int keyIndex = ilst.readInt() - 1;
    if (keyIndex >= 0 && keyIndex < keyNames.length) {
      String key = keyNames[keyIndex];
      Metadata.Entry entry =
          MetadataUtil.parseMdtaMetadataEntryFromIlst(ilst, atomPosition + atomSize, key);
      if (entry != null) {
        entries.add(entry);
      }
    } else {
      Log.w(TAG, "Skipped metadata with unknown key index: " + keyIndex);
    }
    ilst.setPosition(atomPosition + atomSize);
  }
  return entries.isEmpty() ? null : new Metadata(entries);
}
 
Example 20
Source File: AvcConfig.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
private static byte[] buildNalUnitForChild(ParsableByteArray data) {
  int length = data.readUnsignedShort();
  int offset = data.getPosition();
  data.skipBytes(length);
  return CodecSpecificDataUtil.buildNalUnit(data.data, offset, length);
}