bind method

  1. @override
Stream<Uint8List> bind(
  1. Stream<List<T>> stream
)
override

Binds this stream to transfrom an other stream. The runtime type of the input stream must be castable to either Stream<Float32List>, Stream<Int16List> or Stream<Uint8List> depending on what constructor was used or a TypeError will be thrown.

Implementation

@override
Stream<Uint8List> bind(Stream<List<T>> stream) async* {
  try {
    int dataIndex;
    Uint8List bytes;
    int available;
    int max;
    int use;
    Uint8List inputBuffer = _encoder.inputBuffer;
    Stream<Uint8List> mapped;
    if (_expect == Int16List) {
      mapped = stream.cast<Int16List>().map<Uint8List>((Int16List s16le) =>
          s16le.buffer.asUint8List(s16le.offsetInBytes, s16le.lengthInBytes));
    } else if (_expect == Float32List) {
      mapped = stream.cast<Float32List>().map<Uint8List>(
          (Float32List floats) => floats.buffer
              .asUint8List(floats.offsetInBytes, floats.lengthInBytes));
    } else {
      mapped = stream.cast<Uint8List>();
    }
    await for (Uint8List pcm in mapped) {
      bytes = pcm;
      dataIndex = 0;
      available = bytes.lengthInBytes;
      while (available > 0) {
        max = _encoder.maxInputBufferSizeBytes - _encoder.inputBufferIndex;
        use = max < available ? max : available;
        inputBuffer.setRange(_encoder.inputBufferIndex,
            _encoder.inputBufferIndex + use, bytes, dataIndex);
        dataIndex += use;
        _encoder.inputBufferIndex += use;
        available = bytes.lengthInBytes - dataIndex;
        if (_encoder.inputBufferIndex == _encoder.maxInputBufferSizeBytes) {
          Uint8List bytes =
              floats ? _encoder.encodeFloat() : _encoder.encode();
          yield copyOutput ? Uint8List.fromList(bytes) : bytes;
          _encoder.inputBufferIndex = 0;
        }
      }
    }
    if (_encoder.maxInputBufferSizeBytes != 0) {
      if (fillUpLastFrame) {
        _encoder.inputBuffer.setAll(
            _encoder.inputBufferIndex,
            Uint8List(_encoder.maxInputBufferSizeBytes -
                _encoder.inputBufferIndex));
        _encoder.inputBufferIndex = _encoder.maxInputBufferSizeBytes;
        Uint8List bytes = floats ? _encoder.encodeFloat() : _encoder.encode();
        yield copyOutput ? Uint8List.fromList(bytes) : bytes;
      } else {
        int missingSamples =
            (_encoder.maxInputBufferSizeBytes - _encoder.inputBufferIndex) ~/
                (floats ? 4 : 2);
        throw UnfinishedFrameException._(missingSamples: missingSamples);
      }
    }
  } finally {
    destroy();
  }
}