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 
19 #include <media/stagefright/foundation/ADebug.h>
20 #include <media/stagefright/foundation/ALooper.h>
21 
22 namespace android {
23 
ThrottledSource(const sp<DataSource> & source,int32_t bandwidthLimitBytesPerSecond)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 
readAt(off64_t offset,void * data,size_t size)34 ssize_t ThrottledSource::readAt(off64_t offset, void *data, size_t size) {
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 
45     int64_t nowUs = ALooper::GetNowUs();
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     }
61     return n;
62 }
63 
64 
65 }  // namespace android
66 
67