michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* vim:set ts=2 sw=2 sts=2 et cindent: */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #include "EncodedBufferCache.h" michael@0: #include "nsAnonymousTemporaryFile.h" michael@0: #include "nsDOMFile.h" michael@0: #include "prio.h" michael@0: michael@0: namespace mozilla { michael@0: michael@0: void michael@0: EncodedBufferCache::AppendBuffer(nsTArray & aBuf) michael@0: { michael@0: MutexAutoLock lock(mMutex); michael@0: mDataSize += aBuf.Length(); michael@0: michael@0: mEncodedBuffers.AppendElement()->SwapElements(aBuf); michael@0: michael@0: if (!mTempFileEnabled && mDataSize > mMaxMemoryStorage) { michael@0: nsresult rv = NS_OpenAnonymousTemporaryFile(&mFD); michael@0: if (!NS_FAILED(rv)) { michael@0: mTempFileEnabled = true; michael@0: } michael@0: } michael@0: michael@0: if (mTempFileEnabled) { michael@0: // has created temporary file, write buffer in it michael@0: for (uint32_t i = 0; i < mEncodedBuffers.Length(); i++) { michael@0: int64_t amount = PR_Write(mFD, mEncodedBuffers.ElementAt(i).Elements(), mEncodedBuffers.ElementAt(i).Length()); michael@0: if (amount < mEncodedBuffers.ElementAt(i).Length()) { michael@0: NS_WARNING("Failed to write media cache block!"); michael@0: } michael@0: } michael@0: mEncodedBuffers.Clear(); michael@0: } michael@0: michael@0: } michael@0: michael@0: already_AddRefed michael@0: EncodedBufferCache::ExtractBlob(const nsAString &aContentType) michael@0: { michael@0: MutexAutoLock lock(mMutex); michael@0: nsCOMPtr blob; michael@0: if (mTempFileEnabled) { michael@0: // generate new temporary file to write michael@0: blob = new nsDOMTemporaryFileBlob(mFD, 0, mDataSize, aContentType); michael@0: // fallback to memory blob michael@0: mTempFileEnabled = false; michael@0: mDataSize = 0; michael@0: mFD = nullptr; michael@0: } else { michael@0: void* blobData = moz_malloc(mDataSize); michael@0: NS_ASSERTION(blobData, "out of memory!!"); michael@0: michael@0: if (blobData) { michael@0: for (uint32_t i = 0, offset = 0; i < mEncodedBuffers.Length(); i++) { michael@0: memcpy((uint8_t*)blobData + offset, mEncodedBuffers.ElementAt(i).Elements(), michael@0: mEncodedBuffers.ElementAt(i).Length()); michael@0: offset += mEncodedBuffers.ElementAt(i).Length(); michael@0: } michael@0: blob = new nsDOMMemoryFile(blobData, mDataSize, michael@0: aContentType); michael@0: mEncodedBuffers.Clear(); michael@0: } else michael@0: return nullptr; michael@0: } michael@0: mDataSize = 0; michael@0: return blob.forget(); michael@0: } michael@0: michael@0: } //end namespace