FileSource.cpp revision 03475f5af25e4aa32d46d41dd2ec756853d8dd9d
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <media/stagefright/FileSource.h> 18#include <media/stagefright/MediaDebug.h> 19 20namespace android { 21 22FileSource::FileSource(const char *filename) 23 : mFile(fopen(filename, "rb")), 24 mOffset(0), 25 mLength(-1) { 26} 27 28FileSource::FileSource(int fd, int64_t offset, int64_t length) 29 : mFile(fdopen(fd, "rb")), 30 mOffset(offset), 31 mLength(length) { 32 CHECK(offset >= 0); 33 CHECK(length >= 0); 34} 35 36FileSource::~FileSource() { 37 if (mFile != NULL) { 38 fclose(mFile); 39 mFile = NULL; 40 } 41} 42 43status_t FileSource::initCheck() const { 44 return mFile != NULL ? OK : NO_INIT; 45} 46 47ssize_t FileSource::readAt(off_t offset, void *data, size_t size) { 48 Mutex::Autolock autoLock(mLock); 49 50 if (mLength >= 0) { 51 if (offset >= mLength) { 52 return 0; // read beyond EOF. 53 } 54 int64_t numAvailable = mLength - offset; 55 if ((int64_t)size > numAvailable) { 56 size = numAvailable; 57 } 58 } 59 60 int err = fseeko(mFile, offset + mOffset, SEEK_SET); 61 CHECK(err != -1); 62 63 return fread(data, 1, size, mFile); 64} 65 66status_t FileSource::getSize(off_t *size) { 67 if (mLength >= 0) { 68 *size = mLength; 69 70 return OK; 71 } 72 73 fseek(mFile, SEEK_END, 0); 74 *size = ftello(mFile); 75 76 return OK; 77} 78 79} // namespace android 80