blob: 4a10f50dde5a659b1a72b5dfd0dd51bce0de24f8 [file] [log] [blame]
Jungshik Jang0792d372014-04-23 17:57:26 +09001/*
2 * Copyright (C) 2014 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
17package com.android.server.hdmi;
18
Jinsuk Kim0340bbc2014-06-05 11:07:47 +090019import android.hardware.hdmi.HdmiPortInfo;
Donghyun Chobc6e3722016-11-04 05:25:52 +090020import android.hardware.tv.cec.V1_0.Result;
21import android.hardware.tv.cec.V1_0.SendMessageResult;
Jungshik Jang0792d372014-04-23 17:57:26 +090022import android.os.Handler;
Jungshik Jang02bb4262014-05-23 16:48:31 +090023import android.os.Looper;
Jungshik Jang4085d0e2014-05-27 19:52:39 +090024import android.os.MessageQueue;
Yuncheol Heoece603b2014-05-23 20:10:19 +090025import android.util.Slog;
Jungshik Jang7d9a8432014-04-29 15:12:43 +090026import android.util.SparseArray;
Terry Heo959d2db2014-08-28 16:45:41 +090027import com.android.internal.util.IndentingPrintWriter;
Jungshik Jang0f8b4b72014-05-28 17:58:58 +090028import com.android.internal.util.Predicate;
Jungshik Janga5b74142014-06-23 18:03:10 +090029import com.android.server.hdmi.HdmiAnnotations.IoThreadOnly;
30import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly;
Jungshik Jang02bb4262014-05-23 16:48:31 +090031import com.android.server.hdmi.HdmiControlService.DevicePollingCallback;
Donghyun Cho0b485b22016-12-13 17:21:01 +090032import java.text.SimpleDateFormat;
Jungshik Jang7d9a8432014-04-29 15:12:43 +090033import java.util.ArrayList;
Donghyun Cho0b485b22016-12-13 17:21:01 +090034import java.util.Date;
Jungshik Jangb3ecb722014-09-11 16:09:45 +090035import java.util.LinkedList;
Jungshik Jang7d9a8432014-04-29 15:12:43 +090036import java.util.List;
Donghyun Cho0b485b22016-12-13 17:21:01 +090037import java.util.concurrent.ArrayBlockingQueue;
Donghyun Chobc6e3722016-11-04 05:25:52 +090038import libcore.util.EmptyArray;
39import sun.util.locale.LanguageTag;
Jungshik Jang0792d372014-04-23 17:57:26 +090040
41/**
42 * Manages HDMI-CEC command and behaviors. It converts user's command into CEC command
43 * and pass it to CEC HAL so that it sends message to other device. For incoming
44 * message it translates the message and delegates it to proper module.
45 *
Jungshik Jang02bb4262014-05-23 16:48:31 +090046 * <p>It should be careful to access member variables on IO thread because
47 * it can be accessed from system thread as well.
48 *
Jungshik Jang0792d372014-04-23 17:57:26 +090049 * <p>It can be created only by {@link HdmiCecController#create}
50 *
51 * <p>Declared as package-private, accessed by {@link HdmiControlService} only.
52 */
Jungshik Janga9095ba2014-05-02 13:06:22 +090053final class HdmiCecController {
Jungshik Jang0792d372014-04-23 17:57:26 +090054 private static final String TAG = "HdmiCecController";
55
Jungshik Jang3ee65722014-06-03 16:22:30 +090056 /**
57 * Interface to report allocated logical address.
58 */
59 interface AllocateAddressCallback {
60 /**
61 * Called when a new logical address is allocated.
62 *
63 * @param deviceType requested device type to allocate logical address
64 * @param logicalAddress allocated logical address. If it is
Jungshik Jang42230722014-07-07 17:40:25 +090065 * {@link Constants#ADDR_UNREGISTERED}, it means that
Jungshik Jang3ee65722014-06-03 16:22:30 +090066 * it failed to allocate logical address for the given device type
67 */
68 void onAllocated(int deviceType, int logicalAddress);
69 }
70
Jungshik Jang3f74ab02014-04-30 14:31:02 +090071 private static final byte[] EMPTY_BODY = EmptyArray.BYTE;
72
Jungshik Jang3f74ab02014-04-30 14:31:02 +090073 private static final int NUM_LOGICAL_ADDRESS = 16;
74
Donghyun Cho0b485b22016-12-13 17:21:01 +090075 private static final int MAX_CEC_MESSAGE_HISTORY = 20;
76
Jungshik Jang0f8b4b72014-05-28 17:58:58 +090077 // Predicate for whether the given logical address is remote device's one or not.
78 private final Predicate<Integer> mRemoteDeviceAddressPredicate = new Predicate<Integer>() {
79 @Override
80 public boolean apply(Integer address) {
81 return !isAllocatedLocalDeviceAddress(address);
82 }
83 };
84
85 // Predicate whether the given logical address is system audio's one or not
86 private final Predicate<Integer> mSystemAudioAddressPredicate = new Predicate<Integer>() {
87 @Override
88 public boolean apply(Integer address) {
Jinsuk Kimc0c20d02014-07-04 14:34:31 +090089 return HdmiUtils.getTypeFromAddress(address) == Constants.ADDR_AUDIO_SYSTEM;
Jungshik Jang0f8b4b72014-05-28 17:58:58 +090090 }
91 };
92
Jungshik Jang0792d372014-04-23 17:57:26 +090093 // Handler instance to process synchronous I/O (mainly send) message.
94 private Handler mIoHandler;
95
96 // Handler instance to process various messages coming from other CEC
97 // device or issued by internal state change.
Jungshik Jange9c77c82014-04-24 20:30:09 +090098 private Handler mControlHandler;
Jungshik Jang0792d372014-04-23 17:57:26 +090099
100 // Stores the pointer to the native implementation of the service that
101 // interacts with HAL.
Jungshik Jang02bb4262014-05-23 16:48:31 +0900102 private volatile long mNativePtr;
Jungshik Jang0792d372014-04-23 17:57:26 +0900103
Jungshik Jang7df52862014-08-11 14:35:27 +0900104 private final HdmiControlService mService;
Jungshik Janga1fa91f2014-05-08 20:56:41 +0900105
Jinsuk Kim7fe2ae02014-05-26 17:33:05 +0900106 // Stores the local CEC devices in the system. Device type is used for key.
107 private final SparseArray<HdmiCecLocalDevice> mLocalDevices = new SparseArray<>();
Jungshik Jang7d9a8432014-04-29 15:12:43 +0900108
Donghyun Cho0b485b22016-12-13 17:21:01 +0900109 // Stores recent CEC messages history for debugging purpose.
110 private final ArrayBlockingQueue<MessageHistoryRecord> mMessageHistory =
111 new ArrayBlockingQueue<>(MAX_CEC_MESSAGE_HISTORY);
112
Jungshik Jang0792d372014-04-23 17:57:26 +0900113 // Private constructor. Use HdmiCecController.create().
Jungshik Jang7df52862014-08-11 14:35:27 +0900114 private HdmiCecController(HdmiControlService service) {
115 mService = service;
Jungshik Jang0792d372014-04-23 17:57:26 +0900116 }
117
118 /**
119 * A factory method to get {@link HdmiCecController}. If it fails to initialize
120 * inner device or has no device it will return {@code null}.
121 *
122 * <p>Declared as package-private, accessed by {@link HdmiControlService} only.
Jungshik Jange9c77c82014-04-24 20:30:09 +0900123 * @param service {@link HdmiControlService} instance used to create internal handler
124 * and to pass callback for incoming message or event.
Jungshik Jang0792d372014-04-23 17:57:26 +0900125 * @return {@link HdmiCecController} if device is initialized successfully. Otherwise,
126 * returns {@code null}.
127 */
Jungshik Jange9c77c82014-04-24 20:30:09 +0900128 static HdmiCecController create(HdmiControlService service) {
Jungshik Jang7df52862014-08-11 14:35:27 +0900129 HdmiCecController controller = new HdmiCecController(service);
Jungshik Jang4085d0e2014-05-27 19:52:39 +0900130 long nativePtr = nativeInit(controller, service.getServiceLooper().getQueue());
Jungshik Jang0792d372014-04-23 17:57:26 +0900131 if (nativePtr == 0L) {
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900132 controller = null;
Jungshik Jang0792d372014-04-23 17:57:26 +0900133 return null;
134 }
135
Jungshik Jang7df52862014-08-11 14:35:27 +0900136 controller.init(nativePtr);
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900137 return controller;
138 }
139
Jungshik Jang7df52862014-08-11 14:35:27 +0900140 private void init(long nativePtr) {
Yuncheol Heof1702482014-11-27 19:52:01 +0900141 mIoHandler = new Handler(mService.getIoLooper());
Jungshik Jang7df52862014-08-11 14:35:27 +0900142 mControlHandler = new Handler(mService.getServiceLooper());
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900143 mNativePtr = nativePtr;
Jungshik Jang0792d372014-04-23 17:57:26 +0900144 }
145
Jungshik Janga5b74142014-06-23 18:03:10 +0900146 @ServiceThreadOnly
Jungshik Jang3ee65722014-06-03 16:22:30 +0900147 void addLocalDevice(int deviceType, HdmiCecLocalDevice device) {
Jungshik Janga5b74142014-06-23 18:03:10 +0900148 assertRunOnServiceThread();
Jungshik Jang3ee65722014-06-03 16:22:30 +0900149 mLocalDevices.put(deviceType, device);
Jungshik Jang3f74ab02014-04-30 14:31:02 +0900150 }
151
152 /**
153 * Allocate a new logical address of the given device type. Allocated
Jungshik Jang3ee65722014-06-03 16:22:30 +0900154 * address will be reported through {@link AllocateAddressCallback}.
Jungshik Jang3f74ab02014-04-30 14:31:02 +0900155 *
156 * <p> Declared as package-private, accessed by {@link HdmiControlService} only.
157 *
158 * @param deviceType type of device to used to determine logical address
159 * @param preferredAddress a logical address preferred to be allocated.
Jungshik Jang42230722014-07-07 17:40:25 +0900160 * If sets {@link Constants#ADDR_UNREGISTERED}, scans
Jungshik Jang3f74ab02014-04-30 14:31:02 +0900161 * the smallest logical address matched with the given device type.
162 * Otherwise, scan address will start from {@code preferredAddress}
163 * @param callback callback interface to report allocated logical address to caller
164 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900165 @ServiceThreadOnly
Jungshik Jangd643f762014-05-22 19:28:09 +0900166 void allocateLogicalAddress(final int deviceType, final int preferredAddress,
Jungshik Jang3ee65722014-06-03 16:22:30 +0900167 final AllocateAddressCallback callback) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900168 assertRunOnServiceThread();
169
Jungshik Jangd643f762014-05-22 19:28:09 +0900170 runOnIoThread(new Runnable() {
171 @Override
172 public void run() {
173 handleAllocateLogicalAddress(deviceType, preferredAddress, callback);
174 }
175 });
176 }
177
Jungshik Janga5b74142014-06-23 18:03:10 +0900178 @IoThreadOnly
Jungshik Jangd643f762014-05-22 19:28:09 +0900179 private void handleAllocateLogicalAddress(final int deviceType, int preferredAddress,
Jungshik Jang3ee65722014-06-03 16:22:30 +0900180 final AllocateAddressCallback callback) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900181 assertRunOnIoThread();
Jungshik Jangd643f762014-05-22 19:28:09 +0900182 int startAddress = preferredAddress;
183 // If preferred address is "unregistered", start address will be the smallest
184 // address matched with the given device type.
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900185 if (preferredAddress == Constants.ADDR_UNREGISTERED) {
Jungshik Jangd643f762014-05-22 19:28:09 +0900186 for (int i = 0; i < NUM_LOGICAL_ADDRESS; ++i) {
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900187 if (deviceType == HdmiUtils.getTypeFromAddress(i)) {
Jungshik Jangd643f762014-05-22 19:28:09 +0900188 startAddress = i;
189 break;
190 }
191 }
192 }
193
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900194 int logicalAddress = Constants.ADDR_UNREGISTERED;
Jungshik Jangd643f762014-05-22 19:28:09 +0900195 // Iterates all possible addresses which has the same device type.
196 for (int i = 0; i < NUM_LOGICAL_ADDRESS; ++i) {
197 int curAddress = (startAddress + i) % NUM_LOGICAL_ADDRESS;
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900198 if (curAddress != Constants.ADDR_UNREGISTERED
199 && deviceType == HdmiUtils.getTypeFromAddress(curAddress)) {
Donghyun Chodbf9f9c2016-07-04 20:39:26 +0900200 boolean acked = false;
Jungshik Jang8e93c842014-08-06 15:48:33 +0900201 for (int j = 0; j < HdmiConfig.ADDRESS_ALLOCATION_RETRY; ++j) {
Donghyun Chodbf9f9c2016-07-04 20:39:26 +0900202 if (sendPollMessage(curAddress, curAddress, 1)) {
203 acked = true;
204 break;
Jungshik Jang8e93c842014-08-06 15:48:33 +0900205 }
206 }
Donghyun Chodbf9f9c2016-07-04 20:39:26 +0900207 // If sending <Polling Message> failed, it becomes new logical address for the
208 // device because no device uses it as logical address of the device.
209 if (!acked) {
Jungshik Jangd643f762014-05-22 19:28:09 +0900210 logicalAddress = curAddress;
211 break;
212 }
213 }
214 }
215
216 final int assignedAddress = logicalAddress;
Jungshik Jang2e8f1b62014-09-03 08:28:02 +0900217 HdmiLogger.debug("New logical address for device [%d]: [preferred:%d, assigned:%d]",
218 deviceType, preferredAddress, assignedAddress);
Jungshik Jangd643f762014-05-22 19:28:09 +0900219 if (callback != null) {
220 runOnServiceThread(new Runnable() {
Jungshik Jang8e93c842014-08-06 15:48:33 +0900221 @Override
Jungshik Jangd643f762014-05-22 19:28:09 +0900222 public void run() {
223 callback.onAllocated(deviceType, assignedAddress);
224 }
225 });
226 }
Jungshik Jang3f74ab02014-04-30 14:31:02 +0900227 }
228
Jungshik Jange9c77c82014-04-24 20:30:09 +0900229 private static byte[] buildBody(int opcode, byte[] params) {
230 byte[] body = new byte[params.length + 1];
231 body[0] = (byte) opcode;
232 System.arraycopy(params, 0, body, 1, params.length);
233 return body;
234 }
Jungshik Jang0792d372014-04-23 17:57:26 +0900235
Jungshik Jang7d9a8432014-04-29 15:12:43 +0900236
Jinsuk Kim0340bbc2014-06-05 11:07:47 +0900237 HdmiPortInfo[] getPortInfos() {
238 return nativeGetPortInfos(mNativePtr);
239 }
240
Jungshik Janga9095ba2014-05-02 13:06:22 +0900241 /**
Jinsuk Kim7fe2ae02014-05-26 17:33:05 +0900242 * Return the locally hosted logical device of a given type.
243 *
244 * @param deviceType logical device type
245 * @return {@link HdmiCecLocalDevice} instance if the instance of the type is available;
246 * otherwise null.
247 */
248 HdmiCecLocalDevice getLocalDevice(int deviceType) {
249 return mLocalDevices.get(deviceType);
250 }
251
252 /**
Jungshik Janga9095ba2014-05-02 13:06:22 +0900253 * Add a new logical address to the device. Device's HW should be notified
254 * when a new logical address is assigned to a device, so that it can accept
255 * a command having available destinations.
256 *
257 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
258 *
259 * @param newLogicalAddress a logical address to be added
260 * @return 0 on success. Otherwise, returns negative value
261 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900262 @ServiceThreadOnly
Jungshik Janga9095ba2014-05-02 13:06:22 +0900263 int addLogicalAddress(int newLogicalAddress) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900264 assertRunOnServiceThread();
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900265 if (HdmiUtils.isValidAddress(newLogicalAddress)) {
Jungshik Janga9095ba2014-05-02 13:06:22 +0900266 return nativeAddLogicalAddress(mNativePtr, newLogicalAddress);
267 } else {
Donghyun Chobc6e3722016-11-04 05:25:52 +0900268 return Result.FAILURE_INVALID_ARGS;
Jungshik Janga9095ba2014-05-02 13:06:22 +0900269 }
270 }
271
272 /**
273 * Clear all logical addresses registered in the device.
274 *
275 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
276 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900277 @ServiceThreadOnly
Jungshik Janga9095ba2014-05-02 13:06:22 +0900278 void clearLogicalAddress() {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900279 assertRunOnServiceThread();
Jinsuk Kim7fe2ae02014-05-26 17:33:05 +0900280 for (int i = 0; i < mLocalDevices.size(); ++i) {
281 mLocalDevices.valueAt(i).clearAddress();
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900282 }
Jungshik Janga9095ba2014-05-02 13:06:22 +0900283 nativeClearLogicalAddress(mNativePtr);
284 }
285
Jungshik Jang4fc1d102014-07-09 19:24:50 +0900286 @ServiceThreadOnly
287 void clearLocalDevices() {
288 assertRunOnServiceThread();
289 mLocalDevices.clear();
290 }
291
Jungshik Janga9095ba2014-05-02 13:06:22 +0900292 /**
293 * Return the physical address of the device.
294 *
295 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
296 *
297 * @return CEC physical address of the device. The range of success address
298 * is between 0x0000 and 0xFFFF. If failed it returns -1
299 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900300 @ServiceThreadOnly
Jungshik Janga9095ba2014-05-02 13:06:22 +0900301 int getPhysicalAddress() {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900302 assertRunOnServiceThread();
Jungshik Janga9095ba2014-05-02 13:06:22 +0900303 return nativeGetPhysicalAddress(mNativePtr);
304 }
305
306 /**
307 * Return CEC version of the device.
308 *
309 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
310 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900311 @ServiceThreadOnly
Jungshik Janga9095ba2014-05-02 13:06:22 +0900312 int getVersion() {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900313 assertRunOnServiceThread();
Jungshik Janga9095ba2014-05-02 13:06:22 +0900314 return nativeGetVersion(mNativePtr);
315 }
316
317 /**
318 * Return vendor id of the device.
319 *
320 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
321 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900322 @ServiceThreadOnly
Jungshik Janga9095ba2014-05-02 13:06:22 +0900323 int getVendorId() {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900324 assertRunOnServiceThread();
Jungshik Janga9095ba2014-05-02 13:06:22 +0900325 return nativeGetVendorId(mNativePtr);
326 }
327
Jungshik Jang02bb4262014-05-23 16:48:31 +0900328 /**
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900329 * Set an option to CEC HAL.
Jungshik Jang092b4452014-06-11 15:19:17 +0900330 *
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900331 * @param flag key of option
Donghyun Chobc6e3722016-11-04 05:25:52 +0900332 * @param enabled whether to enable/disable the given option.
Jungshik Jang092b4452014-06-11 15:19:17 +0900333 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900334 @ServiceThreadOnly
Donghyun Chobc6e3722016-11-04 05:25:52 +0900335 void setOption(int flag, boolean enabled) {
Jungshik Jang092b4452014-06-11 15:19:17 +0900336 assertRunOnServiceThread();
Donghyun Chobc6e3722016-11-04 05:25:52 +0900337 HdmiLogger.debug("setOption: [flag:%d, enabled:%b]", flag, enabled);
338 nativeSetOption(mNativePtr, flag, enabled);
339 }
340
341 /**
342 * Informs CEC HAL about the current system language.
343 *
344 * @param language Three-letter code defined in ISO/FDIS 639-2. Must be lowercase letters.
345 */
346 @ServiceThreadOnly
347 void setLanguage(String language) {
348 assertRunOnServiceThread();
349 if (!LanguageTag.isLanguage(language)) {
350 return;
351 }
352 nativeSetLanguage(mNativePtr, language);
Jungshik Jang092b4452014-06-11 15:19:17 +0900353 }
354
355 /**
356 * Configure ARC circuit in the hardware logic to start or stop the feature.
357 *
Jinsuk Kim1481a422014-12-17 16:15:05 +0900358 * @param port ID of HDMI port to which AVR is connected
Jungshik Jang092b4452014-06-11 15:19:17 +0900359 * @param enabled whether to enable/disable ARC
360 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900361 @ServiceThreadOnly
Donghyun Chobc6e3722016-11-04 05:25:52 +0900362 void enableAudioReturnChannel(int port, boolean enabled) {
Jungshik Jang092b4452014-06-11 15:19:17 +0900363 assertRunOnServiceThread();
Donghyun Chobc6e3722016-11-04 05:25:52 +0900364 nativeEnableAudioReturnChannel(mNativePtr, port, enabled);
Jungshik Jang092b4452014-06-11 15:19:17 +0900365 }
366
367 /**
368 * Return the connection status of the specified port
369 *
370 * @param port port number to check connection status
371 * @return true if connected; otherwise, return false
372 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900373 @ServiceThreadOnly
Jungshik Jang092b4452014-06-11 15:19:17 +0900374 boolean isConnected(int port) {
375 assertRunOnServiceThread();
376 return nativeIsConnected(mNativePtr, port);
377 }
378
379 /**
Jungshik Jang02bb4262014-05-23 16:48:31 +0900380 * Poll all remote devices. It sends &lt;Polling Message&gt; to all remote
381 * devices.
382 *
383 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
384 *
385 * @param callback an interface used to get a list of all remote devices' address
Jungshik Jang1de51422014-07-03 11:14:26 +0900386 * @param sourceAddress a logical address of source device where sends polling message
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900387 * @param pickStrategy strategy how to pick polling candidates
Jungshik Jang02bb4262014-05-23 16:48:31 +0900388 * @param retryCount the number of retry used to send polling message to remote devices
389 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900390 @ServiceThreadOnly
Jungshik Jang1de51422014-07-03 11:14:26 +0900391 void pollDevices(DevicePollingCallback callback, int sourceAddress, int pickStrategy,
392 int retryCount) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900393 assertRunOnServiceThread();
Jungshik Jang02bb4262014-05-23 16:48:31 +0900394
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900395 // Extract polling candidates. No need to poll against local devices.
396 List<Integer> pollingCandidates = pickPollCandidates(pickStrategy);
Jungshik Jangb3ecb722014-09-11 16:09:45 +0900397 ArrayList<Integer> allocated = new ArrayList<>();
398 runDevicePolling(sourceAddress, pollingCandidates, retryCount, callback, allocated);
Jungshik Jang02bb4262014-05-23 16:48:31 +0900399 }
400
Jungshik Jangcc5ef8c2014-05-27 13:27:36 +0900401 /**
402 * Return a list of all {@link HdmiCecLocalDevice}s.
403 *
404 * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
405 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900406 @ServiceThreadOnly
Jungshik Jangcc5ef8c2014-05-27 13:27:36 +0900407 List<HdmiCecLocalDevice> getLocalDeviceList() {
408 assertRunOnServiceThread();
Jungshik Jang79c58a42014-06-16 16:45:36 +0900409 return HdmiUtils.sparseArrayToList(mLocalDevices);
Jungshik Jangcc5ef8c2014-05-27 13:27:36 +0900410 }
411
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900412 private List<Integer> pickPollCandidates(int pickStrategy) {
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900413 int strategy = pickStrategy & Constants.POLL_STRATEGY_MASK;
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900414 Predicate<Integer> pickPredicate = null;
415 switch (strategy) {
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900416 case Constants.POLL_STRATEGY_SYSTEM_AUDIO:
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900417 pickPredicate = mSystemAudioAddressPredicate;
418 break;
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900419 case Constants.POLL_STRATEGY_REMOTES_DEVICES:
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900420 default: // The default is POLL_STRATEGY_REMOTES_DEVICES.
421 pickPredicate = mRemoteDeviceAddressPredicate;
422 break;
423 }
424
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900425 int iterationStrategy = pickStrategy & Constants.POLL_ITERATION_STRATEGY_MASK;
Jungshik Jangb3ecb722014-09-11 16:09:45 +0900426 LinkedList<Integer> pollingCandidates = new LinkedList<>();
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900427 switch (iterationStrategy) {
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900428 case Constants.POLL_ITERATION_IN_ORDER:
429 for (int i = Constants.ADDR_TV; i <= Constants.ADDR_SPECIFIC_USE; ++i) {
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900430 if (pickPredicate.apply(i)) {
431 pollingCandidates.add(i);
432 }
433 }
434 break;
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900435 case Constants.POLL_ITERATION_REVERSE_ORDER:
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900436 default: // The default is reverse order.
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900437 for (int i = Constants.ADDR_SPECIFIC_USE; i >= Constants.ADDR_TV; --i) {
Jungshik Jang0f8b4b72014-05-28 17:58:58 +0900438 if (pickPredicate.apply(i)) {
439 pollingCandidates.add(i);
440 }
441 }
442 break;
443 }
444 return pollingCandidates;
445 }
446
Jungshik Janga5b74142014-06-23 18:03:10 +0900447 @ServiceThreadOnly
Jungshik Jang02bb4262014-05-23 16:48:31 +0900448 private boolean isAllocatedLocalDeviceAddress(int address) {
Jungshik Janga5b74142014-06-23 18:03:10 +0900449 assertRunOnServiceThread();
Jinsuk Kim7fe2ae02014-05-26 17:33:05 +0900450 for (int i = 0; i < mLocalDevices.size(); ++i) {
451 if (mLocalDevices.valueAt(i).isAddressOf(address)) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900452 return true;
453 }
454 }
455 return false;
456 }
457
Jungshik Janga5b74142014-06-23 18:03:10 +0900458 @ServiceThreadOnly
Jungshik Jang1de51422014-07-03 11:14:26 +0900459 private void runDevicePolling(final int sourceAddress,
460 final List<Integer> candidates, final int retryCount,
Jungshik Jangb3ecb722014-09-11 16:09:45 +0900461 final DevicePollingCallback callback, final List<Integer> allocated) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900462 assertRunOnServiceThread();
Jungshik Jangb3ecb722014-09-11 16:09:45 +0900463 if (candidates.isEmpty()) {
464 if (callback != null) {
465 HdmiLogger.debug("[P]:AllocatedAddress=%s", allocated.toString());
466 callback.onPollingFinished(allocated);
467 }
468 return;
469 }
470
471 final Integer candidate = candidates.remove(0);
472 // Proceed polling action for the next address once polling action for the
473 // previous address is done.
Jungshik Jang02bb4262014-05-23 16:48:31 +0900474 runOnIoThread(new Runnable() {
475 @Override
476 public void run() {
Jungshik Jangb3ecb722014-09-11 16:09:45 +0900477 if (sendPollMessage(sourceAddress, candidate, retryCount)) {
478 allocated.add(candidate);
479 }
480 runOnServiceThread(new Runnable() {
481 @Override
482 public void run() {
483 runDevicePolling(sourceAddress, candidates, retryCount, callback,
484 allocated);
Jungshik Jang02bb4262014-05-23 16:48:31 +0900485 }
Jungshik Jangb3ecb722014-09-11 16:09:45 +0900486 });
Jungshik Jang02bb4262014-05-23 16:48:31 +0900487 }
488 });
489 }
490
Jungshik Janga5b74142014-06-23 18:03:10 +0900491 @IoThreadOnly
Jungshik Jang1de51422014-07-03 11:14:26 +0900492 private boolean sendPollMessage(int sourceAddress, int destinationAddress, int retryCount) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900493 assertRunOnIoThread();
494 for (int i = 0; i < retryCount; ++i) {
Jungshik Jang1de51422014-07-03 11:14:26 +0900495 // <Polling Message> is a message which has empty body.
Donghyun Chodbf9f9c2016-07-04 20:39:26 +0900496 int ret =
497 nativeSendCecCommand(mNativePtr, sourceAddress, destinationAddress, EMPTY_BODY);
Donghyun Chobc6e3722016-11-04 05:25:52 +0900498 if (ret == SendMessageResult.SUCCESS) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900499 return true;
Donghyun Chobc6e3722016-11-04 05:25:52 +0900500 } else if (ret != SendMessageResult.NACK) {
Donghyun Chodbf9f9c2016-07-04 20:39:26 +0900501 // Unusual failure
502 HdmiLogger.warning("Failed to send a polling message(%d->%d) with return code %d",
503 sourceAddress, destinationAddress, ret);
Jungshik Jang02bb4262014-05-23 16:48:31 +0900504 }
505 }
506 return false;
507 }
508
509 private void assertRunOnIoThread() {
510 if (Looper.myLooper() != mIoHandler.getLooper()) {
511 throw new IllegalStateException("Should run on io thread.");
512 }
513 }
514
515 private void assertRunOnServiceThread() {
516 if (Looper.myLooper() != mControlHandler.getLooper()) {
517 throw new IllegalStateException("Should run on service thread.");
518 }
519 }
520
521 // Run a Runnable on IO thread.
522 // It should be careful to access member variables on IO thread because
523 // it can be accessed from system thread as well.
Jungshik Jangd643f762014-05-22 19:28:09 +0900524 private void runOnIoThread(Runnable runnable) {
525 mIoHandler.post(runnable);
526 }
527
528 private void runOnServiceThread(Runnable runnable) {
529 mControlHandler.post(runnable);
530 }
531
Yuncheol Heof1702482014-11-27 19:52:01 +0900532 @ServiceThreadOnly
533 void flush(final Runnable runnable) {
534 assertRunOnServiceThread();
535 runOnIoThread(new Runnable() {
536 @Override
537 public void run() {
538 // This ensures the runnable for cleanup is performed after all the pending
539 // commands are processed by IO thread.
540 runOnServiceThread(runnable);
541 }
542 });
543 }
544
Jungshik Janga1fa91f2014-05-08 20:56:41 +0900545 private boolean isAcceptableAddress(int address) {
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900546 // Can access command targeting devices available in local device or broadcast command.
Jinsuk Kimc0c20d02014-07-04 14:34:31 +0900547 if (address == Constants.ADDR_BROADCAST) {
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900548 return true;
549 }
Jungshik Jang02bb4262014-05-23 16:48:31 +0900550 return isAllocatedLocalDeviceAddress(address);
Jungshik Janga1fa91f2014-05-08 20:56:41 +0900551 }
552
Jungshik Janga5b74142014-06-23 18:03:10 +0900553 @ServiceThreadOnly
Jungshik Jange9c77c82014-04-24 20:30:09 +0900554 private void onReceiveCommand(HdmiCecMessage message) {
Jungshik Jang02bb4262014-05-23 16:48:31 +0900555 assertRunOnServiceThread();
Yuncheol Heo6aae6522014-08-05 14:48:37 +0900556 if (isAcceptableAddress(message.getDestination()) && mService.handleCecCommand(message)) {
Jungshik Janga1fa91f2014-05-08 20:56:41 +0900557 return;
558 }
Yuncheol Heo6aae6522014-08-05 14:48:37 +0900559 // Not handled message, so we will reply it with <Feature Abort>.
560 maySendFeatureAbortCommand(message, Constants.ABORT_UNRECOGNIZED_OPCODE);
561 }
Jungshik Jang1827fdc2014-07-17 13:58:14 +0900562
Yuncheol Heo6aae6522014-08-05 14:48:37 +0900563 @ServiceThreadOnly
564 void maySendFeatureAbortCommand(HdmiCecMessage message, int reason) {
565 assertRunOnServiceThread();
566 // Swap the source and the destination.
567 int src = message.getDestination();
568 int dest = message.getSource();
569 if (src == Constants.ADDR_BROADCAST || dest == Constants.ADDR_UNREGISTERED) {
570 // Don't reply <Feature Abort> from the unregistered devices or for the broadcasted
571 // messages. See CEC 12.2 Protocol General Rules for detail.
572 return;
573 }
574 int originalOpcode = message.getOpcode();
575 if (originalOpcode == Constants.MESSAGE_FEATURE_ABORT) {
576 return;
577 }
578 sendCommand(
579 HdmiCecMessageBuilder.buildFeatureAbortCommand(src, dest, originalOpcode, reason));
Jungshik Jange9c77c82014-04-24 20:30:09 +0900580 }
581
Jungshik Janga5b74142014-06-23 18:03:10 +0900582 @ServiceThreadOnly
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900583 void sendCommand(HdmiCecMessage cecMessage) {
Jungshik Janga5b74142014-06-23 18:03:10 +0900584 assertRunOnServiceThread();
Jinsuk Kim2918e9e2014-05-20 16:45:45 +0900585 sendCommand(cecMessage, null);
586 }
587
Jungshik Janga5b74142014-06-23 18:03:10 +0900588 @ServiceThreadOnly
Jungshik Jangd643f762014-05-22 19:28:09 +0900589 void sendCommand(final HdmiCecMessage cecMessage,
590 final HdmiControlService.SendMessageCallback callback) {
Jungshik Janga5b74142014-06-23 18:03:10 +0900591 assertRunOnServiceThread();
Donghyun Cho0b485b22016-12-13 17:21:01 +0900592 addMessageToHistory(false /* isReceived */, cecMessage);
Jungshik Jangd643f762014-05-22 19:28:09 +0900593 runOnIoThread(new Runnable() {
594 @Override
595 public void run() {
Jungshik Jang2e8f1b62014-09-03 08:28:02 +0900596 HdmiLogger.debug("[S]:" + cecMessage);
Jungshik Jangd643f762014-05-22 19:28:09 +0900597 byte[] body = buildBody(cecMessage.getOpcode(), cecMessage.getParams());
Jungshik Jang8ed86c42014-07-11 11:56:46 +0900598 int i = 0;
Donghyun Chobc6e3722016-11-04 05:25:52 +0900599 int errorCode = SendMessageResult.SUCCESS;
Jungshik Jang8ed86c42014-07-11 11:56:46 +0900600 do {
601 errorCode = nativeSendCecCommand(mNativePtr, cecMessage.getSource(),
602 cecMessage.getDestination(), body);
Donghyun Chobc6e3722016-11-04 05:25:52 +0900603 if (errorCode == SendMessageResult.SUCCESS) {
Jungshik Jang8ed86c42014-07-11 11:56:46 +0900604 break;
605 }
606 } while (i++ < HdmiConfig.RETRANSMISSION_COUNT);
607
608 final int finalError = errorCode;
Donghyun Chobc6e3722016-11-04 05:25:52 +0900609 if (finalError != SendMessageResult.SUCCESS) {
Donghyun Cho0b485b22016-12-13 17:21:01 +0900610 Slog.w(TAG, "Failed to send " + cecMessage + " with errorCode=" + finalError);
Yuncheol Heoece603b2014-05-23 20:10:19 +0900611 }
Jungshik Jangd643f762014-05-22 19:28:09 +0900612 if (callback != null) {
613 runOnServiceThread(new Runnable() {
614 @Override
615 public void run() {
Jungshik Jang8ed86c42014-07-11 11:56:46 +0900616 callback.onSendCompleted(finalError);
Jungshik Jangd643f762014-05-22 19:28:09 +0900617 }
618 });
619 }
620 }
621 });
Jungshik Jange9c77c82014-04-24 20:30:09 +0900622 }
623
Jungshik Jang0792d372014-04-23 17:57:26 +0900624 /**
Jungshik Jange9c77c82014-04-24 20:30:09 +0900625 * Called by native when incoming CEC message arrived.
Jungshik Jang0792d372014-04-23 17:57:26 +0900626 */
Jungshik Janga5b74142014-06-23 18:03:10 +0900627 @ServiceThreadOnly
Jungshik Jange9c77c82014-04-24 20:30:09 +0900628 private void handleIncomingCecCommand(int srcAddress, int dstAddress, byte[] body) {
Jungshik Jang4085d0e2014-05-27 19:52:39 +0900629 assertRunOnServiceThread();
Jungshik Jangc94ac5c2014-08-27 13:48:37 +0900630 HdmiCecMessage command = HdmiCecMessageBuilder.of(srcAddress, dstAddress, body);
Jungshik Jang2e8f1b62014-09-03 08:28:02 +0900631 HdmiLogger.debug("[R]:" + command);
Donghyun Cho0b485b22016-12-13 17:21:01 +0900632 addMessageToHistory(true /* isReceived */, command);
Jungshik Jangc94ac5c2014-08-27 13:48:37 +0900633 onReceiveCommand(command);
Jungshik Jange9c77c82014-04-24 20:30:09 +0900634 }
635
636 /**
637 * Called by native when a hotplug event issues.
638 */
Jungshik Jang42230722014-07-07 17:40:25 +0900639 @ServiceThreadOnly
640 private void handleHotplug(int port, boolean connected) {
641 assertRunOnServiceThread();
Jungshik Jang2e8f1b62014-09-03 08:28:02 +0900642 HdmiLogger.debug("Hotplug event:[port:%d, connected:%b]", port, connected);
Jungshik Jang42230722014-07-07 17:40:25 +0900643 mService.onHotplug(port, connected);
Jungshik Jang0792d372014-04-23 17:57:26 +0900644 }
645
Donghyun Cho0b485b22016-12-13 17:21:01 +0900646 @ServiceThreadOnly
647 private void addMessageToHistory(boolean isReceived, HdmiCecMessage message) {
648 assertRunOnServiceThread();
649 MessageHistoryRecord record = new MessageHistoryRecord(isReceived, message);
650 if (!mMessageHistory.offer(record)) {
651 mMessageHistory.poll();
652 mMessageHistory.offer(record);
653 }
654 }
655
Terry Heo959d2db2014-08-28 16:45:41 +0900656 void dump(final IndentingPrintWriter pw) {
657 for (int i = 0; i < mLocalDevices.size(); ++i) {
658 pw.println("HdmiCecLocalDevice #" + i + ":");
659 pw.increaseIndent();
660 mLocalDevices.valueAt(i).dump(pw);
661 pw.decreaseIndent();
662 }
Donghyun Cho0b485b22016-12-13 17:21:01 +0900663 pw.println("CEC message history:");
664 pw.increaseIndent();
665 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
666 for (MessageHistoryRecord record : mMessageHistory) {
667 record.dump(pw, sdf);
668 }
669 pw.decreaseIndent();
Terry Heo959d2db2014-08-28 16:45:41 +0900670 }
671
Jungshik Jang4085d0e2014-05-27 19:52:39 +0900672 private static native long nativeInit(HdmiCecController handler, MessageQueue messageQueue);
Jungshik Janga9095ba2014-05-02 13:06:22 +0900673 private static native int nativeSendCecCommand(long controllerPtr, int srcAddress,
Jungshik Jange9c77c82014-04-24 20:30:09 +0900674 int dstAddress, byte[] body);
Jungshik Janga9095ba2014-05-02 13:06:22 +0900675 private static native int nativeAddLogicalAddress(long controllerPtr, int logicalAddress);
676 private static native void nativeClearLogicalAddress(long controllerPtr);
677 private static native int nativeGetPhysicalAddress(long controllerPtr);
678 private static native int nativeGetVersion(long controllerPtr);
679 private static native int nativeGetVendorId(long controllerPtr);
Jinsuk Kim0340bbc2014-06-05 11:07:47 +0900680 private static native HdmiPortInfo[] nativeGetPortInfos(long controllerPtr);
Donghyun Chobc6e3722016-11-04 05:25:52 +0900681 private static native void nativeSetOption(long controllerPtr, int flag, boolean enabled);
682 private static native void nativeSetLanguage(long controllerPtr, String language);
683 private static native void nativeEnableAudioReturnChannel(long controllerPtr, int port, boolean flag);
Jungshik Jang092b4452014-06-11 15:19:17 +0900684 private static native boolean nativeIsConnected(long controllerPtr, int port);
Donghyun Cho0b485b22016-12-13 17:21:01 +0900685
686 private final class MessageHistoryRecord {
687 private final long mTime;
688 private final boolean mIsReceived; // true if received message and false if sent message
689 private final HdmiCecMessage mMessage;
690
691 public MessageHistoryRecord(boolean isReceived, HdmiCecMessage message) {
692 mTime = System.currentTimeMillis();
693 mIsReceived = isReceived;
694 mMessage = message;
695 }
696
697 void dump(final IndentingPrintWriter pw, SimpleDateFormat sdf) {
698 pw.print(mIsReceived ? "[R]" : "[S]");
699 pw.print(" time=");
700 pw.print(sdf.format(new Date(mTime)));
701 pw.print(" message=");
702 pw.println(mMessage);
703 }
704 }
Jungshik Jang0792d372014-04-23 17:57:26 +0900705}