blob: 7496752809cf9546d03d31138d831df54f46ebff [file] [log] [blame]
Andreas Huberc282e3e2010-06-01 13:38:13 -07001/*
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 Dongf1d5aa12012-02-06 23:46:37 -080019#include <media/stagefright/foundation/ADebug.h>
Andreas Huberfa0e0332012-10-01 16:03:44 -070020#include <media/stagefright/foundation/ALooper.h>
Andreas Huberc282e3e2010-06-01 13:38:13 -070021
22namespace android {
23
Andreas Huberc282e3e2010-06-01 13:38:13 -070024ThrottledSource::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 Dongc7fc37a2010-11-16 14:04:54 -080034ssize_t ThrottledSource::readAt(off64_t offset, void *data, size_t size) {
Andreas Huberc282e3e2010-06-01 13:38:13 -070035 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 Huberfa0e0332012-10-01 16:03:44 -070045 int64_t nowUs = ALooper::GetNowUs();
Andreas Huberc282e3e2010-06-01 13:38:13 -070046
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 Huberc282e3e2010-06-01 13:38:13 -070061 return n;
62}
63
Andreas Huberc282e3e2010-06-01 13:38:13 -070064
65} // namespace android
66