package com.mbridge.msdk.playercommon.exoplayer2.upstream; import android.net.Uri; import java.io.EOFException; import java.io.IOException; import java.io.RandomAccessFile; /* loaded from: classes4.dex */ public final class FileDataSource implements DataSource { private long bytesRemaining; private RandomAccessFile file; private final TransferListener listener; private boolean opened; private Uri uri; @Override // com.mbridge.msdk.playercommon.exoplayer2.upstream.DataSource public final Uri getUri() { return this.uri; } public static class FileDataSourceException extends IOException { public FileDataSourceException(IOException iOException) { super(iOException); } } public FileDataSource() { this(null); } public FileDataSource(TransferListener transferListener) { this.listener = transferListener; } @Override // com.mbridge.msdk.playercommon.exoplayer2.upstream.DataSource public final long open(DataSpec dataSpec) throws FileDataSourceException { try { this.uri = dataSpec.uri; RandomAccessFile randomAccessFile = new RandomAccessFile(dataSpec.uri.getPath(), "r"); this.file = randomAccessFile; randomAccessFile.seek(dataSpec.position); long j = dataSpec.length; if (j == -1) { j = this.file.length() - dataSpec.position; } this.bytesRemaining = j; if (j < 0) { throw new EOFException(); } this.opened = true; TransferListener transferListener = this.listener; if (transferListener != null) { transferListener.onTransferStart(this, dataSpec); } return this.bytesRemaining; } catch (IOException e) { throw new FileDataSourceException(e); } } @Override // com.mbridge.msdk.playercommon.exoplayer2.upstream.DataSource public final int read(byte[] bArr, int i, int i2) throws FileDataSourceException { if (i2 == 0) { return 0; } long j = this.bytesRemaining; if (j == 0) { return -1; } try { int read = this.file.read(bArr, i, (int) Math.min(j, i2)); if (read > 0) { this.bytesRemaining -= read; TransferListener transferListener = this.listener; if (transferListener != null) { transferListener.onBytesTransferred(this, read); } } return read; } catch (IOException e) { throw new FileDataSourceException(e); } } @Override // com.mbridge.msdk.playercommon.exoplayer2.upstream.DataSource public final void close() throws FileDataSourceException { this.uri = null; try { try { RandomAccessFile randomAccessFile = this.file; if (randomAccessFile != null) { randomAccessFile.close(); } } catch (IOException e) { throw new FileDataSourceException(e); } } finally { this.file = null; if (this.opened) { this.opened = false; TransferListener transferListener = this.listener; if (transferListener != null) { transferListener.onTransferEnd(this); } } } } }