Java Code Examples for com.google.android.exoplayer2.util.Util#closeQuietly()

The following examples show how to use com.google.android.exoplayer2.util.Util#closeQuietly() . 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: CacheDataSink.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("ThrowFromFinallyBlock")
private void closeCurrentOutputStream() throws IOException {
  if (outputStream == null) {
    return;
  }

  boolean success = false;
  try {
    outputStream.flush();
    success = true;
  } finally {
    Util.closeQuietly(outputStream);
    outputStream = null;
    File fileToCommit = file;
    file = null;
    if (success) {
      cache.commitFile(fileToCommit, outputStreamBytesWritten);
    } else {
      fileToCommit.delete();
    }
  }
}
 
Example 2
Source File: InitializationChunk.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    ExtractorInput input = new DefaultExtractorInput(dataSource,
        loadDataSpec.absoluteStreamPosition, dataSource.open(loadDataSpec));
    if (nextLoadPosition == 0) {
      extractorWrapper.init(/* trackOutputProvider= */ null, C.TIME_UNSET);
    }
    // Load and decode the initialization data.
    try {
      Extractor extractor = extractorWrapper.extractor;
      int result = Extractor.RESULT_CONTINUE;
      while (result == Extractor.RESULT_CONTINUE && !loadCanceled) {
        result = extractor.read(input, DUMMY_POSITION_HOLDER);
      }
      Assertions.checkState(result != Extractor.RESULT_SEEK);
    } finally {
      nextLoadPosition = input.getPosition() - dataSpec.absoluteStreamPosition;
    }
  } finally {
    Util.closeQuietly(dataSource);
  }
}
 
Example 3
Source File: CacheDataSink.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("ThrowFromFinallyBlock")
private void closeCurrentOutputStream() throws IOException {
  if (outputStream == null) {
    return;
  }

  boolean success = false;
  try {
    outputStream.flush();
    success = true;
  } finally {
    Util.closeQuietly(outputStream);
    outputStream = null;
    File fileToCommit = file;
    file = null;
    if (success) {
      cache.commitFile(fileToCommit, outputStreamBytesWritten);
    } else {
      fileToCommit.delete();
    }
  }
}
 
Example 4
Source File: DownloadManager.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private void initialize(int notMetRequirements) {
  this.notMetRequirements = notMetRequirements;
  DownloadCursor cursor = null;
  try {
    downloadIndex.setDownloadingStatesToQueued();
    cursor =
        downloadIndex.getDownloads(
            STATE_QUEUED, STATE_STOPPED, STATE_DOWNLOADING, STATE_REMOVING, STATE_RESTARTING);
    while (cursor.moveToNext()) {
      downloads.add(cursor.getDownload());
    }
  } catch (IOException e) {
    Log.e(TAG, "Failed to load index.", e);
    downloads.clear();
  } finally {
    Util.closeQuietly(cursor);
  }
  // A copy must be used for the message to ensure that subsequent changes to the downloads list
  // are not visible to the main thread when it processes the message.
  ArrayList<Download> downloadsForMessage = new ArrayList<>(downloads);
  mainHandler.obtainMessage(MSG_INITIALIZED, downloadsForMessage).sendToTarget();
  syncTasks();
}
 
Example 5
Source File: DownloadManager.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private void initialize(int notMetRequirements) {
  this.notMetRequirements = notMetRequirements;
  DownloadCursor cursor = null;
  try {
    downloadIndex.setDownloadingStatesToQueued();
    cursor =
        downloadIndex.getDownloads(
            STATE_QUEUED, STATE_STOPPED, STATE_DOWNLOADING, STATE_REMOVING, STATE_RESTARTING);
    while (cursor.moveToNext()) {
      downloads.add(cursor.getDownload());
    }
  } catch (IOException e) {
    Log.e(TAG, "Failed to load index.", e);
    downloads.clear();
  } finally {
    Util.closeQuietly(cursor);
  }
  // A copy must be used for the message to ensure that subsequent changes to the downloads list
  // are not visible to the main thread when it processes the message.
  ArrayList<Download> downloadsForMessage = new ArrayList<>(downloads);
  mainHandler.obtainMessage(MSG_INITIALIZED, downloadsForMessage).sendToTarget();
  syncTasks();
}
 
