依据下载sampleBytesTransferred开方数作为weight参数调用addSample,意味着下载码率越高weight越大
public synchronized void onTransferEnd(DataSource source, DataSpec dataSpec, boolean isNetwork) {
if (!isNetwork) {
return;
}
Assertions.checkState(streamCount > 0);
long nowMs = clock.elapsedRealtime();
int sampleElapsedTimeMs = (int) (nowMs - sampleStartTimeMs);
totalElapsedTimeMs += sampleElapsedTimeMs;
totalBytesTransferred += sampleBytesTransferred;
if (sampleElapsedTimeMs > 0) {
float bitsPerSecond = (sampleBytesTransferred * 8000) / sampleElapsedTimeMs;
slidingPercentile.addSample((int) Math.sqrt(sampleBytesTransferred), bitsPerSecond);
if (totalElapsedTimeMs >= ELAPSED_MILLIS_FOR_ESTIMATE
|| totalBytesTransferred >= BYTES_TRANSFERRED_FOR_ESTIMATE) {
bitrateEstimate = (long) slidingPercentile.getPercentile(0.5f);
}
}
notifyBandwidthSample(sampleElapsedTimeMs, sampleBytesTransferred, bitrateEstimate);
if (--streamCount > 0) {
sampleStartTimeMs = nowMs;
}
sampleBytesTransferred = 0;
}
按照INDEX插入weight,value,超出weight部分删除最旧index对应的sample
/**
* Adds a new weighted value.
*
* @param weight The weight of the new observation.
* @param value The value of the new observation.
*/
public void addSample(int weight, float value) {
ensureSortedByIndex();
Sample newSample = recycledSampleCount > 0 ? recycledSamples[--recycledSampleCount]
: new Sample();
newSample.index = nextSampleIndex++;
newSample.weight = weight;
newSample.value = value;
samples.add(newSample);
totalWeight += weight;
for (int i = 0; i < samples.size(); i++) {
Sample currentSample = samples.get(i);
}
while (totalWeight > maxWeight) {
int excessWeight = totalWeight - maxWeight;
Sample oldestSample = samples.get(0);
if (oldestSample.weight <= excessWeight) {
totalWeight -= oldestSample.weight;
samples.remove(0);
if (recycledSampleCount < MAX_RECYCLED_SAMPLES) {
recycledSamples[recycledSampleCount++] = oldestSample;
}
} else {
oldestSample.weight -= excessWeight;
totalWeight -= excessWeight;
}
}
}
获取当前value时,依据value排序:
如果weight较小,窗口中累加weight次数较多,依据下载速度排序后会选择value相对较大的sample
如果weight较大,累加weight次数较少,但在切片均匀的情况下通常weight也跟网速成正比(网速快才会下载更高码率,sample size也会更大),此时选择value可能直接就拿第一个sample了
/**
* Computes a percentile by integration.
*
* @param percentile The desired percentile, expressed as a fraction in the range (0,1].
* @return The requested percentile value or {@link Float#NaN} if no samples have been added.
*/
public float getPercentile(float percentile) {
ensureSortedByValue();
float desiredWeight = percentile * totalWeight;
int accumulatedWeight = 0;
for (int i = 0; i < samples.size(); i++) {
Sample currentSample = samples.get(i);
accumulatedWeight += currentSample.weight;
if (accumulatedWeight >= desiredWeight) {
return currentSample.value;
}
}
// Clamp to maximum value or NaN if no values.
return samples.isEmpty() ? Float.NaN : samples.get(samples.size() - 1).value;
}
sample.png
网友评论