HdmiCecController.java revision 42230728b8212738c2351939c5577730f05a58de
1/*
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
19import android.hardware.hdmi.HdmiPortInfo;
20import android.os.Handler;
21import android.os.Looper;
22import android.os.MessageQueue;
23import android.util.Slog;
24import android.util.SparseArray;
25
26import com.android.internal.util.Predicate;
27import com.android.server.hdmi.HdmiAnnotations.IoThreadOnly;
28import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly;
29import com.android.server.hdmi.HdmiControlService.DevicePollingCallback;
30
31import libcore.util.EmptyArray;
32
33import java.util.ArrayList;
34import java.util.List;
35
36/**
37 * Manages HDMI-CEC command and behaviors. It converts user's command into CEC command
38 * and pass it to CEC HAL so that it sends message to other device. For incoming
39 * message it translates the message and delegates it to proper module.
40 *
41 * <p>It should be careful to access member variables on IO thread because
42 * it can be accessed from system thread as well.
43 *
44 * <p>It can be created only by {@link HdmiCecController#create}
45 *
46 * <p>Declared as package-private, accessed by {@link HdmiControlService} only.
47 */
48final class HdmiCecController {
49    private static final String TAG = "HdmiCecController";
50
51    /**
52     * Interface to report allocated logical address.
53     */
54    interface AllocateAddressCallback {
55        /**
56         * Called when a new logical address is allocated.
57         *
58         * @param deviceType requested device type to allocate logical address
59         * @param logicalAddress allocated logical address. If it is
60         *                       {@link Constants#ADDR_UNREGISTERED}, it means that
61         *                       it failed to allocate logical address for the given device type
62         */
63        void onAllocated(int deviceType, int logicalAddress);
64    }
65
66    private static final byte[] EMPTY_BODY = EmptyArray.BYTE;
67
68    // A message to pass cec send command to IO looper.
69    private static final int MSG_SEND_CEC_COMMAND = 1;
70    // A message to delegate logical allocation to IO looper.
71    private static final int MSG_ALLOCATE_LOGICAL_ADDRESS = 2;
72
73    // Message types to handle incoming message in main service looper.
74    private final static int MSG_RECEIVE_CEC_COMMAND = 1;
75    // A message to report allocated logical address to main control looper.
76    private final static int MSG_REPORT_LOGICAL_ADDRESS = 2;
77
78    private static final int NUM_LOGICAL_ADDRESS = 16;
79
80    private static final int RETRY_COUNT_FOR_LOGICAL_ADDRESS_ALLOCATION = 3;
81
82    // Predicate for whether the given logical address is remote device's one or not.
83    private final Predicate<Integer> mRemoteDeviceAddressPredicate = new Predicate<Integer>() {
84        @Override
85        public boolean apply(Integer address) {
86            return !isAllocatedLocalDeviceAddress(address);
87        }
88    };
89
90    // Predicate whether the given logical address is system audio's one or not
91    private final Predicate<Integer> mSystemAudioAddressPredicate = new Predicate<Integer>() {
92        @Override
93        public boolean apply(Integer address) {
94            return HdmiUtils.getTypeFromAddress(address) == Constants.ADDR_AUDIO_SYSTEM;
95        }
96    };
97
98    // Handler instance to process synchronous I/O (mainly send) message.
99    private Handler mIoHandler;
100
101    // Handler instance to process various messages coming from other CEC
102    // device or issued by internal state change.
103    private Handler mControlHandler;
104
105    // Stores the pointer to the native implementation of the service that
106    // interacts with HAL.
107    private volatile long mNativePtr;
108
109    private HdmiControlService mService;
110
111    // Stores the local CEC devices in the system. Device type is used for key.
112    private final SparseArray<HdmiCecLocalDevice> mLocalDevices = new SparseArray<>();
113
114    // Private constructor.  Use HdmiCecController.create().
115    private HdmiCecController() {
116    }
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.
123     * @param service {@link HdmiControlService} instance used to create internal handler
124     *                and to pass callback for incoming message or event.
125     * @return {@link HdmiCecController} if device is initialized successfully. Otherwise,
126     *         returns {@code null}.
127     */
128    static HdmiCecController create(HdmiControlService service) {
129        HdmiCecController controller = new HdmiCecController();
130        long nativePtr = nativeInit(controller, service.getServiceLooper().getQueue());
131        if (nativePtr == 0L) {
132            controller = null;
133            return null;
134        }
135
136        controller.init(service, nativePtr);
137        return controller;
138    }
139
140    private void init(HdmiControlService service, long nativePtr) {
141        mService = service;
142        mIoHandler = new Handler(service.getServiceLooper());
143        mControlHandler = new Handler(service.getServiceLooper());
144        mNativePtr = nativePtr;
145    }
146
147    @ServiceThreadOnly
148    void addLocalDevice(int deviceType, HdmiCecLocalDevice device) {
149        assertRunOnServiceThread();
150        mLocalDevices.put(deviceType, device);
151    }
152
153    /**
154     * Allocate a new logical address of the given device type. Allocated
155     * address will be reported through {@link AllocateAddressCallback}.
156     *
157     * <p> Declared as package-private, accessed by {@link HdmiControlService} only.
158     *
159     * @param deviceType type of device to used to determine logical address
160     * @param preferredAddress a logical address preferred to be allocated.
161     *                         If sets {@link Constants#ADDR_UNREGISTERED}, scans
162     *                         the smallest logical address matched with the given device type.
163     *                         Otherwise, scan address will start from {@code preferredAddress}
164     * @param callback callback interface to report allocated logical address to caller
165     */
166    @ServiceThreadOnly
167    void allocateLogicalAddress(final int deviceType, final int preferredAddress,
168            final AllocateAddressCallback callback) {
169        assertRunOnServiceThread();
170
171        runOnIoThread(new Runnable() {
172            @Override
173            public void run() {
174                handleAllocateLogicalAddress(deviceType, preferredAddress, callback);
175            }
176        });
177    }
178
179    @IoThreadOnly
180    private void handleAllocateLogicalAddress(final int deviceType, int preferredAddress,
181            final AllocateAddressCallback callback) {
182        assertRunOnIoThread();
183        int startAddress = preferredAddress;
184        // If preferred address is "unregistered", start address will be the smallest
185        // address matched with the given device type.
186        if (preferredAddress == Constants.ADDR_UNREGISTERED) {
187            for (int i = 0; i < NUM_LOGICAL_ADDRESS; ++i) {
188                if (deviceType == HdmiUtils.getTypeFromAddress(i)) {
189                    startAddress = i;
190                    break;
191                }
192            }
193        }
194
195        int logicalAddress = Constants.ADDR_UNREGISTERED;
196        // Iterates all possible addresses which has the same device type.
197        for (int i = 0; i < NUM_LOGICAL_ADDRESS; ++i) {
198            int curAddress = (startAddress + i) % NUM_LOGICAL_ADDRESS;
199            if (curAddress != Constants.ADDR_UNREGISTERED
200                    && deviceType == HdmiUtils.getTypeFromAddress(curAddress)) {
201                if (!sendPollMessage(curAddress, curAddress,
202                        RETRY_COUNT_FOR_LOGICAL_ADDRESS_ALLOCATION)) {
203                    logicalAddress = curAddress;
204                    break;
205                }
206            }
207        }
208
209        final int assignedAddress = logicalAddress;
210        if (callback != null) {
211            runOnServiceThread(new Runnable() {
212                    @Override
213                public void run() {
214                    callback.onAllocated(deviceType, assignedAddress);
215                }
216            });
217        }
218    }
219
220    private static byte[] buildBody(int opcode, byte[] params) {
221        byte[] body = new byte[params.length + 1];
222        body[0] = (byte) opcode;
223        System.arraycopy(params, 0, body, 1, params.length);
224        return body;
225    }
226
227
228    HdmiPortInfo[] getPortInfos() {
229        return nativeGetPortInfos(mNativePtr);
230    }
231
232    /**
233     * Return the locally hosted logical device of a given type.
234     *
235     * @param deviceType logical device type
236     * @return {@link HdmiCecLocalDevice} instance if the instance of the type is available;
237     *          otherwise null.
238     */
239    HdmiCecLocalDevice getLocalDevice(int deviceType) {
240        return mLocalDevices.get(deviceType);
241    }
242
243    /**
244     * Add a new logical address to the device. Device's HW should be notified
245     * when a new logical address is assigned to a device, so that it can accept
246     * a command having available destinations.
247     *
248     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
249     *
250     * @param newLogicalAddress a logical address to be added
251     * @return 0 on success. Otherwise, returns negative value
252     */
253    @ServiceThreadOnly
254    int addLogicalAddress(int newLogicalAddress) {
255        assertRunOnServiceThread();
256        if (HdmiUtils.isValidAddress(newLogicalAddress)) {
257            return nativeAddLogicalAddress(mNativePtr, newLogicalAddress);
258        } else {
259            return -1;
260        }
261    }
262
263    /**
264     * Clear all logical addresses registered in the device.
265     *
266     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
267     */
268    @ServiceThreadOnly
269    void clearLogicalAddress() {
270        assertRunOnServiceThread();
271        // TODO: consider to backup logical address so that new logical address
272        // allocation can use it as preferred address.
273        for (int i = 0; i < mLocalDevices.size(); ++i) {
274            mLocalDevices.valueAt(i).clearAddress();
275        }
276        nativeClearLogicalAddress(mNativePtr);
277    }
278
279    /**
280     * Return the physical address of the device.
281     *
282     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
283     *
284     * @return CEC physical address of the device. The range of success address
285     *         is between 0x0000 and 0xFFFF. If failed it returns -1
286     */
287    @ServiceThreadOnly
288    int getPhysicalAddress() {
289        assertRunOnServiceThread();
290        return nativeGetPhysicalAddress(mNativePtr);
291    }
292
293    /**
294     * Return CEC version of the device.
295     *
296     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
297     */
298    @ServiceThreadOnly
299    int getVersion() {
300        assertRunOnServiceThread();
301        return nativeGetVersion(mNativePtr);
302    }
303
304    /**
305     * Return vendor id of the device.
306     *
307     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
308     */
309    @ServiceThreadOnly
310    int getVendorId() {
311        assertRunOnServiceThread();
312        return nativeGetVendorId(mNativePtr);
313    }
314
315    /**
316     * Set an option to CEC HAL.
317     *
318     * @param flag key of option
319     * @param value value of option
320     */
321    @ServiceThreadOnly
322    void setOption(int flag, int value) {
323        assertRunOnServiceThread();
324        nativeSetOption(mNativePtr, flag, value);
325    }
326
327    /**
328     * Configure ARC circuit in the hardware logic to start or stop the feature.
329     *
330     * @param enabled whether to enable/disable ARC
331     */
332    @ServiceThreadOnly
333    void setAudioReturnChannel(boolean enabled) {
334        assertRunOnServiceThread();
335        nativeSetAudioReturnChannel(mNativePtr, enabled);
336    }
337
338    /**
339     * Return the connection status of the specified port
340     *
341     * @param port port number to check connection status
342     * @return true if connected; otherwise, return false
343     */
344    @ServiceThreadOnly
345    boolean isConnected(int port) {
346        assertRunOnServiceThread();
347        return nativeIsConnected(mNativePtr, port);
348    }
349
350    /**
351     * Poll all remote devices. It sends &lt;Polling Message&gt; to all remote
352     * devices.
353     *
354     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
355     *
356     * @param callback an interface used to get a list of all remote devices' address
357     * @param sourceAddress a logical address of source device where sends polling message
358     * @param pickStrategy strategy how to pick polling candidates
359     * @param retryCount the number of retry used to send polling message to remote devices
360     */
361    @ServiceThreadOnly
362    void pollDevices(DevicePollingCallback callback, int sourceAddress, int pickStrategy,
363            int retryCount) {
364        assertRunOnServiceThread();
365
366        // Extract polling candidates. No need to poll against local devices.
367        List<Integer> pollingCandidates = pickPollCandidates(pickStrategy);
368        runDevicePolling(sourceAddress, pollingCandidates, retryCount, callback);
369    }
370
371    /**
372     * Return a list of all {@link HdmiCecLocalDevice}s.
373     *
374     * <p>Declared as package-private. accessed by {@link HdmiControlService} only.
375     */
376    @ServiceThreadOnly
377    List<HdmiCecLocalDevice> getLocalDeviceList() {
378        assertRunOnServiceThread();
379        return HdmiUtils.sparseArrayToList(mLocalDevices);
380    }
381
382    private List<Integer> pickPollCandidates(int pickStrategy) {
383        int strategy = pickStrategy & Constants.POLL_STRATEGY_MASK;
384        Predicate<Integer> pickPredicate = null;
385        switch (strategy) {
386            case Constants.POLL_STRATEGY_SYSTEM_AUDIO:
387                pickPredicate = mSystemAudioAddressPredicate;
388                break;
389            case Constants.POLL_STRATEGY_REMOTES_DEVICES:
390            default:  // The default is POLL_STRATEGY_REMOTES_DEVICES.
391                pickPredicate = mRemoteDeviceAddressPredicate;
392                break;
393        }
394
395        int iterationStrategy = pickStrategy & Constants.POLL_ITERATION_STRATEGY_MASK;
396        ArrayList<Integer> pollingCandidates = new ArrayList<>();
397        switch (iterationStrategy) {
398            case Constants.POLL_ITERATION_IN_ORDER:
399                for (int i = Constants.ADDR_TV; i <= Constants.ADDR_SPECIFIC_USE; ++i) {
400                    if (pickPredicate.apply(i)) {
401                        pollingCandidates.add(i);
402                    }
403                }
404                break;
405            case Constants.POLL_ITERATION_REVERSE_ORDER:
406            default:  // The default is reverse order.
407                for (int i = Constants.ADDR_SPECIFIC_USE; i >= Constants.ADDR_TV; --i) {
408                    if (pickPredicate.apply(i)) {
409                        pollingCandidates.add(i);
410                    }
411                }
412                break;
413        }
414        return pollingCandidates;
415    }
416
417    @ServiceThreadOnly
418    private boolean isAllocatedLocalDeviceAddress(int address) {
419        assertRunOnServiceThread();
420        for (int i = 0; i < mLocalDevices.size(); ++i) {
421            if (mLocalDevices.valueAt(i).isAddressOf(address)) {
422                return true;
423            }
424        }
425        return false;
426    }
427
428    @ServiceThreadOnly
429    private void runDevicePolling(final int sourceAddress,
430            final List<Integer> candidates, final int retryCount,
431            final DevicePollingCallback callback) {
432        assertRunOnServiceThread();
433        runOnIoThread(new Runnable() {
434            @Override
435            public void run() {
436                final ArrayList<Integer> allocated = new ArrayList<>();
437                for (Integer address : candidates) {
438                    if (sendPollMessage(sourceAddress, address, retryCount)) {
439                        allocated.add(address);
440                    }
441                }
442                if (callback != null) {
443                    runOnServiceThread(new Runnable() {
444                        @Override
445                        public void run() {
446                            callback.onPollingFinished(allocated);
447                        }
448                    });
449                }
450            }
451        });
452    }
453
454    @IoThreadOnly
455    private boolean sendPollMessage(int sourceAddress, int destinationAddress, int retryCount) {
456        assertRunOnIoThread();
457        for (int i = 0; i < retryCount; ++i) {
458            // <Polling Message> is a message which has empty body.
459            // If sending <Polling Message> failed (NAK), it becomes
460            // new logical address for the device because no device uses
461            // it as logical address of the device.
462            if (nativeSendCecCommand(mNativePtr, sourceAddress, destinationAddress, EMPTY_BODY)
463                    == Constants.SEND_RESULT_SUCCESS) {
464                return true;
465            }
466        }
467        return false;
468    }
469
470    private void assertRunOnIoThread() {
471        if (Looper.myLooper() != mIoHandler.getLooper()) {
472            throw new IllegalStateException("Should run on io thread.");
473        }
474    }
475
476    private void assertRunOnServiceThread() {
477        if (Looper.myLooper() != mControlHandler.getLooper()) {
478            throw new IllegalStateException("Should run on service thread.");
479        }
480    }
481
482    // Run a Runnable on IO thread.
483    // It should be careful to access member variables on IO thread because
484    // it can be accessed from system thread as well.
485    private void runOnIoThread(Runnable runnable) {
486        mIoHandler.post(runnable);
487    }
488
489    private void runOnServiceThread(Runnable runnable) {
490        mControlHandler.post(runnable);
491    }
492
493    private boolean isAcceptableAddress(int address) {
494        // Can access command targeting devices available in local device or broadcast command.
495        if (address == Constants.ADDR_BROADCAST) {
496            return true;
497        }
498        return isAllocatedLocalDeviceAddress(address);
499    }
500
501    @ServiceThreadOnly
502    private void onReceiveCommand(HdmiCecMessage message) {
503        assertRunOnServiceThread();
504        if (isAcceptableAddress(message.getDestination())
505                && mService.handleCecCommand(message)) {
506            return;
507        }
508
509        if (message.getDestination() != Constants.ADDR_BROADCAST) {
510            int sourceAddress = message.getDestination();
511            // Reply <Feature Abort> to initiator (source) for all requests.
512            HdmiCecMessage cecMessage = HdmiCecMessageBuilder.buildFeatureAbortCommand(
513                    sourceAddress, message.getSource(), message.getOpcode(),
514                    Constants.ABORT_REFUSED);
515            sendCommand(cecMessage);
516        }
517    }
518
519    @ServiceThreadOnly
520    void sendCommand(HdmiCecMessage cecMessage) {
521        assertRunOnServiceThread();
522        sendCommand(cecMessage, null);
523    }
524
525    @ServiceThreadOnly
526    void sendCommand(final HdmiCecMessage cecMessage,
527            final HdmiControlService.SendMessageCallback callback) {
528        assertRunOnServiceThread();
529        runOnIoThread(new Runnable() {
530            @Override
531            public void run() {
532                byte[] body = buildBody(cecMessage.getOpcode(), cecMessage.getParams());
533                final int error = nativeSendCecCommand(mNativePtr, cecMessage.getSource(),
534                        cecMessage.getDestination(), body);
535                if (error != Constants.SEND_RESULT_SUCCESS) {
536                    Slog.w(TAG, "Failed to send " + cecMessage);
537                }
538                if (callback != null) {
539                    runOnServiceThread(new Runnable() {
540                        @Override
541                        public void run() {
542                            callback.onSendCompleted(error);
543                        }
544                    });
545                }
546            }
547        });
548    }
549
550    /**
551     * Called by native when incoming CEC message arrived.
552     */
553    @ServiceThreadOnly
554    private void handleIncomingCecCommand(int srcAddress, int dstAddress, byte[] body) {
555        assertRunOnServiceThread();
556        onReceiveCommand(HdmiCecMessageBuilder.of(srcAddress, dstAddress, body));
557    }
558
559    /**
560     * Called by native when a hotplug event issues.
561     */
562    @ServiceThreadOnly
563    private void handleHotplug(int port, boolean connected) {
564        assertRunOnServiceThread();
565        mService.onHotplug(port, connected);
566    }
567
568    private static native long nativeInit(HdmiCecController handler, MessageQueue messageQueue);
569    private static native int nativeSendCecCommand(long controllerPtr, int srcAddress,
570            int dstAddress, byte[] body);
571    private static native int nativeAddLogicalAddress(long controllerPtr, int logicalAddress);
572    private static native void nativeClearLogicalAddress(long controllerPtr);
573    private static native int nativeGetPhysicalAddress(long controllerPtr);
574    private static native int nativeGetVersion(long controllerPtr);
575    private static native int nativeGetVendorId(long controllerPtr);
576    private static native HdmiPortInfo[] nativeGetPortInfos(long controllerPtr);
577    private static native void nativeSetOption(long controllerPtr, int flag, int value);
578    private static native void nativeSetAudioReturnChannel(long controllerPtr, boolean flag);
579    private static native boolean nativeIsConnected(long controllerPtr, int port);
580}
581