summaryrefslogtreecommitdiff
path: root/tests/tests/mediacujtest/common/src/android/media/cujcommon/cts/PlayerListener.java
blob: 2956a56228afd1dfb4e05e445a5d97b511d439f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.media.cujcommon.cts;

import static android.media.cujcommon.cts.CujTestBase.ORIENTATIONS;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Looper;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;
import androidx.media3.common.C;
import androidx.media3.common.Format;
import androidx.media3.common.Player;
import androidx.media3.common.Player.Events;
import androidx.media3.common.TrackSelectionOverride;
import androidx.media3.common.TrackSelectionParameters;
import androidx.media3.common.Tracks;

import java.util.ArrayList;
import java.util.List;

public abstract class PlayerListener implements Player.Listener {

  public static final long NOTIFICATIONTEST_PLAYBACK_DELTA_TIME_US = 6000;
  public static final Object LISTENER_LOCK = new Object();
  public static int CURRENT_MEDIA_INDEX = 0;

  // Enum Declared for Test Type
  public enum TestType {
    PLAYBACK_TEST,
    SEEK_TEST,
    ORIENTATION_TEST,
    ADAPTIVE_PLAYBACK_TEST,
    SCROLL_TEST,
    SWITCH_AUDIO_TRACK_TEST,
    SWITCH_SUBTITLE_TRACK_TEST,
    CALL_NOTIFICATION_TEST,
    MESSAGE_NOTIFICATION_TEST,
    PINCH_TO_ZOOM_TEST,
    SPEED_CHANGE_TEST,
    PIP_MODE_TEST,
    SPLIT_SCREEN_TEST,
    DEVICE_LOCK_TEST
  }

  public static boolean mPlaybackEnded;
  protected long mExpectedTotalTime;
  protected MainActivity mActivity;
  protected ScrollTestActivity mScrollActivity;
  protected long mSendMessagePosition;
  protected int mPreviousOrientation;
  protected int mOrientationIndex;
  protected boolean mScrollRequested;
  protected boolean mTrackChangeRequested;
  protected List<Tracks.Group> mTrackGroups;
  protected Format mStartTrackFormat;
  protected Format mCurrentTrackFormat;
  protected Format mConfiguredTrackFormat;
  protected long mStartTime;

  public PlayerListener() {
    this.mSendMessagePosition = 0;
  }

  /**
   * Returns the type of test.
   */
  public abstract TestType getTestType();

  /**
   * Returns True for Orientation test.
   */
  public final boolean isOrientationTest() {
    return getTestType().equals(TestType.ORIENTATION_TEST);
  }

  /**
   * Returns True for Scroll test.
   */
  public final boolean isScrollTest() {
    return getTestType().equals(TestType.SCROLL_TEST);
  }

  /**
   * Returns True for Call Notification test.
   */
  public final boolean isCallNotificationTest() {
    return getTestType().equals(TestType.CALL_NOTIFICATION_TEST);
  }

  /**
   * Returns True for PinchToZoom test.
   */
  public final boolean isPinchToZoomTest() {
    return getTestType().equals(TestType.PINCH_TO_ZOOM_TEST);
  }

  /**
   * Returns True for PIP Minimized Playback Mode test.
   */
  public final boolean isPipTest() {
    return getTestType().equals(TestType.PIP_MODE_TEST);
  }

  /**
   * Returns True for Split Screen test.
   */
  public final boolean isSplitScreenTest() {
    return getTestType().equals(TestType.SPLIT_SCREEN_TEST);
  }

  /**
   * Returns expected playback time for the playlist.
   */
  public final long getExpectedTotalTime() {
    return mExpectedTotalTime;
  }

  /**
   * Sets activity for test.
   */
  public final void setActivity(MainActivity activity) {
    this.mActivity = activity;
    if (isOrientationTest()) {
      mOrientationIndex = 0;
      mActivity.setRequestedOrientation(
          ORIENTATIONS[mOrientationIndex] /* SCREEN_ORIENTATION_PORTRAIT */);
    }
  }

  /**
   * Get Orientation of the device.
   */
  protected static int getDeviceOrientation(final Activity activity) {
    final DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getDisplay().getRealMetrics(displayMetrics);
    if (displayMetrics.widthPixels < displayMetrics.heightPixels) {
      return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    } else {
      return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
    }
  }

  /**
   * Sets activity for scroll test.
   */
  public final void setScrollActivity(ScrollTestActivity activity) {
    this.mScrollActivity = activity;
  }

  /**
   * Check if two formats are similar.
   *
   * @param refFormat  Reference format
   * @param testFormat Test format
   * @return True, if two formats are similar, false otherwise
   */
  protected final boolean isFormatSimilar(Format refFormat, Format testFormat) {
    String refMediaType = refFormat.sampleMimeType;
    String testMediaType = testFormat.sampleMimeType;
    if (getTestType().equals(TestType.SWITCH_AUDIO_TRACK_TEST)) {
      assertTrue(refMediaType.startsWith("audio/") && testMediaType.startsWith("audio/"));
      if ((refFormat.channelCount != testFormat.channelCount) || (refFormat.sampleRate
          != testFormat.sampleRate)) {
        return false;
      }
    } else if (getTestType().equals(TestType.SWITCH_SUBTITLE_TRACK_TEST)) {
      assertTrue((refMediaType.startsWith("text/") && testMediaType.startsWith("text/")) || (
          refMediaType.startsWith("application/") && testMediaType.startsWith("application/")));
    }
    if (!refMediaType.equals(testMediaType)) {
      return false;
    }
    if (!refFormat.id.equals(testFormat.id)) {
      return false;
    }
    return true;
  }

