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