ExoPlayer之SampleQueue

之前分析ExoPlayer的流程是source->buffer,从数据源读取数据到buffer中,在ExoPlayer中是用SampleQueue来保存buffer。下面看下SampleQueue是怎么工作的。
SampleQueue类有个SampleDataQueue变量,读取的数据真正保存在SampleDataQueue中,

/** A queue of media sample data. */
/* package */ class SampleDataQueue {
  // References into the linked list of allocations.
  private AllocationNode firstAllocationNode;
  private AllocationNode readAllocationNode;
  private AllocationNode writeAllocationNode;

public SampleDataQueue(Allocator allocator) {
    this.allocator = allocator;
    allocationLength = allocator.getIndividualAllocationLength();\\64 * 1024
    scratch = new ParsableByteArray(INITIAL_SCRATCH_SIZE);
    firstAllocationNode = new AllocationNode(/* startPosition= */ 0, allocationLength);
    readAllocationNode = firstAllocationNode;
    writeAllocationNode = firstAllocationNode;
  }
}

SampleDataQueue初始化时先生成一个AllocationNode,每个AllocationNode的大小是allocationLength (64 * 1024),读写指针都指向这个AllocationNode。

先来分析writeAllocationNode 的工作,从数据源读取数据写入writeAllocationNode ,数据源封装在DefaultDataSource,读取数据时调用:

@Override
  public int read(byte[] buffer, int offset, int readLength) throws IOException {
    return Assertions.checkNotNull(dataSource).read(buffer, offset, readLength);
  }

对于mp4文件,dataSource就是FileDataSource,其实最终是通过FileDataSource去读取:

try {
        bytesRead = castNonNull(file).read(buffer, offset, (int) min(bytesRemaining, readLength));
      } catch (IOException e) {
        throw new FileDataSourceException(e);
      }

在FileDataSource中,file被定义为RandomAccessFile file。下面看怎么把上面的几个类串起来。
在Mp4Extractor里解析mp4文件,对于Sample调用readSample保存:

 private int readSample(ExtractorInput input, PositionHolder positionHolder) throws IOException {
 while (sampleBytesWritten < sampleSize) {
        int writtenBytes = trackOutput.sampleData(input, sampleSize - sampleBytesWritten, false);
        sampleBytesRead += writtenBytes;
        sampleBytesWritten += writtenBytes;
        sampleCurrentNalBytesRemaining -= writtenBytes;
      }
}

trackOutput就是SampleQueue,input就是FileDataSource。SampleQueue又调用SampleDataQueue的sampleData的方法:

public int sampleData(DataReader input, int length, boolean allowEndOfInput) throws IOException {
    length = preAppend(length);
    int bytesAppended =
        input.read(
            writeAllocationNode.allocation.data,
            writeAllocationNode.translateOffset(totalBytesWritten),
            length);
    postAppend(bytesAppended);
    return bytesAppended;
  }

读取数据前先调用preAppend,如果writeAllocationNode没有初始化,就把当前writeAllocationNode初始化,并在队尾添加一个没有初始化的writeAllocationNode:

 private int preAppend(int length) {
    if (!writeAllocationNode.wasInitialized) {
      writeAllocationNode.initialize(
          allocator.allocate(),
          new AllocationNode(writeAllocationNode.endPosition, allocationLength));
    }
    return min(length, (int) (writeAllocationNode.endPosition - totalBytesWritten));
  }

注意,这里调用initialize,赋值了个Allocation(allocator.allocate()),allocator是DefaultAllocator,分配了64 * 1024的空间给Allocation,看Allocation的定义:

public final class Allocation {
    public final byte[] data;
    public final int offset;
}

由此可见,读取的数据最终保存在Allocation 的data里。这里还有个细节,每个Allocation 是串起来的,下次有数据读过来时,当前的Allocation 还没填满,这时就要计算偏移量了,计算出在当前Allocation 的哪个位置开始填充,上面的translateOffset就是做这件事:

//absolutePosition是当前读的数据总长度,startPosition是当前Allocation 的起点,减后就得到当前Allocation 要填充的起始位置
    public int translateOffset(long absolutePosition) {
      return (int) (absolutePosition - startPosition) + allocation.offset;
    }

AllocationNode填充完当前读到的数据,调用postAppend来看当前的writeAllocationNode是否填满了,如果填满了,writeAllocationNode指针就走到下一个:

  private void postAppend(int length) {
    totalBytesWritten += length;
    if (totalBytesWritten == writeAllocationNode.endPosition) {
      writeAllocationNode = writeAllocationNode.next;
    }
  }

然后看readAllocationNode的使用,Exoplayer不断循环调用doSomething,会调到MediaCodecRenderer的feedInputBuffer() ,就是读取Sample往MediaCodec解码器的 InputBuffer填充,最终调到readAllocationNode(SampleDataQueue)的readData方法:

private void readData(long absolutePosition, ByteBuffer target, int length) {
    advanceReadTo(absolutePosition);
    int remaining = length;
    while (remaining > 0) {
      int toCopy = min(remaining, (int) (readAllocationNode.endPosition - absolutePosition));
      Allocation allocation = readAllocationNode.allocation;
      target.put(allocation.data, readAllocationNode.translateOffset(absolutePosition), toCopy);
      remaining -= toCopy;
      absolutePosition += toCopy;
      if (absolutePosition == readAllocationNode.endPosition) {
        readAllocationNode = readAllocationNode.next;
      }
    }
  }

首先计算起始位置,如果读取位置absolutePosition比当前的readAllocationNode位置大,readAllocationNode就走到下个位置,这部分逻辑在advanceReadTo,然后读取数据到target,target就是MediaCodec的InputBuffer。

最后说明下,SampleQueue其实有两个,一个视频,一个音频,在ProgressiveMediaPeriod里创建:

 private TrackOutput prepareTrackOutput(TrackId id) {
 SampleQueue trackOutput =
        new SampleQueue(
            allocator,
            /* playbackLooper= */ handler.getLooper(),
            drmSessionManager,
            drmEventDispatcher);
    ...............
    sampleQueues[trackCount] = trackOutput;
    this.sampleQueues = Util.castNonNullTypeArray(sampleQueues);
    return trackOutput;
}

因为有音视频两个track,prepareTrackOutput这个方法会被调用两次。这样就分别构建了对应音视频的两个SampleQueue。

你可能感兴趣的:(ExoPlayer之SampleQueue)