/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.exoplayer2.upstream.cache;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.upstream.DataSink;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.cache.Cache.CacheException;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Writes data into a cache.
 */
public final class CacheDataSink implements DataSink {

  private final Cache cache;
  private final long maxCacheFileSize;
  private final int bufferSize;

  private DataSpec dataSpec;
  private File file;
  private OutputStream outputStream;
  private FileOutputStream underlyingFileOutputStream;
  private long outputStreamBytesWritten;
  private long dataSpecBytesWritten;

  /**
   * Thrown when IOException is encountered when writing data into sink.
   */
  public static class CacheDataSinkException extends CacheException {

    public CacheDataSinkException(IOException cause) {
      super(cause);
    }

  }

  /**
   * @param cache The cache into which data should be written.
   * @param maxCacheFileSize The maximum size of a cache file, in bytes. If the sink is opened for
   *    a {@link DataSpec} whose size exceeds this value, then the data will be fragmented into
   *    multiple cache files.
   */
  public CacheDataSink(Cache cache, long maxCacheFileSize) {
    this(cache, maxCacheFileSize, 0);
  }

  /**
   * @param cache The cache into which data should be written.
   * @param maxCacheFileSize The maximum size of a cache file, in bytes. If the sink is opened for
   *    a {@link DataSpec} whose size exceeds this value, then the data will be fragmented into
   *    multiple cache files.
   * @param bufferSize The buffer size in bytes for writing to a cache file. A zero or negative
   *    value disables buffering.
   */
  public CacheDataSink(Cache cache, long maxCacheFileSize, int bufferSize) {
    this.cache = Assertions.checkNotNull(cache);
    this.maxCacheFileSize = maxCacheFileSize;
    this.bufferSize = bufferSize;
  }

  @Override
  public void open(DataSpec dataSpec) throws CacheDataSinkException {
    this.dataSpec = dataSpec;
    if (dataSpec.length == C.LENGTH_UNSET) {
      return;
    }
    dataSpecBytesWritten = 0;
    try {
      openNextOutputStream();
    } catch (IOException e) {
      throw new CacheDataSinkException(e);
    }
  }

  @Override
  public void write(byte[] buffer, int offset, int length) throws CacheDataSinkException {
    if (dataSpec.length == C.LENGTH_UNSET) {
      return;
    }
    try {
      int bytesWritten = 0;
      while (bytesWritten < length) {
        if (outputStreamBytesWritten == maxCacheFileSize) {
          closeCurrentOutputStream();
          openNextOutputStream();
        }
        int bytesToWrite = (int) Math.min(length - bytesWritten,
            maxCacheFileSize - outputStreamBytesWritten);
        outputStream.write(buffer, offset + bytesWritten, bytesToWrite);
        bytesWritten += bytesToWrite;
        outputStreamBytesWritten += bytesToWrite;
        dataSpecBytesWritten += bytesToWrite;
      }
    } catch (IOException e) {
      throw new CacheDataSinkException(e);
    }
  }

  @Override
  public void close() throws CacheDataSinkException {
    if (dataSpec == null || dataSpec.length == C.LENGTH_UNSET) {
      return;
    }
    try {
      closeCurrentOutputStream();
    } catch (IOException e) {
      throw new CacheDataSinkException(e);
    }
  }

  private void openNextOutputStream() throws IOException {
    file = cache.startFile(dataSpec.key, dataSpec.absoluteStreamPosition + dataSpecBytesWritten,
        Math.min(dataSpec.length - dataSpecBytesWritten, maxCacheFileSize));
    underlyingFileOutputStream = new FileOutputStream(file);
    outputStream = bufferSize > 0
        ? new BufferedOutputStream(underlyingFileOutputStream, bufferSize)
        : underlyingFileOutputStream;
    outputStreamBytesWritten = 0;
  }

  @SuppressWarnings("ThrowFromFinallyBlock")
  private void closeCurrentOutputStream() throws IOException {
    if (outputStream == null) {
      return;
    }

    boolean success = false;
    try {
      outputStream.flush();
      underlyingFileOutputStream.getFD().sync();
      success = true;
    } finally {
      Util.closeQuietly(outputStream);
      outputStream = null;
      File fileToCommit = file;
      file = null;
      if (success) {
        cache.commitFile(fileToCommit);
      } else {
        fileToCommit.delete();
      }
    }
  }

}

@@ -994,49 +994,84 @@
 til.
-Util;%0Aimport java.io.BufferedOutputStream
+ReusableBufferedOutputStream;%0Aimport com.google.android.exoplayer2.util.Util
 ;%0Aim
@@ -1593,16 +1593,77 @@
 Written;
+%0A  private ReusableBufferedOutputStream bufferedOutputStream;
 %0A%0A  /**%0A
@@ -4664,53 +4664,213 @@
     
-outputStream = bufferSize %3E 0%0A        ? new B
+if (bufferSize %3E 0) %7B%0A      if (bufferedOutputStream == null) %7B%0A        bufferedOutputStream = new ReusableBufferedOutputStream(underlyingFileOutputStream,%0A            bufferSize);%0A      %7D else %7B%0A        b
 uffe
@@ -4876,32 +4876,38 @@
 eredOutputStream
+.reset
 (underlyingFileO
@@ -4921,31 +4921,95 @@
 ream
-, bufferSize)%0A        :
+);%0A      %7D%0A      outputStream = bufferedOutputStream;%0A    %7D else %7B%0A      outputStream =
  und
@@ -5029,24 +5029,30 @@
 tputStream;%0A
+    %7D%0A
     outputSt

Make CacheDataSink use ReusableBufferedOutputStream