void
EncodedBufferCache::AppendBuffer(nsTArray<uint8_t> & aBuf)
{
  MutexAutoLock lock(mMutex);
  mDataSize += aBuf.Length();

  mEncodedBuffers.AppendElement()->SwapElements(aBuf);

  if (!mTempFileEnabled && mDataSize > mMaxMemoryStorage) {
    nsresult rv = NS_OpenAnonymousTemporaryFile(&mFD);
    if (!NS_FAILED(rv)) {
      mTempFileEnabled = true;
    }
  }

  if (mTempFileEnabled) {
    // has created temporary file, write buffer in it
    for (uint32_t i = 0; i < mEncodedBuffers.Length(); i++) {
      int64_t amount = PR_Write(mFD, mEncodedBuffers.ElementAt(i).Elements(), mEncodedBuffers.ElementAt(i).Length());
      if (amount <  mEncodedBuffers.ElementAt(i).Length()) {
        NS_WARNING("Failed to write media cache block!");
      }
    }
    mEncodedBuffers.Clear();
  }

}
void
EncodedBufferCache::AppendBuffer(nsTArray<uint8_t> & aBuf)
{
  MutexAutoLock lock(mMutex);
  mDataSize += aBuf.Length();

  mEncodedBuffers.AppendElement()->SwapElements(aBuf);

  if (!mTempFileEnabled && mDataSize > mMaxMemoryStorage) {
    nsresult rv;
    PRFileDesc* tempFD = nullptr;
    {
      // Release the mMutex because there is a sync dispatch to mainthread in
      // NS_OpenAnonymousTemporaryFile.
      MutexAutoUnlock unlock(mMutex);
      rv = NS_OpenAnonymousTemporaryFile(&tempFD);
    }
    if (!NS_FAILED(rv)) {
      // Check the mDataSize again since we release the mMutex before.
      if (mDataSize > mMaxMemoryStorage) {
        mFD = tempFD;
        mTempFileEnabled = true;
      } else {
        // Close the tempFD because the data had been taken during the
        // MutexAutoUnlock.
        PR_Close(tempFD);
      }
    }
  }

  if (mTempFileEnabled) {
    // has created temporary file, write buffer in it
    for (uint32_t i = 0; i < mEncodedBuffers.Length(); i++) {
      int32_t amount = PR_Write(mFD, mEncodedBuffers.ElementAt(i).Elements(), mEncodedBuffers.ElementAt(i).Length());
      if (amount < 0 || size_t(amount) < mEncodedBuffers.ElementAt(i).Length()) {
        NS_WARNING("Failed to write media cache block!");
      }
    }
    mEncodedBuffers.Clear();
  }

}