ThrottledSource.cpp revision af5dd7753e62353411cf0daf3b513c38818e9662
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
22namespace android {
23
24ThrottledSource::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
34status_t ThrottledSource::initCheck() const {
35    return mSource->initCheck();
36}
37
38ssize_t ThrottledSource::readAt(off64_t offset, void *data, size_t size) {
39    Mutex::Autolock autoLock(mLock);
40
41    ssize_t n = mSource->readAt(offset, data, size);
42
43    if (n <= 0) {
44        return n;
45    }
46
47    mTotalTransferred += n;
48
49    int64_t nowUs = ALooper::GetNowUs();
50
51    if (mStartTimeUs < 0) {
52        mStartTimeUs = nowUs;
53    }
54
55    // How long would it have taken to transfer everything we ever
56    // transferred given the limited bandwidth.
57    int64_t durationUs =
58        mTotalTransferred * 1000000ll / mBandwidthLimitBytesPerSecond;
59
60    int64_t whenUs = mStartTimeUs + durationUs;
61
62    if (whenUs > nowUs) {
63        usleep(whenUs - nowUs);
64    }
65
66    return n;
67}
68
69status_t ThrottledSource::getSize(off64_t *size) {
70    return mSource->getSize(size);
71}
72
73uint32_t ThrottledSource::flags() {
74    return mSource->flags();
75}
76
77}  // namespace android
78
79