Example 6
Source File: CacheDataSink.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("ThrowFromFinallyBlock")
private void closeCurrentOutputStream() throws IOException {
  if (outputStream == null) {
    return;
  }

  boolean success = false;
  try {
    outputStream.flush();
    if (syncFileDescriptor) {
      underlyingFileOutputStream.getFD().sync();
    }
    success = true;
  } finally {
    Util.closeQuietly(outputStream);
    outputStream = null;
    File fileToCommit = file;
    file = null;
    if (success) {
      cache.commitFile(fileToCommit);
    } else {
      fileToCommit.delete();
    }
  }
}
 
Example 7
Source File: ParsingLoadable.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public final void load() throws IOException {
  // We always load from the beginning, so reset bytesRead to 0.
  dataSource.resetBytesRead();
  DataSourceInputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
  try {
    inputStream.open();
    Uri dataSourceUri = Assertions.checkNotNull(dataSource.getUri());
    result = parser.parse(dataSourceUri, inputStream);
  } finally {
    Util.closeQuietly(inputStream);
  }
}
 
Example 8
Source File: SingleSampleMediaChunk.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    long length = dataSource.open(loadDataSpec);
    if (length != C.LENGTH_UNSET) {
      length += nextLoadPosition;
    }
    ExtractorInput extractorInput =
        new DefaultExtractorInput(dataSource, nextLoadPosition, length);
    BaseMediaChunkOutput output = getOutput();
    output.setSampleOffsetUs(0);
    TrackOutput trackOutput = output.track(0, trackType);
    trackOutput.format(sampleFormat);
    // Load the sample data.
    int result = 0;
    while (result != C.RESULT_END_OF_INPUT) {
      nextLoadPosition += result;
      result = trackOutput.sampleData(extractorInput, Integer.MAX_VALUE, true);
    }
    int sampleSize = (int) nextLoadPosition;
    trackOutput.sampleMetadata(startTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example 9
Source File: HttpMediaDrmCallback.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] executePost(HttpDataSource.Factory dataSourceFactory, String url,
    byte[] data, Map<String, String> requestProperties) throws IOException {
  HttpDataSource dataSource = dataSourceFactory.createDataSource();
  if (requestProperties != null) {
    for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
      dataSource.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
    }
  }

  int manualRedirectCount = 0;
  while (true) {
    DataSpec dataSpec =
        new DataSpec(
            Uri.parse(url),
            data,
            /* absoluteStreamPosition= */ 0,
            /* position= */ 0,
            /* length= */ C.LENGTH_UNSET,
            /* key= */ null,
            DataSpec.FLAG_ALLOW_GZIP);
    DataSourceInputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
    try {
      return Util.toByteArray(inputStream);
    } catch (InvalidResponseCodeException e) {
      // For POST requests, the underlying network stack will not normally follow 307 or 308
      // redirects automatically. Do so manually here.
      boolean manuallyRedirect =
          (e.responseCode == 307 || e.responseCode == 308)
              && manualRedirectCount++ < MAX_MANUAL_REDIRECTS;
      url = manuallyRedirect ? getRedirectUrl(e) : null;
      if (url == null) {
        throw e;
      }
    } finally {
      Util.closeQuietly(inputStream);
    }
  }
}
 
Example 10
Source File: ParsingLoadable.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void load() throws IOException {
  // We always load from the beginning, so reset bytesRead to 0.
  dataSource.resetBytesRead();
  DataSourceInputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
  try {
    inputStream.open();
    Uri dataSourceUri = Assertions.checkNotNull(dataSource.getUri());
    result = parser.parse(dataSourceUri, inputStream);
  } finally {
    Util.closeQuietly(inputStream);
  }
}
 
