Video Quality Test
VideoQualityTest measures playback quality on web-based streaming platforms such as YouTube or Netflix. See VideoTestActivity in the demo app for an example.
Do not instantiate the builder before the registration is complete, as you will receive an exception. Make sure your application is checking the registration before starting the test.
Note that this is slightly different from the ExoPlayerQualityTest, and uses a different builder class/result listener class.
Here is a breakdown of the essential parts of the test. Note that in contrast to the ExoPlayer quality test, the VideoQualityTest requires a FrameLayout to be attached to the test, to display the video.
Starting the Test
This is how you would start the test:
// attach the FrameLayout to the test --> see the demo app, `activity_video.xml` layout for more info
FrameLayout videoFrame = findViewById(R.id.videoFrame);
VideoQualityTest.Builder builder = new VideoQualityTest.Builder(
this,
"netflix_trailer", // the subject identifier, e.g. "youtube", "netflix_trailer", "facebook", "instagram", "tiktok", "hotstar", or "snapchat"
Uri.parse("https://www.netflix.com/tudum/videos/your-trailer-url"),
30 * 1000 // 30 seconds playback duration
)
.setMaxTestDuration(60 * 1000) // 60 seconds timeout
.setVideoQualityTestResultListener(this)
.attachToView(videoFrame); // attach to a FrameLayout in your layout
try {
mQTest = builder.build();
mQTest.start();
} catch (Exception e) {
Log.e(TAG, "Test start failed", e);
// Handle exception
}
Which URLs/subjects are supported? Please check the below:
- Netflix Trailer
- YouTube
- Snapchat
For Netflix content, currently only trailer URLs from Netflix's Tudum site are supported:
new VideoQualityTest.Builder(
this,
"netflix_trailer",
Uri.parse("https://www.netflix.com/tudum/videos/your-trailer-url"),
30 * 1000
)
For YouTube content, you can use any YouTube video URL from the main YouTube site:
new VideoQualityTest.Builder(
this,
"youtube",
Uri.parse("https://www.youtube.com/watch?v=your-video-id"),
30 * 1000
);
However, this may play back the video in a smaller resolution, hence we recommend using embed URLs instead:
new VideoQualityTest.Builder(
this,
"youtube",
Uri.parse("https://www.youtube.com/embed/your-video-id"),
30 * 1000
);
Any Facebook post with a video should work, but we recommend using the m.facebook.com domain:
new VideoQualityTest.Builder(
this,
"facebook",
Uri.parse("https://m.facebook.com/your-post-url"),
30 * 1000
);
On its mobile site, Facebook plays one file per video, picked when the page loads, and never changes it however good or bad the network is. Which file that is depends on the video: a popular one may be served at 720p, while an older upload can be as small as 400x225 at around 150 kbps, in which case the quality score sits near the bottom of the scale and says little about the network. To choose the resolution yourself, see Forcing or Capping the Playback Resolution below.
For Snapchat, use a direct link to a Spotlight video, in the form https://www.snapchat.com/@<author>/spotlight/<video-id>:
new VideoQualityTest.Builder(
this,
"snapchat",
Uri.parse("https://www.snapchat.com/@<author>/spotlight/<video-id>"),
30 * 1000
);
Calculation Settings
VideoQualityTest.Builder.setCalculationSettings(...) uses the same calculation options and defaults as ExoPlayerQualityTest. See Calculation Settings for the supported keys, model names, and an example.
Overriding the User Agent
By default, the test uses the WebView's built-in user agent. If you need the streaming platform to be served a specific user agent (for example, to emulate a particular browser or device), you can override it via the builder:
.setUserAgent("Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36")
If you do not call setUserAgent, or pass null, the WebView's default user agent is kept — with one exception: the Facebook subject switches to a desktop user agent on its own whenever you ask it for a resolution, because Facebook only lets a resolution be chosen on its desktop site. See Forcing or Capping the Playback Resolution below. Setting your own user agent always takes precedence over that.
Cookies and Cache
By default, the test removes all cookies and clears the WebView's cache and history before it starts. Every test then begins from the same clean state, and the measurement is not influenced by a page that was already cached. If you want to keep them, turn this off via the builder:
.setClearBrowsingData(false)
Keeping the browsing data is useful if the platform under test needs a logged-in session, or if your app uses cookies of its own that must survive the test — cookies are shared by all WebViews of an app, and clearing them removes those as well.
Muting Playback
Playback starts muted by default to prevent automated measurements from playing audio unexpectedly. To start with audio, turn this off via the builder:
.setMuted(false)
You can also call setMuted(boolean) on the running test, and isMuted() returns the current state.
The test remembers the previous media volume and restores it when you unmute the test or when the test ends.
Tests started through the background or foreground service are always muted.
Measuring Higher Resolutions (e.g. 4K)
So far, measuring higher resolutions has only been confirmed to work for YouTube. Other services may behave differently and are not yet verified.
By default, the video is loaded into a WebView that is sized at 1920x1080 pixels. Adaptive streaming services such as YouTube never serve a resolution higher than the player surface can display. This size therefore limits the resolution you can measure to 1080p. If you want to measure higher resolutions, such as 4K (2160p), you need to override two things.
First, enlarge the WebView so the player has a big enough surface to render into:
.setWebViewDimensions(3840, 2160)
Second, set the reported display size to the same value as the WebView:
.setReportedDisplaySize(3840, 2160)
For a 4K test, set both to the same size (3840x2160).
new VideoQualityTest.Builder(
this,
"youtube",
Uri.parse("https://www.youtube.com/embed/aqz-KE-bpKQ"),
30 * 1000
)
.setWebViewDimensions(3840, 2160)
.setReportedDisplaySize(3840, 2160)
.setVideoQualityTestResultListener(this)
.attachToView(videoFrame);
/embed URL for YouTube 4KTo actually receive a 4K stream from YouTube, you must use an embed URL (for example, https://www.youtube.com/embed/aqz-KE-bpKQ). A regular watch URL may not play back in 4K even with a large WebView.
The device must be able to decode the target resolution. Large surfaces must also fit within the GPU's maximum texture size.
Forcing or Capping the Playback Resolution
This option is currently implemented for the YouTube and Facebook subjects. Other subjects ignore it. Facebook works differently from YouTube — see Facebook below.
By default, YouTube's own adaptive streaming logic picks the playback resolution based on the player surface size (see Measuring Higher Resolutions above) and the available network bandwidth. If you want to control the streamed resolution directly instead, use setForceResolution on the builder.
Pin the resolution to an exact value:
.setForceResolution(2160) // stream exactly 2160p (4K), do not adapt down
Use a fixed resolution to test whether the network can sustain that quality. Playback stalls if the available bandwidth is too low.
Or cap the resolution to a range, still allowing the player to adapt down under congestion:
.setForceResolution(720, 1080) // stream up to 1080p, but allow dropping to 720p if needed
This raises the ceiling to the given maximum while still letting the player adapt down to the minimum under congestion, which measures the realistic quality of experience for a viewer on a screen capable of the maximum resolution.
Allowed values for both the pinned resolution and the range bounds are 144, 240, 360, 480, 720, 1080, 1440, and 2160, matching YouTube's own quality levels. For a range, the minimum must not be greater than the maximum.
Note that the WebView surface size still bounds what can actually be decoded. 1080p works reliably on the default setWebViewDimensions surface (1920x1080). For 2160p you also need setWebViewDimensions(3840, 2160), a matching setReportedDisplaySize(3840, 2160) so P.1203 does not underreport the display size, and a device with a 4K-capable decoder:
new VideoQualityTest.Builder(
this,
"youtube",
Uri.parse("https://www.youtube.com/embed/aqz-KE-bpKQ"),
30 * 1000
)
.setWebViewDimensions(3840, 2160)
.setReportedDisplaySize(3840, 2160)
.setForceResolution(2160)
.setVideoQualityTestResultListener(this)
.attachToView(videoFrame);
Forcing the Resolution on Facebook
Facebook does not let you choose a resolution on its mobile site: it sends a single progressive file per video, chosen once when the page loads, and renders no player controls at all. On its desktop site most videos stream adaptively, with a quality ladder that typically runs 360p, 540p, 720p and 1080p, while some, mostly older uploads, again have only two files to choose from.
Use setForceResolution to set an upper limit on the video height. The test plays the highest rendition at or below it, or the lowest available rendition if all exceed it.
new VideoQualityTest.Builder(
this,
"facebook",
Uri.parse("https://m.facebook.com/your-post-url"),
30 * 1000
)
.setForceResolution(720) // play the highest rendition up to 720p
.setVideoQualityTestResultListener(this)
.attachToView(videoFrame);
Some caveats:
- Facebook only lets a resolution be chosen on its desktop site. The SDK then sends a desktop user agent for that request, and the measurement then covers a different page from the one a phone user would see
- Not every video is streamed adaptively, and for one that is not, a network too slow for the chosen file makes playback stall rather than drop to a smaller one
- A
[min, max]range is judged by its maximum, because Facebook's player takes a single quality and not a range
Receiving Test Results
To receive the outcomes of the test, your activity or class must implement the VideoQualityTestResultListener interface. This interface includes methods for handling successful results, errors, and state changes.
Test Success
When the test completes successfully, the onTestResult method is called:
@Override
public void onTestResult(@NonNull Map<String, Object> result) {
Log.i(TAG, "Test result received: " + result);
// Convert the result to a JSON string for display or storage
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String resultJson = gson.toJson(result);
// Process or display the resultJson
}
For more information on the values, see the measurement data.
Test Errors
If an error occurs during the test, the onTestError method is invoked:
@Override
public void onTestError(@NonNull QualityTestException error) {
// Handle the error, e.g., display a message to the user
Log.e(TAG, "Test error: " + error.getMessage(), error);
}
If you get an error like:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
it means that the test is not able to connect to the server. Please verify that you are using a recent SDK/Android system version, since old versions may not bundle the root certificates used by modern websites.
Test State Changes
You can monitor the lifecycle of the test by implementing the onTestStateChanged method from the VideoQualityTestResultListener interface:
@Override
public void onTestStateChanged(QualityTestState state) {
Log.d(TAG, "Test state: " + state);
}
Getting Periodic Statistics
You can also receive periodic statistics updates by implementing the VideoStatisticsListener interface in your class, then setting it in the builder:
.setVideoStatisticsListener(this)
This will trigger the onStatisticsUpdate method in your class, which you can use to update your UI or store the statistics in a database:
@Override
void onStatisticsUpdate(Map<String, Object> statistics) {
// handle the statistics
runOnUiThread(() -> {
// update the UI if needed
String statsJson = new GsonBuilder().setPrettyPrinting().create().toJson(statistics);
statisticsTextView.setText(statsJson);
});
}
The values might look like this:
{
"averageAudioBitrate": 126.92089792420876,
"averageStallingTime": 0.0,
"averageTotalBitrate": 2068.632738783725,
"averageVideoBitrate": 1941.711840859516,
"averageVideoFramerate": 60.05286424104944,
"contentServerHostname": "",
"contentServerIpAddress": "",
"initialLoadingDelay": 1.549,
"initialResolution": 1080.0,
"largestPlayedVideoSize": 1080.0,
"longestPlayedChunk": 1080.0,
"mostUsedAudioCodec": "aaclc",
"mostUsedVideoCodec": "h264",
"numberOfQualitySwitches": 0.0,
"numberOfStallingEvents": 0.0,
"p1203AverageAudioQuality": 4.553492832693684,
"p1203AverageVideoQuality": 4.2279949249820765,
"p1203MaxMosRatio": 0.8531772087203596,
"p1203MaxTheoreticalMos": 4.77197412302386,
"p1203OverallAudiovisualQuality": 5.0,
"p1203OverallMos": 4.071339562367283,
"p1203StallingQuality": 4.171710787150921,
"qualitySwitchDownCount": 0.0,
"qualitySwitchUpCount": 0.0,
"stallingRatio": 0.0,
"totalPlayTime": 10.316056,
"totalStallingTime": 0.0,
"videoCompletionRatio": 0.016255971862634947
}
Please refer to our statistic values reference for more information on the values.
Furthermore, if you implement the method onStatisticsInputUpdate, you will receive the enriched computational input used for statistics calculation, which includes more diagnostic data.
@Override
void onStatisticsInputUpdate(Map<String, Object> enrichedInput) {
// handle the enriched input
runOnUiThread(() -> {
// update the UI if needed
String inputJson = new GsonBuilder().setPrettyPrinting().create().toJson(enrichedInput);
enrichedStatisticsInputTextView.setText(inputJson);
});
}
The enriched input might look like this:
{
// video attribute metadata
"videoAttributes": {
"contentType": "trailer",
"isReferenceVideo": false,
"service": "netflix",
"streamId": "next-in-fashion-season-2-teaser",
"duration": 42.250541
},
// these will be normally empty
"audioBufferTrace": [],
"videoBufferTrace": [],
"latencyTrace": [],
"bufferTrace": [],
// current number of dropped video frames
"droppedVideoFrames": 2.0,
"audioSegments": [
{
"start": 0.0,
"duration": 1.267794,
"bitrate": 273.34682581782505,
"codec": "heaac"
}
// ... and so on
],
"videoSegments": [
{
"start": 0.0,
"duration": 1.267794,
"resolution": "683x384",
"bitrate": 2310.8907358032275,
"fps": 25.0,
"codec": "h264"
}
// ... and so on
],
// a list of stalling events, with start time and duration
"stallingEvents": [
[0.0, 4.768]
],
"rawVideoEvents": [], // empty
"p1203OutputReport": {
"O46Audiovisual": 4.760453954582164,
"O46Video": 2.4030881961524693,
"O21Average": 4.351519985511639,
"O22Average": 4.351079933116701,
"O46Maximum": 4.766421476705611,
"O23": 1.753737302869288,
"O34": [5.0, 5.0, 5.0],
"O35": 5.0,
"O46": 2.265873586932749,
"date": "2025-10-21T11:27:46.287Z",
"mode": 0.0,
"streamId": "",
"O21": [4.351519985511639, 4.351519985511639, 4.351519985511639],
"O22": [4.39593231192713, 4.328653743711486, 4.328653743711486]
}
}
Video State and Progress Callbacks
The VideoQualityTestResultListener interface also provides methods to track video state changes, duration, and playback progress:
@Override
public void onVideoStateChanged(String videoState, Double clientTime, Double mediaTime) {
// videoState can be: 'unstarted', 'stalling', 'playing', 'seeking', 'ended', 'paused'
Log.i(TAG, "Video state changed: " + videoState +
", clientTime=" + clientTime +
", mediaTime=" + mediaTime);
}
@Override
public void onVideoDuration(Double duration) {
// Called when the video duration is known (in seconds)
Log.i(TAG, "Video duration: " + duration);
}
@Override
public void onPlaybackProgress(int progress) {
// progress is an integer between 0-100 representing playback percentage
Log.i(TAG, "Playback progress: " + progress + "%");
// update a progress bar or other UI element
progressBar.setProgress(progress);
}
These callbacks make it easier to track the video playback state and update your UI accordingly.
Instrumented Usage
You can start a VideoQualityTest with adb by passing intent extras to the demo VideoTestActivity. This helps with automated testing.
adb shell am start -n "com.aveq.qualitytestlibdemo/.VideoTestActivity" \
--ez autoRunTest true \
--es url "https://www.netflix.com/tudum/videos/your-trailer-url" \
--es subject "netflix_trailer" \
--el maxPlaybackDuration 30000
The following intent extras are supported:
autoRunTest(boolean) – start the test automatically on activity launchurl(string) – URL of the video to testsubject(string) – service to test, such asyoutubeornetflix_trailermaxPlaybackDuration(long) – max playback duration in mstimeout(long) – test timeout in mspvModel(string) – Pv model namepqModel(string) – Pq model nameforceResolution(string) – resolution to force, as a height (1080) or a range (360,1080), for YouTube and FacebookuserAgent(string) –User-Agentheader for the testwebViewWidth,webViewHeight(int) – WebView size in pixelsreportDisplayWidth,reportDisplayHeight(int) – display size to report for the scoremetadata(string) – JSON metadata to attach to the measurement, such as{"key":"value"}loopTest(boolean) – repeat the test automatically until stopped, see Looping Tests below
To measure higher resolutions, you can pass the same overrides as integer extras:
adb shell am start -n "com.aveq.qualitytestlibdemo/.VideoTestActivity" \
--ez autoRunTest true \
--es url "https://www.youtube.com/embed/aqz-KE-bpKQ" \
--es subject "youtube" \
--el maxPlaybackDuration 30000 \
--ei webViewWidth 3840 --ei webViewHeight 2160 \
--ei reportDisplayWidth 3840 --ei reportDisplayHeight 2160
The ./run_video_quality_test.sh script runs this call and reads the results from the Android log.
Looping Tests
The demo VideoTestActivity can repeat an in-activity test automatically until you press Stop, using the "Loop test" checkbox in the settings screen (or the loopTest intent extra above). Looping works only for in-activity tests, because the activity must stay in the foreground. Turning it on turns off the Background Service and Foreground Service checkboxes, and the other way round.
While a loop is running, the app does not show the result screen after each test and keeps going unattended. Each test's result is still delivered as usual through VideoQualityTestResultListener#onTestResult. Press Stop at any time to end the loop after the current test finishes.
Background Execution
The SDK supports two service modes for automated or periodic tests:
- A background service that runs in the background while your app is visible on screen
- A foreground service that can run while your app is hidden
The demo app calls tests that run directly in the visible activity "in-activity tests."
We recommend you use the background service for most use cases, as it is less intrusive and does not require an extra permission. A foreground service displays a visible notification and causes an extra notification prompt, which is not desirable for some users. However, if you cannot guarantee your app to stay on-screen, then you must use the foreground service.
Background Service
To instantiate a background service based test, you need to use the QualityTestService class.
Bundle parameters = new Bundle();
parameters.putParcelable(QualityTestService.ParameterKeys.URL, Uri.parse("https://www.youtube.com/watch?v=aqz-KE-bpKQ"));
parameters.putString(QualityTestService.ParameterKeys.SUBJECT, "youtube");
parameters.putLong(QualityTestService.ParameterKeys.MAX_PLAYBACK_DURATION_MS, 30 * 1000);
parameters.putLong(QualityTestService.ParameterKeys.TIMEOUT_MS, 60 * 1000);
Intent intent = new Intent(this, QualityTestService.class);
intent.setAction(QualityTestService.ACTION_START_TEST);
intent.putExtra(QualityTestService.EXTRA_TEST_TYPE, QualityTestService.TEST_TYPE_VIDEO);
intent.putExtra(QualityTestService.EXTRA_TEST_PARAMETERS, parameters);
startService(intent);
This will start a background test that will run for 30 seconds and timeout after 60 seconds. The test will be delivered via broadcast intents to the TestResultReceiver class. Have a look at the setupTestResultReceiver method in the BaseTestActivity class in the demo app for more info on how to set it up and register it.
Our demo app further includes a scheduling feature using the WorkManager library. This is a good example of how to schedule periodic tests, but note that the minimum interval for periodic tests is 15 minutes because of a WorkManager limitation. See the schedulePeriodicBackgroundWork method in the VideoTestActivity class for more info.
Foreground Service
Before you can use the foreground service, your app needs to have the following permissions in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
You also need to request the permissions at runtime. Check out the getRequiredPermissionsList() function in the MainActivity.java file in the demo app.
To then instantiate a foreground service based test, you can also use the QualityTestService class, but you need to set the EXTRA_RUN_AS_FOREGROUND_SERVICE flag to true in the intent:
Bundle parameters = new Bundle();
parameters.putParcelable(QualityTestService.ParameterKeys.URL, Uri.parse("https://www.youtube.com/watch?v=aqz-KE-bpKQ"));
parameters.putString(QualityTestService.ParameterKeys.SUBJECT, "youtube");
parameters.putLong(QualityTestService.ParameterKeys.MAX_PLAYBACK_DURATION_MS, 30 * 1000);
parameters.putLong(QualityTestService.ParameterKeys.TIMEOUT_MS, 60 * 1000);
Intent intent = new Intent(this, QualityTestService.class);
intent.setAction(QualityTestService.ACTION_START_TEST);
intent.putExtra(QualityTestService.EXTRA_TEST_TYPE, QualityTestService.TEST_TYPE_VIDEO);
intent.putExtra(QualityTestService.EXTRA_TEST_PARAMETERS, parameters);
intent.putExtra(QualityTestService.EXTRA_RUN_AS_FOREGROUND_SERVICE, true);
startService(intent);
This will start a foreground service that will run for 30 seconds and timeout after 60 seconds. The test will be delivered via broadcast intents to the TestResultReceiver class. Have a look at the setupTestResultReceiver method in the BaseTestActivity class in the demo app for more info on how to set it up and register it.
Receiving Test Results via Broadcast
Of course, when a test is done, you want to receive the results.
When you start a test using QualityTestService (for either background or foreground service mode), the results are delivered via broadcast intents. To receive these, you need to implement and register a BroadcastReceiver.
The service will send intents with the following actions:
QualityTestService.ACTION_TEST_RESULT(com.aveq.qualitytestlib.action.TEST_RESULT): The test finished. The results are in aBundlein theQualityTestService.EXTRA_RESULT_DATAextra. This bundle holds a serializableMap<String, Object>under the key"map".QualityTestService.ACTION_TEST_ERROR(com.aveq.qualitytestlib.action.TEST_ERROR): The test failed. The error details are in aBundlein theQualityTestService.EXTRA_ERROR_DATAextra. This bundle holds a"message"(String) and a"code"(int).
The QualityTestService.EXTRA_TEST_TYPE extra holds the test type.
To see an example of how to implement the TestResultReceiver class, check out the BaseTestActivity class in the demo app.
The service sends these broadcasts only to your own app. You can receive them in two ways:
- Register a
BroadcastReceiverat runtime in the Activity or other component that needs the results. Unregister it when you no longer need it. - Declare a receiver in your
AndroidManifest.xmlwith an intent filter for the two actions. It also gets results when none of your activities is open. It does not need to be exported.
The demo app does both. Its manifest receiver saves each result. Results of background tests then show up in the Results tab, even when the test activity is closed.