  /**
   * Called when player states changed.
   *
   * @param player The {@link Player} whose state changed. Use the getters to obtain the latest
   *               states.
   * @param events The {@link Events} that happened in this iteration, indicating which player
   *               states changed.
   */
  public final void onEvents(@NonNull Player player, Events events) {
    if (events.contains(Player.EVENT_PLAYBACK_STATE_CHANGED)) {
      onEventsPlaybackStateChanged(player);
      synchronized (LISTENER_LOCK) {
        if (player.getPlaybackState() == Player.STATE_ENDED) {
          if (mPlaybackEnded) {
            throw new RuntimeException("mPlaybackEnded already set, player could be ended");
          }
          if (!isScrollTest()) {
            mActivity.removePlayerListener();
          } else {
            assertTrue(mScrollRequested);
            mScrollActivity.removePlayerListener();
          }
          // Verify the total time taken by the notification test
          if (getTestType().equals(TestType.CALL_NOTIFICATION_TEST) || getTestType().equals(
              TestType.MESSAGE_NOTIFICATION_TEST)) {
            long actualTime = System.currentTimeMillis() - mStartTime;
            assertEquals((float) mExpectedTotalTime, (float) actualTime,
              NOTIFICATIONTEST_PLAYBACK_DELTA_TIME_US);
          }
          mPlaybackEnded = true;
          LISTENER_LOCK.notify();
        }
      }
    }
    if (events.contains(Player.EVENT_MEDIA_ITEM_TRANSITION)) {
      onEventsMediaItemTransition(player);
      // Add duration on media transition.
      long duration = player.getDuration();
      if (duration != C.TIME_UNSET) {
        mExpectedTotalTime += duration;
      }
    }
  }

  /**
   * Called when the value returned from {@link Player#getPlaybackState()} changes.
   *
   * @param player The {@link Player} whose state changed. Use the getters to obtain the latest
   *               states.
   */
  public abstract void onEventsPlaybackStateChanged(@NonNull Player player);

  /**
   * Called when the value returned from {@link Player#getCurrentMediaItem()} changes or the player
   * starts repeating the current item.
   *
   * @param player The {@link Player} whose state changed. Use the getters to obtain the latest
   *               states.
   */
  public abstract void onEventsMediaItemTransition(@NonNull Player player);

  /**
   * Create a message at given position to change the audio or the subtitle track
   *
   * @param sendMessagePosition Position at which message needs to be executed
   * @param trackGroupIndex     Index of the current track group
   * @param trackIndex          Index of the current track
   */
  protected final void createSwitchTrackMessage(long sendMessagePosition, int trackGroupIndex,
      int trackIndex) {
    mActivity.mPlayer.createMessage((messageType, payload) -> {
          TrackSelectionParameters currentParameters =
              mActivity.mPlayer.getTrackSelectionParameters();
          TrackSelectionParameters newParameters = currentParameters
              .buildUpon()
              .setOverrideForType(
                  new TrackSelectionOverride(
                      mTrackGroups.get(trackGroupIndex).getMediaTrackGroup(),
                      trackIndex))
              .build();
          mActivity.mPlayer.setTrackSelectionParameters(newParameters);
          mConfiguredTrackFormat = mTrackGroups.get(trackGroupIndex)
              .getTrackFormat(trackIndex);
          mTrackChangeRequested = true;
        }).setLooper(Looper.getMainLooper()).setPosition(sendMessagePosition)
        .setDeleteAfterDelivery(true).send();
  }

  /**
   * Called when the value of getCurrentTracks() changes. onEvents(Player, Player.Events) will also
   * be called to report this event along with other events that happen in the same Looper message
   * queue iteration.
   *
   * @param tracks The available tracks information. Never null, but may be of length zero.
   */
  @Override
  public final void onTracksChanged(Tracks tracks) {
    for (Tracks.Group currentTrackGroup : tracks.getGroups()) {
      if (currentTrackGroup.isSelected() && (
          (getTestType().equals(TestType.SWITCH_AUDIO_TRACK_TEST) && (currentTrackGroup.getType()
              == C.TRACK_TYPE_AUDIO)) || (getTestType().equals(TestType.SWITCH_SUBTITLE_TRACK_TEST)
              && (currentTrackGroup.getType() == C.TRACK_TYPE_TEXT)))) {
        for (int trackIndex = 0; trackIndex < currentTrackGroup.length; trackIndex++) {
          if (currentTrackGroup.isTrackSelected(trackIndex)) {
            if (!mTrackChangeRequested) {
              mStartTrackFormat = currentTrackGroup.getTrackFormat(trackIndex);
            } else {
              mCurrentTrackFormat = currentTrackGroup.getTrackFormat(trackIndex);
            }
          }
        }
      }
    }
  }

  /**
   * Get all audio/subtitle tracks group from the player's Tracks.
   */
  protected final List<Tracks.Group> getTrackGroups() {
    List<Tracks.Group> trackGroups = new ArrayList<>();
    Tracks currentTracks = mActivity.mPlayer.getCurrentTracks();
    for (Tracks.Group currentTrackGroup : currentTracks.getGroups()) {
      if ((currentTrackGroup.getType() == C.TRACK_TYPE_AUDIO) || (currentTrackGroup.getType()
          == C.TRACK_TYPE_TEXT)) {
        trackGroups.add(currentTrackGroup);
      }
    }
    return trackGroups;
  }
}