1 /*
2  * Copyright (C) 2015 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 //#define LOG_NDEBUG 0
18 #define LOG_TAG "FrameDropper"
19 #include <utils/Log.h>
20 
21 #include "FrameDropper.h"
22 
23 #include <media/stagefright/foundation/ADebug.h>
24 
25 namespace android {
26 
27 static const int64_t kMaxJitterUs = 2000;
28 
FrameDropper()29 FrameDropper::FrameDropper()
30     : mDesiredMinTimeUs(-1),
31       mMinIntervalUs(0) {
32 }
33 
~FrameDropper()34 FrameDropper::~FrameDropper() {
35 }
36 
setMaxFrameRate(float maxFrameRate)37 status_t FrameDropper::setMaxFrameRate(float maxFrameRate) {
38     if (maxFrameRate <= 0) {
39         ALOGE("framerate should be positive but got %f.", maxFrameRate);
40         return BAD_VALUE;
41     }
42     mMinIntervalUs = (int64_t) (1000000.0f / maxFrameRate);
43     return OK;
44 }
45 
shouldDrop(int64_t timeUs)46 bool FrameDropper::shouldDrop(int64_t timeUs) {
47     if (mMinIntervalUs <= 0) {
48         return false;
49     }
50 
51     if (mDesiredMinTimeUs < 0) {
52         mDesiredMinTimeUs = timeUs + mMinIntervalUs;
53         ALOGV("first frame %lld, next desired frame %lld",
54                 (long long)timeUs, (long long)mDesiredMinTimeUs);
55         return false;
56     }
57 
58     if (timeUs < (mDesiredMinTimeUs - kMaxJitterUs)) {
59         ALOGV("drop frame %lld, desired frame %lld, diff %lld",
60                 (long long)timeUs, (long long)mDesiredMinTimeUs,
61                 (long long)(mDesiredMinTimeUs - timeUs));
62         return true;
63     }
64 
65     int64_t n = (timeUs - mDesiredMinTimeUs + kMaxJitterUs) / mMinIntervalUs;
66     mDesiredMinTimeUs += (n + 1) * mMinIntervalUs;
67     ALOGV("keep frame %lld, next desired frame %lld, diff %lld",
68             (long long)timeUs, (long long)mDesiredMinTimeUs,
69             (long long)(mDesiredMinTimeUs - timeUs));
70     return false;
71 }
72 
73 }  // namespace android
74