Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2010 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 "include/ThrottledSource.h" |
| 18 | |
James Dong | f1d5aa1 | 2012-02-06 23:46:37 -0800 | [diff] [blame] | 19 | #include <media/stagefright/foundation/ADebug.h> |
Andreas Huber | fa0e033 | 2012-10-01 16:03:44 -0700 | [diff] [blame] | 20 | #include <media/stagefright/foundation/ALooper.h> |
Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 21 | |
| 22 | namespace android { |
| 23 | |
Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 24 | ThrottledSource::ThrottledSource( |
| 25 | const sp<DataSource> &source, |
| 26 | int32_t bandwidthLimitBytesPerSecond) |
| 27 | : mSource(source), |
| 28 | mBandwidthLimitBytesPerSecond(bandwidthLimitBytesPerSecond), |
| 29 | mStartTimeUs(-1), |
| 30 | mTotalTransferred(0) { |
| 31 | CHECK(mBandwidthLimitBytesPerSecond > 0); |
| 32 | } |
| 33 | |
James Dong | c7fc37a | 2010-11-16 14:04:54 -0800 | [diff] [blame] | 34 | ssize_t ThrottledSource::readAt(off64_t offset, void *data, size_t size) { |
Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 35 | Mutex::Autolock autoLock(mLock); |
| 36 | |
| 37 | ssize_t n = mSource->readAt(offset, data, size); |
| 38 | |
| 39 | if (n <= 0) { |
| 40 | return n; |
| 41 | } |
| 42 | |
| 43 | mTotalTransferred += n; |
| 44 | |
Andreas Huber | fa0e033 | 2012-10-01 16:03:44 -0700 | [diff] [blame] | 45 | int64_t nowUs = ALooper::GetNowUs(); |
Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 46 | |
| 47 | if (mStartTimeUs < 0) { |
| 48 | mStartTimeUs = nowUs; |
| 49 | } |
| 50 | |
| 51 | // How long would it have taken to transfer everything we ever |
| 52 | // transferred given the limited bandwidth. |
| 53 | int64_t durationUs = |
| 54 | mTotalTransferred * 1000000ll / mBandwidthLimitBytesPerSecond; |
| 55 | |
| 56 | int64_t whenUs = mStartTimeUs + durationUs; |
| 57 | |
| 58 | if (whenUs > nowUs) { |
| 59 | usleep(whenUs - nowUs); |
| 60 | } |
Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 61 | return n; |
| 62 | } |
| 63 | |
Andreas Huber | c282e3e | 2010-06-01 13:38:13 -0700 | [diff] [blame] | 64 | |
| 65 | } // namespace android |
| 66 | |