Example 11
Source File: SingleSampleMediaChunk.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    long length = dataSource.open(loadDataSpec);
    if (length != C.LENGTH_UNSET) {
      length += nextLoadPosition;
    }
    ExtractorInput extractorInput =
        new DefaultExtractorInput(dataSource, nextLoadPosition, length);
    BaseMediaChunkOutput output = getOutput();
    output.setSampleOffsetUs(0);
    TrackOutput trackOutput = output.track(0, trackType);
    trackOutput.format(sampleFormat);
    // Load the sample data.
    int result = 0;
    while (result != C.RESULT_END_OF_INPUT) {
      nextLoadPosition += result;
      result = trackOutput.sampleData(extractorInput, Integer.MAX_VALUE, true);
    }
    int sampleSize = (int) nextLoadPosition;
    trackOutput.sampleMetadata(startTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example 12
Source File: SingleSampleMediaChunk.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    long length = dataSource.open(loadDataSpec);
    if (length != C.LENGTH_UNSET) {
      length += nextLoadPosition;
    }
    ExtractorInput extractorInput =
        new DefaultExtractorInput(dataSource, nextLoadPosition, length);
    BaseMediaChunkOutput output = getOutput();
    output.setSampleOffsetUs(0);
    TrackOutput trackOutput = output.track(0, trackType);
    trackOutput.format(sampleFormat);
    // Load the sample data.
    int result = 0;
    while (result != C.RESULT_END_OF_INPUT) {
      nextLoadPosition += result;
      result = trackOutput.sampleData(extractorInput, Integer.MAX_VALUE, true);
    }
    int sampleSize = (int) nextLoadPosition;
    trackOutput.sampleMetadata(startTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example 13
Source File: ParsingLoadable.java    From K-Sonic with MIT License 5 votes vote down vote up
@Override
public final void load() throws IOException, InterruptedException {
  DataSourceInputStream inputStream = new DataSourceInputStream(dataSource, dataSpec);
  try {
    inputStream.open();
    result = parser.parse(dataSource.getUri(), inputStream);
  } finally {
    bytesLoaded = inputStream.bytesRead();
    Util.closeQuietly(inputStream);
  }
}
 
Example 14
Source File: ContainerMediaChunk.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public final void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    ExtractorInput input = new DefaultExtractorInput(dataSource,
        loadDataSpec.absoluteStreamPosition, dataSource.open(loadDataSpec));
    if (nextLoadPosition == 0) {
      // Configure the output and set it as the target for the extractor wrapper.
      BaseMediaChunkOutput output = getOutput();
      output.setSampleOffsetUs(sampleOffsetUs);
      extractorWrapper.init(
          getTrackOutputProvider(output),
          clippedStartTimeUs == C.TIME_UNSET
              ? C.TIME_UNSET
              : (clippedStartTimeUs - sampleOffsetUs),
          clippedEndTimeUs == C.TIME_UNSET ? C.TIME_UNSET : (clippedEndTimeUs - sampleOffsetUs));
    }
    // Load and decode the sample data.
    try {
      Extractor extractor = extractorWrapper.extractor;
      int result = Extractor.RESULT_CONTINUE;
      while (result == Extractor.RESULT_CONTINUE && !loadCanceled) {
        result = extractor.read(input, DUMMY_POSITION_HOLDER);
      }
      Assertions.checkState(result != Extractor.RESULT_SEEK);
    } finally {
      nextLoadPosition = input.getPosition() - dataSpec.absoluteStreamPosition;
    }
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example 15
Source File: SingleSampleMediaChunk.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = dataSpec.subrange(nextLoadPosition);
  try {
    // Create and open the input.
    long length = dataSource.open(loadDataSpec);
    if (length != C.LENGTH_UNSET) {
      length += nextLoadPosition;
    }
    ExtractorInput extractorInput =
        new DefaultExtractorInput(dataSource, nextLoadPosition, length);
    BaseMediaChunkOutput output = getOutput();
    output.setSampleOffsetUs(0);
    TrackOutput trackOutput = output.track(0, trackType);
    trackOutput.format(sampleFormat);
    // Load the sample data.
    int result = 0;
    while (result != C.RESULT_END_OF_INPUT) {
      nextLoadPosition += result;
      result = trackOutput.sampleData(extractorInput, Integer.MAX_VALUE, true);
    }
    int sampleSize = (int) nextLoadPosition;
    trackOutput.sampleMetadata(startTimeUs, C.BUFFER_FLAG_KEY_FRAME, sampleSize, 0, null);
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example 16
Source File: HlsPlaylistParser.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public HlsPlaylist parse(Uri uri, InputStream inputStream) throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  Queue<String> extraLines = new ArrayDeque<>();
  String line;
  try {
    if (!checkPlaylistHeader(reader)) {
      throw new UnrecognizedInputFormatException("Input does not start with the #EXTM3U header.",
          uri);
    }
    while ((line = reader.readLine()) != null) {
      line = line.trim();
      if (line.isEmpty()) {
        // Do nothing.
      } else if (line.startsWith(TAG_STREAM_INF)) {
        extraLines.add(line);
        return parseMasterPlaylist(new LineIterator(extraLines, reader), uri.toString());
      } else if (line.startsWith(TAG_TARGET_DURATION)
          || line.startsWith(TAG_MEDIA_SEQUENCE)
          || line.startsWith(TAG_MEDIA_DURATION)
          || line.startsWith(TAG_KEY)
          || line.startsWith(TAG_BYTERANGE)
          || line.equals(TAG_DISCONTINUITY)
          || line.equals(TAG_DISCONTINUITY_SEQUENCE)
          || line.equals(TAG_ENDLIST)) {
        extraLines.add(line);
        return parseMediaPlaylist(new LineIterator(extraLines, reader), uri.toString());
      } else {
        extraLines.add(line);
      }
    }
  } finally {
    Util.closeQuietly(reader);
  }
  throw new ParserException("Failed to parse the playlist, could not identify any tags.");
}
 
Example 17
Source File: ContainerMediaChunk.java    From K-Sonic with MIT License 5 votes vote down vote up
@SuppressWarnings("NonAtomicVolatileUpdate")
@Override
public final void load() throws IOException, InterruptedException {
  DataSpec loadDataSpec = Util.getRemainderDataSpec(dataSpec, bytesLoaded);
  try {
    // Create and open the input.
    ExtractorInput input = new DefaultExtractorInput(dataSource,
        loadDataSpec.absoluteStreamPosition, dataSource.open(loadDataSpec));
    if (bytesLoaded == 0) {
      // Configure the output and set it as the target for the extractor wrapper.
      BaseMediaChunkOutput output = getOutput();
      output.setSampleOffsetUs(sampleOffsetUs);
      extractorWrapper.init(output);
    }
    // Load and decode the sample data.
    try {
      Extractor extractor = extractorWrapper.extractor;
      int result = Extractor.RESULT_CONTINUE;
      while (result == Extractor.RESULT_CONTINUE && !loadCanceled) {
        result = extractor.read(input, null);
      }
      Assertions.checkState(result != Extractor.RESULT_SEEK);
    } finally {
      bytesLoaded = (int) (input.getPosition() - dataSpec.absoluteStreamPosition);
    }
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}
 
Example 18
Source File: HlsPlaylistParser.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public HlsPlaylist parse(Uri uri, InputStream inputStream) throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  Queue<String> extraLines = new ArrayDeque<>();
  String line;
  try {
    if (!checkPlaylistHeader(reader)) {
      throw new UnrecognizedInputFormatException("Input does not start with the #EXTM3U header.",
          uri);
    }
    while ((line = reader.readLine()) != null) {
      line = line.trim();
      if (line.isEmpty()) {
        // Do nothing.
      } else if (line.startsWith(TAG_STREAM_INF)) {
        extraLines.add(line);
        return parseMasterPlaylist(new LineIterator(extraLines, reader), uri.toString());
      } else if (line.startsWith(TAG_TARGET_DURATION)
          || line.startsWith(TAG_MEDIA_SEQUENCE)
          || line.startsWith(TAG_MEDIA_DURATION)
          || line.startsWith(TAG_KEY)
          || line.startsWith(TAG_BYTERANGE)
          || line.equals(TAG_DISCONTINUITY)
          || line.equals(TAG_DISCONTINUITY_SEQUENCE)
          || line.equals(TAG_ENDLIST)) {
        extraLines.add(line);
        return parseMediaPlaylist(
            masterPlaylist, new LineIterator(extraLines, reader), uri.toString());
      } else {
        extraLines.add(line);
      }
    }
  } finally {
    Util.closeQuietly(reader);
  }
  throw new ParserException("Failed to parse the playlist, could not identify any tags.");
}
 
Example 19
Source File: HlsPlaylistParser.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public HlsPlaylist parse(Uri uri, InputStream inputStream) throws IOException {
  BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  Queue<String> extraLines = new ArrayDeque<>();
  String line;
  try {
    if (!checkPlaylistHeader(reader)) {
      throw new UnrecognizedInputFormatException("Input does not start with the #EXTM3U header.",
          uri);
    }
    while ((line = reader.readLine()) != null) {
      line = line.trim();
      if (line.isEmpty()) {
        // Do nothing.
      } else if (line.startsWith(TAG_STREAM_INF)) {
        extraLines.add(line);
        return parseMasterPlaylist(new LineIterator(extraLines, reader), uri.toString());
      } else if (line.startsWith(TAG_TARGET_DURATION)
          || line.startsWith(TAG_MEDIA_SEQUENCE)
          || line.startsWith(TAG_MEDIA_DURATION)
          || line.startsWith(TAG_KEY)
          || line.startsWith(TAG_BYTERANGE)
          || line.equals(TAG_DISCONTINUITY)
          || line.equals(TAG_DISCONTINUITY_SEQUENCE)
          || line.equals(TAG_ENDLIST)) {
        extraLines.add(line);
        return parseMediaPlaylist(
            masterPlaylist, new LineIterator(extraLines, reader), uri.toString());
      } else {
        extraLines.add(line);
      }
    }
  } finally {
    Util.closeQuietly(reader);
  }
  throw new ParserException("Failed to parse the playlist, could not identify any tags.");
}
 
Example 20
Source File: HlsMediaChunk.java    From K-Sonic with MIT License 4 votes vote down vote up
private void loadMedia() throws IOException, InterruptedException {
  // If we previously fed part of this chunk to the extractor, we need to skip it this time. For
  // encrypted content we need to skip the data by reading it through the source, so as to ensure
  // correct decryption of the remainder of the chunk. For clear content, we can request the
  // remainder of the chunk directly.
  DataSpec loadDataSpec;
  boolean skipLoadedBytes;
  if (isEncrypted) {
    loadDataSpec = dataSpec;
    skipLoadedBytes = bytesLoaded != 0;
  } else {
    loadDataSpec = Util.getRemainderDataSpec(dataSpec, bytesLoaded);
    skipLoadedBytes = false;
  }
  if (!isMasterTimestampSource) {
    timestampAdjuster.waitUntilInitialized();
  } else if (timestampAdjuster.getFirstSampleTimestampUs() == TimestampAdjuster.DO_NOT_OFFSET) {
    // We're the master and we haven't set the desired first sample timestamp yet.
    timestampAdjuster.setFirstSampleTimestampUs(startTimeUs);
  }
  try {
    ExtractorInput input = new DefaultExtractorInput(dataSource,
        loadDataSpec.absoluteStreamPosition, dataSource.open(loadDataSpec));
    if (extractor == null) {
      // Media segment format is packed audio.
      long id3Timestamp = peekId3PrivTimestamp(input);
      extractor = buildPackedAudioExtractor(id3Timestamp != C.TIME_UNSET
          ? timestampAdjuster.adjustTsTimestamp(id3Timestamp) : startTimeUs);
    }
    if (skipLoadedBytes) {
      input.skipFully(bytesLoaded);
    }
    try {
      int result = Extractor.RESULT_CONTINUE;
      while (result == Extractor.RESULT_CONTINUE && !loadCanceled) {
        result = extractor.read(input, null);
      }
    } finally {
      bytesLoaded = (int) (input.getPosition() - dataSpec.absoluteStreamPosition);
    }
  } finally {
    Util.closeQuietly(dataSource);
  }
  loadCompleted = true;
}