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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
|
/*
* Copyright (C) 2014 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 com.android.server.hdmi;
import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_CEC_DISABLE;
import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION;
import static android.hardware.hdmi.HdmiControlManager.CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE;
import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_CEC_DISABLED;
import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION;
import static android.hardware.hdmi.HdmiControlManager.ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN;
import static android.hardware.hdmi.HdmiControlManager.OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT;
import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED;
import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION;
import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE;
import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_ANALOGUE;
import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_DIGITAL;
import static android.hardware.hdmi.HdmiControlManager.TIMER_RECORDING_TYPE_EXTERNAL;
import android.hardware.hdmi.HdmiControlManager;
import android.hardware.hdmi.HdmiDeviceInfo;
import android.hardware.hdmi.HdmiRecordSources;
import android.hardware.hdmi.HdmiTimerRecordSources;
import android.hardware.hdmi.IHdmiControlCallback;
import android.media.AudioManager;
import android.media.AudioSystem;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.provider.Settings.Global;
import android.util.ArraySet;
import android.util.Slog;
import android.util.SparseArray;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.IndentingPrintWriter;
import com.android.server.hdmi.DeviceDiscoveryAction.DeviceDiscoveryCallback;
import com.android.server.hdmi.HdmiAnnotations.ServiceThreadOnly;
import com.android.server.hdmi.HdmiControlService.SendMessageCallback;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Represent a logical device of type TV residing in Android system.
*/
final class HdmiCecLocalDeviceTv extends HdmiCecLocalDevice {
private static final String TAG = "HdmiCecLocalDeviceTv";
// Whether ARC is available or not. "true" means that ARC is established between TV and
// AVR as audio receiver.
@ServiceThreadOnly
private boolean mArcEstablished = false;
// Whether ARC feature is enabled or not. The default value is true.
// TODO: once adding system setting for it, read the value to it.
private boolean mArcFeatureEnabled = true;
// Whether System audio mode is activated or not.
// This becomes true only when all system audio sequences are finished.
@GuardedBy("mLock")
private boolean mSystemAudioActivated = false;
// The previous port id (input) before switching to the new one. This is remembered in order to
// be able to switch to it upon receiving <Inactive Source> from currently active source.
// This remains valid only when the active source was switched via one touch play operation
// (either by TV or source device). Manual port switching invalidates this value to
// Constants.PORT_INVALID, for which case <Inactive Source> does not do anything.
@GuardedBy("mLock")
private int mPrevPortId;
@GuardedBy("mLock")
private int mSystemAudioVolume = Constants.UNKNOWN_VOLUME;
@GuardedBy("mLock")
private boolean mSystemAudioMute = false;
// Copy of mDeviceInfos to guarantee thread-safety.
@GuardedBy("mLock")
private List<HdmiDeviceInfo> mSafeAllDeviceInfos = Collections.emptyList();
// All external cec input(source) devices. Does not include system audio device.
@GuardedBy("mLock")
private List<HdmiDeviceInfo> mSafeExternalInputs = Collections.emptyList();
// Map-like container of all cec devices including local ones.
// device id is used as key of container.
// This is not thread-safe. For external purpose use mSafeDeviceInfos.
private final SparseArray<HdmiDeviceInfo> mDeviceInfos = new SparseArray<>();
// If true, TV going to standby mode puts other devices also to standby.
private boolean mAutoDeviceOff;
// If true, TV wakes itself up when receiving <Text/Image View On>.
private boolean mAutoWakeup;
private final HdmiCecStandbyModeHandler mStandbyHandler;
// If true, do not do routing control/send active source for internal source.
// Set to true when the device was woken up by <Text/Image View On>.
private boolean mSkipRoutingControl;
// Set of physical addresses of CEC switches on the CEC bus. Managed independently from
// other CEC devices since they might not have logical address.
private final ArraySet<Integer> mCecSwitches = new ArraySet<Integer>();
HdmiCecLocalDeviceTv(HdmiControlService service) {
super(service, HdmiDeviceInfo.DEVICE_TV);
mPrevPortId = Constants.INVALID_PORT_ID;
mAutoDeviceOff = mService.readBooleanSetting(Global.HDMI_CONTROL_AUTO_DEVICE_OFF_ENABLED,
true);
mAutoWakeup = mService.readBooleanSetting(Global.HDMI_CONTROL_AUTO_WAKEUP_ENABLED, true);
mStandbyHandler = new HdmiCecStandbyModeHandler(service, this);
}
@Override
@ServiceThreadOnly
protected void onAddressAllocated(int logicalAddress, int reason) {
assertRunOnServiceThread();
mService.sendCecCommand(HdmiCecMessageBuilder.buildReportPhysicalAddressCommand(
mAddress, mService.getPhysicalAddress(), mDeviceType));
mService.sendCecCommand(HdmiCecMessageBuilder.buildDeviceVendorIdCommand(
mAddress, mService.getVendorId()));
mCecSwitches.add(mService.getPhysicalAddress()); // TV is a CEC switch too.
mSkipRoutingControl = (reason == HdmiControlService.INITIATED_BY_WAKE_UP_MESSAGE);
launchRoutingControl(reason != HdmiControlService.INITIATED_BY_ENABLE_CEC &&
reason != HdmiControlService.INITIATED_BY_BOOT_UP);
launchDeviceDiscovery();
}
@Override
@ServiceThreadOnly
protected int getPreferredAddress() {
assertRunOnServiceThread();
return SystemProperties.getInt(Constants.PROPERTY_PREFERRED_ADDRESS_TV,
Constants.ADDR_UNREGISTERED);
}
@Override
@ServiceThreadOnly
protected void setPreferredAddress(int addr) {
assertRunOnServiceThread();
SystemProperties.set(Constants.PROPERTY_PREFERRED_ADDRESS_TV, String.valueOf(addr));
}
@Override
@ServiceThreadOnly
boolean dispatchMessage(HdmiCecMessage message) {
assertRunOnServiceThread();
if (mService.isPowerStandby() && mStandbyHandler.handleCommand(message)) {
return true;
}
return super.onMessage(message);
}
/**
* Performs the action 'device select', or 'one touch play' initiated by TV.
*
* @param id id of HDMI device to select
* @param callback callback object to report the result with
*/
@ServiceThreadOnly
void deviceSelect(int id, IHdmiControlCallback callback) {
assertRunOnServiceThread();
HdmiDeviceInfo targetDevice = mDeviceInfos.get(id);
if (targetDevice == null) {
invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE);
return;
}
int targetAddress = targetDevice.getLogicalAddress();
ActiveSource active = getActiveSource();
if (active.isValid() && targetAddress == active.logicalAddress) {
invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
return;
}
if (targetAddress == Constants.ADDR_INTERNAL) {
handleSelectInternalSource();
// Switching to internal source is always successful even when CEC control is disabled.
setActiveSource(targetAddress, mService.getPhysicalAddress());
setActivePath(mService.getPhysicalAddress());
invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
return;
}
if (!mService.isControlEnabled()) {
setActiveSource(targetDevice);
invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
return;
}
removeAction(DeviceSelectAction.class);
addAndStartAction(new DeviceSelectAction(this, targetDevice, callback));
}
@ServiceThreadOnly
private void handleSelectInternalSource() {
assertRunOnServiceThread();
// Seq #18
if (mService.isControlEnabled() && mActiveSource.logicalAddress != mAddress) {
updateActiveSource(mAddress, mService.getPhysicalAddress());
if (mSkipRoutingControl) {
mSkipRoutingControl = false;
return;
}
HdmiCecMessage activeSource = HdmiCecMessageBuilder.buildActiveSource(
mAddress, mService.getPhysicalAddress());
mService.sendCecCommand(activeSource);
}
}
@ServiceThreadOnly
void updateActiveSource(int logicalAddress, int physicalAddress) {
assertRunOnServiceThread();
updateActiveSource(ActiveSource.of(logicalAddress, physicalAddress));
}
@ServiceThreadOnly
void updateActiveSource(ActiveSource newActive) {
assertRunOnServiceThread();
// Seq #14
if (mActiveSource.equals(newActive)) {
return;
}
setActiveSource(newActive);
int logicalAddress = newActive.logicalAddress;
if (getCecDeviceInfo(logicalAddress) != null && logicalAddress != mAddress) {
if (mService.pathToPortId(newActive.physicalAddress) == getActivePortId()) {
setPrevPortId(getActivePortId());
}
// TODO: Show the OSD banner related to the new active source device.
} else {
// TODO: If displayed, remove the OSD banner related to the previous
// active source device.
}
}
int getPortId(int physicalAddress) {
return mService.pathToPortId(physicalAddress);
}
/**
* Returns the previous port id kept to handle input switching on <Inactive Source>.
*/
int getPrevPortId() {
synchronized (mLock) {
return mPrevPortId;
}
}
/**
* Sets the previous port id. INVALID_PORT_ID invalidates it, hence no actions will be
* taken for <Inactive Source>.
*/
void setPrevPortId(int portId) {
synchronized (mLock) {
mPrevPortId = portId;
}
}
@ServiceThreadOnly
void updateActiveInput(int path, boolean notifyInputChange) {
assertRunOnServiceThread();
// Seq #15
if (path == getActivePath()) {
return;
}
setPrevPortId(getActivePortId());
setActivePath(path);
// TODO: Handle PAP/PIP case.
// Show OSD port change banner
if (notifyInputChange) {
ActiveSource activeSource = getActiveSource();
HdmiDeviceInfo info = getCecDeviceInfo(activeSource.logicalAddress);
if (info == null) {
info = new HdmiDeviceInfo(Constants.ADDR_INVALID, path, getActivePortId(),
HdmiDeviceInfo.DEVICE_RESERVED, 0, null);
}
mService.invokeInputChangeListener(info);
}
}
@ServiceThreadOnly
void doManualPortSwitching(int portId, IHdmiControlCallback callback) {
assertRunOnServiceThread();
// Seq #20
if (!mService.isValidPortId(portId)) {
invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
return;
}
if (portId == getActivePortId()) {
invokeCallback(callback, HdmiControlManager.RESULT_SUCCESS);
return;
}
mActiveSource.invalidate();
if (!mService.isControlEnabled()) {
setActivePortId(portId);
invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
return;
}
int oldPath = getActivePortId() != Constants.INVALID_PORT_ID
? mService.portIdToPath(getActivePortId()) : getDeviceInfo().getPhysicalAddress();
setActivePath(oldPath);
if (mSkipRoutingControl) {
mSkipRoutingControl = false;
return;
}
int newPath = mService.portIdToPath(portId);
HdmiCecMessage routingChange =
HdmiCecMessageBuilder.buildRoutingChange(mAddress, oldPath, newPath);
mService.sendCecCommand(routingChange);
removeAction(RoutingControlAction.class);
addAndStartAction(new RoutingControlAction(this, newPath, true, callback));
}
@ServiceThreadOnly
int getPowerStatus() {
assertRunOnServiceThread();
return mService.getPowerStatus();
}
/**
* Sends key to a target CEC device.
*
* @param keyCode key code to send. Defined in {@link android.view.KeyEvent}.
* @param isPressed true if this is key press event
*/
@Override
@ServiceThreadOnly
protected void sendKeyEvent(int keyCode, boolean isPressed) {
assertRunOnServiceThread();
if (!HdmiCecKeycode.isSupportedKeycode(keyCode)) {
Slog.w(TAG, "Unsupported key: " + keyCode);
return;
}
List<SendKeyAction> action = getActions(SendKeyAction.class);
if (!action.isEmpty()) {
action.get(0).processKeyEvent(keyCode, isPressed);
} else {
if (isPressed && getActiveSource().isValid()) {
int logicalAddress = getActiveSource().logicalAddress;
addAndStartAction(new SendKeyAction(this, logicalAddress, keyCode));
} else {
Slog.w(TAG, "Discard key event: " + keyCode + " pressed:" + isPressed);
}
}
}
private static void invokeCallback(IHdmiControlCallback callback, int result) {
if (callback == null) {
return;
}
try {
callback.onComplete(result);
} catch (RemoteException e) {
Slog.e(TAG, "Invoking callback failed:" + e);
}
}
@Override
@ServiceThreadOnly
protected boolean handleActiveSource(HdmiCecMessage message) {
assertRunOnServiceThread();
int logicalAddress = message.getSource();
int physicalAddress = HdmiUtils.twoBytesToInt(message.getParams());
if (getCecDeviceInfo(logicalAddress) == null) {
handleNewDeviceAtTheTailOfActivePath(physicalAddress);
} else {
ActiveSource activeSource = ActiveSource.of(logicalAddress, physicalAddress);
ActiveSourceHandler.create(this, null).process(activeSource);
}
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleInactiveSource(HdmiCecMessage message) {
assertRunOnServiceThread();
// Seq #10
// Ignore <Inactive Source> from non-active source device.
if (getActiveSource().logicalAddress != message.getSource()) {
return true;
}
if (isProhibitMode()) {
return true;
}
int portId = getPrevPortId();
if (portId != Constants.INVALID_PORT_ID) {
// TODO: Do this only if TV is not showing multiview like PIP/PAP.
HdmiDeviceInfo inactiveSource = getCecDeviceInfo(message.getSource());
if (inactiveSource == null) {
return true;
}
if (mService.pathToPortId(inactiveSource.getPhysicalAddress()) == portId) {
return true;
}
// TODO: Switch the TV freeze mode off
doManualPortSwitching(portId, null);
setPrevPortId(Constants.INVALID_PORT_ID);
}
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleRequestActiveSource(HdmiCecMessage message) {
assertRunOnServiceThread();
// Seq #19
if (mAddress == getActiveSource().logicalAddress) {
mService.sendCecCommand(
HdmiCecMessageBuilder.buildActiveSource(mAddress, getActivePath()));
}
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleGetMenuLanguage(HdmiCecMessage message) {
assertRunOnServiceThread();
if (!broadcastMenuLanguage(mService.getLanguage())) {
Slog.w(TAG, "Failed to respond to <Get Menu Language>: " + message.toString());
}
return true;
}
@ServiceThreadOnly
boolean broadcastMenuLanguage(String language) {
assertRunOnServiceThread();
HdmiCecMessage command = HdmiCecMessageBuilder.buildSetMenuLanguageCommand(
mAddress, language);
if (command != null) {
mService.sendCecCommand(command);
return true;
}
return false;
}
@Override
@ServiceThreadOnly
protected boolean handleReportPhysicalAddress(HdmiCecMessage message) {
assertRunOnServiceThread();
int path = HdmiUtils.twoBytesToInt(message.getParams());
int address = message.getSource();
int type = message.getParams()[2];
if (updateCecSwitchInfo(address, type, path)) return true;
// Ignore if [Device Discovery Action] is going on.
if (hasAction(DeviceDiscoveryAction.class)) {
Slog.i(TAG, "Ignored while Device Discovery Action is in progress: " + message);
return true;
}
if (!isInDeviceList(address, path)) {
handleNewDeviceAtTheTailOfActivePath(path);
}
startNewDeviceAction(ActiveSource.of(address, path));
return true;
}
@Override
protected boolean handleReportPowerStatus(HdmiCecMessage command) {
int newStatus = command.getParams()[0] & 0xFF;
updateDevicePowerStatus(command.getSource(), newStatus);
return true;
}
@Override
protected boolean handleTimerStatus(HdmiCecMessage message) {
// Do nothing.
return true;
}
@Override
protected boolean handleRecordStatus(HdmiCecMessage message) {
// Do nothing.
return true;
}
boolean updateCecSwitchInfo(int address, int type, int path) {
if (address == Constants.ADDR_UNREGISTERED
&& type == HdmiDeviceInfo.DEVICE_PURE_CEC_SWITCH) {
mCecSwitches.add(path);
updateSafeDeviceInfoList();
return true; // Pure switch does not need further processing. Return here.
}
if (type == HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM) {
mCecSwitches.add(path);
}
return false;
}
void startNewDeviceAction(ActiveSource activeSource) {
for (NewDeviceAction action : getActions(NewDeviceAction.class)) {
// If there is new device action which has the same logical address and path
// ignore new request.
// NewDeviceAction is created whenever it receives <Report Physical Address>.
// And there is a chance starting NewDeviceAction for the same source.
// Usually, new device sends <Report Physical Address> when it's plugged
// in. However, TV can detect a new device from HotPlugDetectionAction,
// which sends <Give Physical Address> to the source for newly detected
// device.
if (action.isActionOf(activeSource)) {
return;
}
}
addAndStartAction(new NewDeviceAction(this, activeSource.logicalAddress,
activeSource.physicalAddress));
}
private void handleNewDeviceAtTheTailOfActivePath(int path) {
// Seq #22
if (isTailOfActivePath(path, getActivePath())) {
removeAction(RoutingControlAction.class);
int newPath = mService.portIdToPath(getActivePortId());
setActivePath(newPath);
mService.sendCecCommand(HdmiCecMessageBuilder.buildRoutingChange(
mAddress, getActivePath(), newPath));
addAndStartAction(new RoutingControlAction(this, newPath, false, null));
}
}
/**
* Whether the given path is located in the tail of current active path.
*
* @param path to be tested
* @param activePath current active path
* @return true if the given path is located in the tail of current active path; otherwise,
* false
*/
static boolean isTailOfActivePath(int path, int activePath) {
// If active routing path is internal source, return false.
if (activePath == 0) {
return false;
}
for (int i = 12; i >= 0; i -= 4) {
int curActivePath = (activePath >> i) & 0xF;
if (curActivePath == 0) {
return true;
} else {
int curPath = (path >> i) & 0xF;
if (curPath != curActivePath) {
return false;
}
}
}
return false;
}
@Override
@ServiceThreadOnly
protected boolean handleRoutingChange(HdmiCecMessage message) {
assertRunOnServiceThread();
// Seq #21
byte[] params = message.getParams();
int currentPath = HdmiUtils.twoBytesToInt(params);
if (HdmiUtils.isAffectingActiveRoutingPath(getActivePath(), currentPath)) {
mActiveSource.invalidate();
removeAction(RoutingControlAction.class);
int newPath = HdmiUtils.twoBytesToInt(params, 2);
addAndStartAction(new RoutingControlAction(this, newPath, true, null));
}
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleReportAudioStatus(HdmiCecMessage message) {
assertRunOnServiceThread();
byte params[] = message.getParams();
int mute = params[0] & 0x80;
int volume = params[0] & 0x7F;
setAudioStatus(mute == 0x80, volume);
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleTextViewOn(HdmiCecMessage message) {
assertRunOnServiceThread();
if (mService.isPowerStandbyOrTransient() && mAutoWakeup) {
mService.wakeUp();
}
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleImageViewOn(HdmiCecMessage message) {
assertRunOnServiceThread();
// Currently, it's the same as <Text View On>.
return handleTextViewOn(message);
}
@Override
@ServiceThreadOnly
protected boolean handleSetOsdName(HdmiCecMessage message) {
int source = message.getSource();
HdmiDeviceInfo deviceInfo = getCecDeviceInfo(source);
// If the device is not in device list, ignore it.
if (deviceInfo == null) {
Slog.e(TAG, "No source device info for <Set Osd Name>." + message);
return true;
}
String osdName = null;
try {
osdName = new String(message.getParams(), "US-ASCII");
} catch (UnsupportedEncodingException e) {
Slog.e(TAG, "Invalid <Set Osd Name> request:" + message, e);
return true;
}
if (deviceInfo.getDisplayName().equals(osdName)) {
Slog.i(TAG, "Ignore incoming <Set Osd Name> having same osd name:" + message);
return true;
}
addCecDevice(new HdmiDeviceInfo(deviceInfo.getLogicalAddress(),
deviceInfo.getPhysicalAddress(), deviceInfo.getPortId(),
deviceInfo.getDeviceType(), deviceInfo.getVendorId(), osdName));
return true;
}
@ServiceThreadOnly
private void launchDeviceDiscovery() {
assertRunOnServiceThread();
clearDeviceInfoList();
DeviceDiscoveryAction action = new DeviceDiscoveryAction(this,
new DeviceDiscoveryCallback() {
@Override
public void onDeviceDiscoveryDone(List<HdmiDeviceInfo> deviceInfos) {
for (HdmiDeviceInfo info : deviceInfos) {
addCecDevice(info);
}
// Since we removed all devices when it's start and
// device discovery action does not poll local devices,
// we should put device info of local device manually here
for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) {
addCecDevice(device.getDeviceInfo());
}
addAndStartAction(new HotplugDetectionAction(HdmiCecLocalDeviceTv.this));
addAndStartAction(new PowerStatusMonitorAction(HdmiCecLocalDeviceTv.this));
// If there is AVR, initiate System Audio Auto initiation action,
// which turns on and off system audio according to last system
// audio setting.
HdmiDeviceInfo avr = getAvrDeviceInfo();
if (avr != null) {
onNewAvrAdded(avr);
}
}
});
addAndStartAction(action);
}
@ServiceThreadOnly
void onNewAvrAdded(HdmiDeviceInfo avr) {
assertRunOnServiceThread();
if (getSystemAudioModeSetting()) {
addAndStartAction(new SystemAudioAutoInitiationAction(this, avr.getLogicalAddress()));
}
if (isArcFeatureEnabled()) {
startArcAction(true);
}
}
// Clear all device info.
@ServiceThreadOnly
private void clearDeviceInfoList() {
assertRunOnServiceThread();
for (HdmiDeviceInfo info : mSafeExternalInputs) {
invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
}
mDeviceInfos.clear();
updateSafeDeviceInfoList();
}
@ServiceThreadOnly
// Seq #32
void changeSystemAudioMode(boolean enabled, IHdmiControlCallback callback) {
assertRunOnServiceThread();
if (!mService.isControlEnabled() || hasAction(DeviceDiscoveryAction.class)) {
setSystemAudioMode(false, true);
invokeCallback(callback, HdmiControlManager.RESULT_INCORRECT_MODE);
return;
}
HdmiDeviceInfo avr = getAvrDeviceInfo();
if (avr == null) {
setSystemAudioMode(false, true);
invokeCallback(callback, HdmiControlManager.RESULT_TARGET_NOT_AVAILABLE);
return;
}
addAndStartAction(
new SystemAudioActionFromTv(this, avr.getLogicalAddress(), enabled, callback));
}
// # Seq 25
void setSystemAudioMode(boolean on, boolean updateSetting) {
HdmiLogger.debug("System Audio Mode change[old:%b new:%b]", mSystemAudioActivated, on);
if (updateSetting) {
mService.writeBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, on);
}
updateAudioManagerForSystemAudio(on);
synchronized (mLock) {
if (mSystemAudioActivated != on) {
mSystemAudioActivated = on;
mService.announceSystemAudioModeChange(on);
}
}
}
private void updateAudioManagerForSystemAudio(boolean on) {
mService.getAudioManager().setHdmiSystemAudioSupported(on);
}
boolean isSystemAudioActivated() {
if (getAvrDeviceInfo() == null) {
return false;
}
synchronized (mLock) {
return mSystemAudioActivated;
}
}
boolean getSystemAudioModeSetting() {
return mService.readBooleanSetting(Global.HDMI_SYSTEM_AUDIO_ENABLED, false);
}
/**
* Change ARC status into the given {@code enabled} status.
*
* @return {@code true} if ARC was in "Enabled" status
*/
@ServiceThreadOnly
boolean setArcStatus(boolean enabled) {
assertRunOnServiceThread();
boolean oldStatus = mArcEstablished;
// 1. Enable/disable ARC circuit.
mService.setAudioReturnChannel(enabled);
// 2. Notify arc status to audio service.
notifyArcStatusToAudioService(enabled);
// 3. Update arc status;
mArcEstablished = enabled;
return oldStatus;
}
private void notifyArcStatusToAudioService(boolean enabled) {
// Note that we don't set any name to ARC.
mService.getAudioManager().setWiredDeviceConnectionState(
AudioSystem.DEVICE_OUT_HDMI_ARC,
enabled ? 1 : 0, "");
}
/**
* Returns whether ARC is enabled or not.
*/
@ServiceThreadOnly
boolean isArcEstabilished() {
assertRunOnServiceThread();
return mArcFeatureEnabled && mArcEstablished;
}
@ServiceThreadOnly
void changeArcFeatureEnabled(boolean enabled) {
assertRunOnServiceThread();
if (mArcFeatureEnabled != enabled) {
mArcFeatureEnabled = enabled;
if (enabled) {
if (!mArcEstablished) {
startArcAction(true);
}
} else {
if (mArcEstablished) {
startArcAction(false);
}
}
}
}
@ServiceThreadOnly
boolean isArcFeatureEnabled() {
assertRunOnServiceThread();
return mArcFeatureEnabled;
}
@ServiceThreadOnly
void startArcAction(boolean enabled) {
assertRunOnServiceThread();
HdmiDeviceInfo info = getAvrDeviceInfo();
if (info == null) {
Slog.w(TAG, "Failed to start arc action; No AVR device.");
return;
}
if (!canStartArcUpdateAction(info.getLogicalAddress(), enabled)) {
Slog.w(TAG, "Failed to start arc action; ARC configuration check failed.");
if (enabled && !isConnectedToArcPort(info.getPhysicalAddress())) {
displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT);
}
return;
}
// Terminate opposite action and start action if not exist.
if (enabled) {
removeAction(RequestArcTerminationAction.class);
if (!hasAction(RequestArcInitiationAction.class)) {
addAndStartAction(new RequestArcInitiationAction(this, info.getLogicalAddress()));
}
} else {
removeAction(RequestArcInitiationAction.class);
if (!hasAction(RequestArcTerminationAction.class)) {
addAndStartAction(new RequestArcTerminationAction(this, info.getLogicalAddress()));
}
}
}
private boolean isDirectConnectAddress(int physicalAddress) {
return (physicalAddress & Constants.ROUTING_PATH_TOP_MASK) == physicalAddress;
}
void setAudioStatus(boolean mute, int volume) {
synchronized (mLock) {
mSystemAudioMute = mute;
mSystemAudioVolume = volume;
int maxVolume = mService.getAudioManager().getStreamMaxVolume(
AudioManager.STREAM_MUSIC);
mService.setAudioStatus(mute,
VolumeControlAction.scaleToCustomVolume(volume, maxVolume));
displayOsd(HdmiControlManager.OSD_MESSAGE_AVR_VOLUME_CHANGED,
mute ? HdmiControlManager.AVR_VOLUME_MUTED : volume);
}
}
@ServiceThreadOnly
void changeVolume(int curVolume, int delta, int maxVolume) {
assertRunOnServiceThread();
if (delta == 0 || !isSystemAudioActivated()) {
return;
}
int targetVolume = curVolume + delta;
int cecVolume = VolumeControlAction.scaleToCecVolume(targetVolume, maxVolume);
synchronized (mLock) {
// If new volume is the same as current system audio volume, just ignore it.
// Note that UNKNOWN_VOLUME is not in range of cec volume scale.
if (cecVolume == mSystemAudioVolume) {
// Update tv volume with system volume value.
mService.setAudioStatus(false,
VolumeControlAction.scaleToCustomVolume(mSystemAudioVolume, maxVolume));
return;
}
}
List<VolumeControlAction> actions = getActions(VolumeControlAction.class);
if (actions.isEmpty()) {
addAndStartAction(new VolumeControlAction(this,
getAvrDeviceInfo().getLogicalAddress(), delta > 0));
} else {
actions.get(0).handleVolumeChange(delta > 0);
}
}
@ServiceThreadOnly
void changeMute(boolean mute) {
assertRunOnServiceThread();
if (!isSystemAudioActivated()) {
return;
}
// Remove existing volume action.
removeAction(VolumeControlAction.class);
sendUserControlPressedAndReleased(getAvrDeviceInfo().getLogicalAddress(),
mute ? HdmiCecKeycode.CEC_KEYCODE_MUTE_FUNCTION :
HdmiCecKeycode.CEC_KEYCODE_RESTORE_VOLUME_FUNCTION);
}
@Override
@ServiceThreadOnly
protected boolean handleInitiateArc(HdmiCecMessage message) {
assertRunOnServiceThread();
if (!canStartArcUpdateAction(message.getSource(), true)) {
mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED);
if (!isConnectedToArcPort(message.getSource())) {
displayOsd(OSD_MESSAGE_ARC_CONNECTED_INVALID_PORT);
}
return true;
}
// In case where <Initiate Arc> is started by <Request ARC Initiation>
// need to clean up RequestArcInitiationAction.
removeAction(RequestArcInitiationAction.class);
SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this,
message.getSource(), true);
addAndStartAction(action);
return true;
}
private boolean canStartArcUpdateAction(int avrAddress, boolean shouldCheckArcFeatureEnabled) {
HdmiDeviceInfo avr = getAvrDeviceInfo();
if (avr != null
&& (avrAddress == avr.getLogicalAddress())
&& isConnectedToArcPort(avr.getPhysicalAddress())
&& isDirectConnectAddress(avr.getPhysicalAddress())) {
if (shouldCheckArcFeatureEnabled) {
return isArcFeatureEnabled();
} else {
return true;
}
} else {
return false;
}
}
@Override
@ServiceThreadOnly
protected boolean handleTerminateArc(HdmiCecMessage message) {
assertRunOnServiceThread();
// In cast of termination, do not check ARC configuration in that AVR device
// might be removed already.
// In case where <Terminate Arc> is started by <Request ARC Termination>
// need to clean up RequestArcInitiationAction.
removeAction(RequestArcTerminationAction.class);
SetArcTransmissionStateAction action = new SetArcTransmissionStateAction(this,
message.getSource(), false);
addAndStartAction(action);
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleSetSystemAudioMode(HdmiCecMessage message) {
assertRunOnServiceThread();
if (!isMessageForSystemAudio(message)) {
HdmiLogger.warning("Invalid <Set System Audio Mode> message:" + message);
mService.maySendFeatureAbortCommand(message, Constants.ABORT_REFUSED);
return true;
}
SystemAudioActionFromAvr action = new SystemAudioActionFromAvr(this,
message.getSource(), HdmiUtils.parseCommandParamSystemAudioStatus(message), null);
addAndStartAction(action);
return true;
}
@Override
@ServiceThreadOnly
protected boolean handleSystemAudioModeStatus(HdmiCecMessage message) {
assertRunOnServiceThread();
if (!isMessageForSystemAudio(message)) {
HdmiLogger.warning("Invalid <System Audio Mode Status> message:" + message);
// Ignore this message.
return true;
}
setSystemAudioMode(HdmiUtils.parseCommandParamSystemAudioStatus(message), true);
return true;
}
// Seq #53
@Override
@ServiceThreadOnly
protected boolean handleRecordTvScreen(HdmiCecMessage message) {
List<OneTouchRecordAction> actions = getActions(OneTouchRecordAction.class);
if (!actions.isEmpty()) {
// Assumes only one OneTouchRecordAction.
OneTouchRecordAction action = actions.get(0);
if (action.getRecorderAddress() != message.getSource()) {
announceOneTouchRecordResult(
HdmiControlManager.ONE_TOUCH_RECORD_PREVIOUS_RECORDING_IN_PROGRESS);
}
return super.handleRecordTvScreen(message);
}
int recorderAddress = message.getSource();
byte[] recordSource = mService.invokeRecordRequestListener(recorderAddress);
int reason = startOneTouchRecord(recorderAddress, recordSource);
if (reason != Constants.ABORT_NO_ERROR) {
mService.maySendFeatureAbortCommand(message, reason);
}
return true;
}
@Override
protected boolean handleTimerClearedStatus(HdmiCecMessage message) {
byte[] params = message.getParams();
int timerClearedStatusData = params[0] & 0xFF;
announceTimerRecordingResult(timerClearedStatusData);
return true;
}
void announceOneTouchRecordResult(int result) {
mService.invokeOneTouchRecordResult(result);
}
void announceTimerRecordingResult(int result) {
mService.invokeTimerRecordingResult(result);
}
void announceClearTimerRecordingResult(int result) {
mService.invokeClearTimerRecordingResult(result);
}
private boolean isMessageForSystemAudio(HdmiCecMessage message) {
return mService.isControlEnabled()
&& message.getSource() == Constants.ADDR_AUDIO_SYSTEM
&& (message.getDestination() == Constants.ADDR_TV
|| message.getDestination() == Constants.ADDR_BROADCAST)
&& getAvrDeviceInfo() != null;
}
/**
* Add a new {@link HdmiDeviceInfo}. It returns old device info which has the same
* logical address as new device info's.
*
* <p>Declared as package-private. accessed by {@link HdmiControlService} only.
*
* @param deviceInfo a new {@link HdmiDeviceInfo} to be added.
* @return {@code null} if it is new device. Otherwise, returns old {@HdmiDeviceInfo}
* that has the same logical address as new one has.
*/
@ServiceThreadOnly
private HdmiDeviceInfo addDeviceInfo(HdmiDeviceInfo deviceInfo) {
assertRunOnServiceThread();
HdmiDeviceInfo oldDeviceInfo = getCecDeviceInfo(deviceInfo.getLogicalAddress());
if (oldDeviceInfo != null) {
removeDeviceInfo(deviceInfo.getId());
}
mDeviceInfos.append(deviceInfo.getId(), deviceInfo);
updateSafeDeviceInfoList();
return oldDeviceInfo;
}
/**
* Remove a device info corresponding to the given {@code logicalAddress}.
* It returns removed {@link HdmiDeviceInfo} if exists.
*
* <p>Declared as package-private. accessed by {@link HdmiControlService} only.
*
* @param id id of device to be removed
* @return removed {@link HdmiDeviceInfo} it exists. Otherwise, returns {@code null}
*/
@ServiceThreadOnly
private HdmiDeviceInfo removeDeviceInfo(int id) {
assertRunOnServiceThread();
HdmiDeviceInfo deviceInfo = mDeviceInfos.get(id);
if (deviceInfo != null) {
mDeviceInfos.remove(id);
}
updateSafeDeviceInfoList();
return deviceInfo;
}
/**
* Return a list of all {@link HdmiDeviceInfo}.
*
* <p>Declared as package-private. accessed by {@link HdmiControlService} only.
* This is not thread-safe. For thread safety, call {@link #getSafeExternalInputsLocked} which
* does not include local device.
*/
@ServiceThreadOnly
List<HdmiDeviceInfo> getDeviceInfoList(boolean includeLocalDevice) {
assertRunOnServiceThread();
if (includeLocalDevice) {
return HdmiUtils.sparseArrayToList(mDeviceInfos);
} else {
ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
for (int i = 0; i < mDeviceInfos.size(); ++i) {
HdmiDeviceInfo info = mDeviceInfos.valueAt(i);
if (!isLocalDeviceAddress(info.getLogicalAddress())) {
infoList.add(info);
}
}
return infoList;
}
}
/**
* Return external input devices.
*/
List<HdmiDeviceInfo> getSafeExternalInputsLocked() {
return mSafeExternalInputs;
}
@ServiceThreadOnly
private void updateSafeDeviceInfoList() {
assertRunOnServiceThread();
List<HdmiDeviceInfo> copiedDevices = HdmiUtils.sparseArrayToList(mDeviceInfos);
List<HdmiDeviceInfo> externalInputs = getInputDevices();
synchronized (mLock) {
mSafeAllDeviceInfos = copiedDevices;
mSafeExternalInputs = externalInputs;
}
}
/**
* Return a list of external cec input (source) devices.
*
* <p>Note that this effectively excludes non-source devices like system audio,
* secondary TV.
*/
private List<HdmiDeviceInfo> getInputDevices() {
ArrayList<HdmiDeviceInfo> infoList = new ArrayList<>();
for (int i = 0; i < mDeviceInfos.size(); ++i) {
HdmiDeviceInfo info = mDeviceInfos.valueAt(i);
if (isLocalDeviceAddress(info.getLogicalAddress())) {
continue;
}
if (info.isSourceType() && !hideDevicesBehindLegacySwitch(info)) {
infoList.add(info);
}
}
return infoList;
}
// Check if we are hiding CEC devices connected to a legacy (non-CEC) switch.
// Returns true if the policy is set to true, and the device to check does not have
// a parent CEC device (which should be the CEC-enabled switch) in the list.
private boolean hideDevicesBehindLegacySwitch(HdmiDeviceInfo info) {
return HdmiConfig.HIDE_DEVICES_BEHIND_LEGACY_SWITCH
&& !isConnectedToCecSwitch(info.getPhysicalAddress(), mCecSwitches);
}
private static boolean isConnectedToCecSwitch(int path, Collection<Integer> switches) {
for (int switchPath : switches) {
if (isParentPath(switchPath, path)) {
return true;
}
}
return false;
}
private static boolean isParentPath(int parentPath, int childPath) {
// (A000, AB00) (AB00, ABC0), (ABC0, ABCD)
// If child's last non-zero nibble is removed, the result equals to the parent.
for (int i = 0; i <= 12; i += 4) {
int nibble = (childPath >> i) & 0xF;
if (nibble != 0) {
int parentNibble = (parentPath >> i) & 0xF;
return parentNibble == 0 && (childPath >> i+4) == (parentPath >> i+4);
}
}
return false;
}
private void invokeDeviceEventListener(HdmiDeviceInfo info, int status) {
if (info.isSourceType() && !hideDevicesBehindLegacySwitch(info)) {
mService.invokeDeviceEventListeners(info, status);
}
}
@ServiceThreadOnly
private boolean isLocalDeviceAddress(int address) {
assertRunOnServiceThread();
for (HdmiCecLocalDevice device : mService.getAllLocalDevices()) {
if (device.isAddressOf(address)) {
return true;
}
}
return false;
}
@ServiceThreadOnly
HdmiDeviceInfo getAvrDeviceInfo() {
assertRunOnServiceThread();
return getCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM);
}
/**
* Return a {@link HdmiDeviceInfo} corresponding to the given {@code logicalAddress}.
*
* This is not thread-safe. For thread safety, call {@link #getSafeCecDeviceInfo(int)}.
*
* @param logicalAddress logical address of the device to be retrieved
* @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}.
* Returns null if no logical address matched
*/
@ServiceThreadOnly
HdmiDeviceInfo getCecDeviceInfo(int logicalAddress) {
assertRunOnServiceThread();
return mDeviceInfos.get(HdmiDeviceInfo.idForCecDevice(logicalAddress));
}
boolean hasSystemAudioDevice() {
return getSafeAvrDeviceInfo() != null;
}
HdmiDeviceInfo getSafeAvrDeviceInfo() {
return getSafeCecDeviceInfo(Constants.ADDR_AUDIO_SYSTEM);
}
/**
* Thread safe version of {@link #getCecDeviceInfo(int)}.
*
* @param logicalAddress logical address to be retrieved
* @return {@link HdmiDeviceInfo} matched with the given {@code logicalAddress}.
* Returns null if no logical address matched
*/
HdmiDeviceInfo getSafeCecDeviceInfo(int logicalAddress) {
synchronized (mLock) {
for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
if (info.isCecDevice() && info.getLogicalAddress() == logicalAddress) {
return info;
}
}
return null;
}
}
/**
* Called when a device is newly added or a new device is detected or
* existing device is updated.
*
* @param info device info of a new device.
*/
@ServiceThreadOnly
final void addCecDevice(HdmiDeviceInfo info) {
assertRunOnServiceThread();
addDeviceInfo(info);
if (info.getLogicalAddress() == mAddress) {
// The addition of TV device itself should not be notified.
return;
}
invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_ADD_DEVICE);
}
/**
* Called when a device is removed or removal of device is detected.
*
* @param address a logical address of a device to be removed
*/
@ServiceThreadOnly
final void removeCecDevice(int address) {
assertRunOnServiceThread();
HdmiDeviceInfo info = removeDeviceInfo(HdmiDeviceInfo.idForCecDevice(address));
mCecMessageCache.flushMessagesFrom(address);
invokeDeviceEventListener(info, HdmiControlManager.DEVICE_EVENT_REMOVE_DEVICE);
}
@ServiceThreadOnly
void handleRemoveActiveRoutingPath(int path) {
assertRunOnServiceThread();
// Seq #23
if (isTailOfActivePath(path, getActivePath())) {
removeAction(RoutingControlAction.class);
int newPath = mService.portIdToPath(getActivePortId());
mService.sendCecCommand(HdmiCecMessageBuilder.buildRoutingChange(
mAddress, getActivePath(), newPath));
mActiveSource.invalidate();
addAndStartAction(new RoutingControlAction(this, getActivePath(), true, null));
}
}
/**
* Launch routing control process.
*
* @param routingForBootup true if routing control is initiated due to One Touch Play
* or TV power on
*/
@ServiceThreadOnly
void launchRoutingControl(boolean routingForBootup) {
assertRunOnServiceThread();
// Seq #24
if (getActivePortId() != Constants.INVALID_PORT_ID) {
if (!routingForBootup && !isProhibitMode()) {
removeAction(RoutingControlAction.class);
int newPath = mService.portIdToPath(getActivePortId());
setActivePath(newPath);
mService.sendCecCommand(HdmiCecMessageBuilder.buildRoutingChange(mAddress,
getActivePath(), newPath));
addAndStartAction(new RoutingControlAction(this, getActivePortId(),
routingForBootup, null));
}
} else {
int activePath = mService.getPhysicalAddress();
setActivePath(activePath);
if (!routingForBootup) {
mService.sendCecCommand(HdmiCecMessageBuilder.buildActiveSource(mAddress,
activePath));
}
}
}
/**
* Returns the {@link HdmiDeviceInfo} instance whose physical address matches
* the given routing path. CEC devices use routing path for its physical address to
* describe the hierarchy of the devices in the network.
*
* @param path routing path or physical address
* @return {@link HdmiDeviceInfo} if the matched info is found; otherwise null
*/
@ServiceThreadOnly
final HdmiDeviceInfo getDeviceInfoByPath(int path) {
assertRunOnServiceThread();
for (HdmiDeviceInfo info : getDeviceInfoList(false)) {
if (info.getPhysicalAddress() == path) {
return info;
}
}
return null;
}
/**
* Whether a device of the specified physical address and logical address exists
* in a device info list. However, both are minimal condition and it could
* be different device from the original one.
*
* @param logicalAddress logical address of a device to be searched
* @param physicalAddress physical address of a device to be searched
* @return true if exist; otherwise false
*/
@ServiceThreadOnly
private boolean isInDeviceList(int logicalAddress, int physicalAddress) {
assertRunOnServiceThread();
HdmiDeviceInfo device = getCecDeviceInfo(logicalAddress);
if (device == null) {
return false;
}
return device.getPhysicalAddress() == physicalAddress;
}
@Override
@ServiceThreadOnly
void onHotplug(int portId, boolean connected) {
assertRunOnServiceThread();
if (!connected) {
removeCecSwitches(portId);
}
// Tv device will have permanent HotplugDetectionAction.
List<HotplugDetectionAction> hotplugActions = getActions(HotplugDetectionAction.class);
if (!hotplugActions.isEmpty()) {
// Note that hotplug action is single action running on a machine.
// "pollAllDevicesNow" cleans up timer and start poll action immediately.
// It covers seq #40, #43.
hotplugActions.get(0).pollAllDevicesNow();
}
}
private void removeCecSwitches(int portId) {
Iterator<Integer> it = mCecSwitches.iterator();
while (!it.hasNext()) {
int path = it.next();
if (pathToPortId(path) == portId) {
it.remove();
}
}
}
@ServiceThreadOnly
void setAutoDeviceOff(boolean enabled) {
assertRunOnServiceThread();
mAutoDeviceOff = enabled;
}
@ServiceThreadOnly
void setAutoWakeup(boolean enabled) {
assertRunOnServiceThread();
mAutoWakeup = enabled;
}
@ServiceThreadOnly
boolean getAutoWakeup() {
assertRunOnServiceThread();
return mAutoWakeup;
}
@Override
@ServiceThreadOnly
protected void disableDevice(boolean initiatedByCec, PendingActionClearedCallback callback) {
super.disableDevice(initiatedByCec, callback);
assertRunOnServiceThread();
// Remove any repeated working actions.
// HotplugDetectionAction will be reinstated during the wake up process.
// HdmiControlService.onWakeUp() -> initializeLocalDevices() ->
// LocalDeviceTv.onAddressAllocated() -> launchDeviceDiscovery().
removeAction(DeviceDiscoveryAction.class);
removeAction(HotplugDetectionAction.class);
removeAction(PowerStatusMonitorAction.class);
// Remove recording actions.
removeAction(OneTouchRecordAction.class);
removeAction(TimerRecordingAction.class);
disableSystemAudioIfExist();
disableArcIfExist();
clearDeviceInfoList();
checkIfPendingActionsCleared();
}
@ServiceThreadOnly
private void disableSystemAudioIfExist() {
assertRunOnServiceThread();
if (getAvrDeviceInfo() == null) {
return;
}
// Seq #31.
removeAction(SystemAudioActionFromAvr.class);
removeAction(SystemAudioActionFromTv.class);
removeAction(SystemAudioAutoInitiationAction.class);
removeAction(SystemAudioStatusAction.class);
removeAction(VolumeControlAction.class);
// Turn off the mode but do not write it the settings, so that the next time TV powers on
// the system audio mode setting can be restored automatically.
setSystemAudioMode(false, false);
}
@ServiceThreadOnly
private void disableArcIfExist() {
assertRunOnServiceThread();
HdmiDeviceInfo avr = getAvrDeviceInfo();
if (avr == null) {
return;
}
// Seq #44.
removeAction(RequestArcInitiationAction.class);
if (!hasAction(RequestArcTerminationAction.class) && isArcEstabilished()) {
addAndStartAction(new RequestArcTerminationAction(this, avr.getLogicalAddress()));
}
}
@Override
@ServiceThreadOnly
protected void onStandby(boolean initiatedByCec) {
assertRunOnServiceThread();
// Seq #11
if (!mService.isControlEnabled()) {
return;
}
if (!initiatedByCec && mAutoDeviceOff) {
mService.sendCecCommand(HdmiCecMessageBuilder.buildStandby(
mAddress, Constants.ADDR_BROADCAST));
}
}
boolean isProhibitMode() {
return mService.isProhibitMode();
}
boolean isPowerStandbyOrTransient() {
return mService.isPowerStandbyOrTransient();
}
@ServiceThreadOnly
void displayOsd(int messageId) {
assertRunOnServiceThread();
mService.displayOsd(messageId);
}
@ServiceThreadOnly
void displayOsd(int messageId, int extra) {
assertRunOnServiceThread();
mService.displayOsd(messageId, extra);
}
// Seq #54 and #55
@ServiceThreadOnly
int startOneTouchRecord(int recorderAddress, byte[] recordSource) {
assertRunOnServiceThread();
if (!mService.isControlEnabled()) {
Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
announceOneTouchRecordResult(ONE_TOUCH_RECORD_CEC_DISABLED);
return Constants.ABORT_NOT_IN_CORRECT_MODE;
}
if (!checkRecorder(recorderAddress)) {
Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
announceOneTouchRecordResult(ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
return Constants.ABORT_NOT_IN_CORRECT_MODE;
}
if (!checkRecordSource(recordSource)) {
Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
announceOneTouchRecordResult(ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN);
return Constants.ABORT_UNABLE_TO_DETERMINE;
}
addAndStartAction(new OneTouchRecordAction(this, recorderAddress, recordSource));
Slog.i(TAG, "Start new [One Touch Record]-Target:" + recorderAddress + ", recordSource:"
+ Arrays.toString(recordSource));
return Constants.ABORT_NO_ERROR;
}
@ServiceThreadOnly
void stopOneTouchRecord(int recorderAddress) {
assertRunOnServiceThread();
if (!mService.isControlEnabled()) {
Slog.w(TAG, "Can not stop one touch record. CEC control is disabled.");
announceOneTouchRecordResult(ONE_TOUCH_RECORD_CEC_DISABLED);
return;
}
if (!checkRecorder(recorderAddress)) {
Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
announceOneTouchRecordResult(ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
return;
}
// Remove one touch record action so that other one touch record can be started.
removeAction(OneTouchRecordAction.class);
mService.sendCecCommand(HdmiCecMessageBuilder.buildRecordOff(mAddress, recorderAddress));
Slog.i(TAG, "Stop [One Touch Record]-Target:" + recorderAddress);
}
private boolean checkRecorder(int recorderAddress) {
HdmiDeviceInfo device = getCecDeviceInfo(recorderAddress);
return (device != null)
&& (HdmiUtils.getTypeFromAddress(recorderAddress)
== HdmiDeviceInfo.DEVICE_RECORDER);
}
private boolean checkRecordSource(byte[] recordSource) {
return (recordSource != null) && HdmiRecordSources.checkRecordSource(recordSource);
}
@ServiceThreadOnly
void startTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) {
assertRunOnServiceThread();
if (!mService.isControlEnabled()) {
Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
announceTimerRecordingResult(TIMER_RECORDING_RESULT_EXTRA_CEC_DISABLED);
return;
}
if (!checkRecorder(recorderAddress)) {
Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
announceTimerRecordingResult(
TIMER_RECORDING_RESULT_EXTRA_CHECK_RECORDER_CONNECTION);
return;
}
if (!checkTimerRecordingSource(sourceType, recordSource)) {
Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
announceTimerRecordingResult(
TIMER_RECORDING_RESULT_EXTRA_FAIL_TO_RECORD_SELECTED_SOURCE);
return;
}
addAndStartAction(
new TimerRecordingAction(this, recorderAddress, sourceType, recordSource));
Slog.i(TAG, "Start [Timer Recording]-Target:" + recorderAddress + ", SourceType:"
+ sourceType + ", RecordSource:" + Arrays.toString(recordSource));
}
private boolean checkTimerRecordingSource(int sourceType, byte[] recordSource) {
return (recordSource != null)
&& HdmiTimerRecordSources.checkTimerRecordSource(sourceType, recordSource);
}
@ServiceThreadOnly
void clearTimerRecording(int recorderAddress, int sourceType, byte[] recordSource) {
assertRunOnServiceThread();
if (!mService.isControlEnabled()) {
Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_CEC_DISABLE);
return;
}
if (!checkRecorder(recorderAddress)) {
Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_CHECK_RECORDER_CONNECTION);
return;
}
if (!checkTimerRecordingSource(sourceType, recordSource)) {
Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
return;
}
sendClearTimerMessage(recorderAddress, sourceType, recordSource);
}
private void sendClearTimerMessage(int recorderAddress, int sourceType, byte[] recordSource) {
HdmiCecMessage message = null;
switch (sourceType) {
case TIMER_RECORDING_TYPE_DIGITAL:
message = HdmiCecMessageBuilder.buildClearDigitalTimer(mAddress, recorderAddress,
recordSource);
break;
case TIMER_RECORDING_TYPE_ANALOGUE:
message = HdmiCecMessageBuilder.buildClearAnalogueTimer(mAddress, recorderAddress,
recordSource);
break;
case TIMER_RECORDING_TYPE_EXTERNAL:
message = HdmiCecMessageBuilder.buildClearExternalTimer(mAddress, recorderAddress,
recordSource);
break;
default:
Slog.w(TAG, "Invalid source type:" + recorderAddress);
announceClearTimerRecordingResult(CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
return;
}
mService.sendCecCommand(message, new SendMessageCallback() {
@Override
public void onSendCompleted(int error) {
if (error != Constants.SEND_RESULT_SUCCESS) {
announceClearTimerRecordingResult(
CLEAR_TIMER_STATUS_FAIL_TO_CLEAR_SELECTED_SOURCE);
}
}
});
}
void updateDevicePowerStatus(int logicalAddress, int newPowerStatus) {
HdmiDeviceInfo info = getCecDeviceInfo(logicalAddress);
if (info == null) {
Slog.w(TAG, "Can not update power status of non-existing device:" + logicalAddress);
return;
}
if (info.getDevicePowerStatus() == newPowerStatus) {
return;
}
HdmiDeviceInfo newInfo = HdmiUtils.cloneHdmiDeviceInfo(info, newPowerStatus);
// addDeviceInfo replaces old device info with new one if exists.
addDeviceInfo(newInfo);
invokeDeviceEventListener(newInfo, HdmiControlManager.DEVICE_EVENT_UPDATE_DEVICE);
}
@Override
protected void dump(final IndentingPrintWriter pw) {
super.dump(pw);
pw.println("mArcEstablished: " + mArcEstablished);
pw.println("mArcFeatureEnabled: " + mArcFeatureEnabled);
pw.println("mSystemAudioActivated: " + mSystemAudioActivated);
pw.println("mSystemAudioMute: " + mSystemAudioMute);
pw.println("mAutoDeviceOff: " + mAutoDeviceOff);
pw.println("mAutoWakeup: " + mAutoWakeup);
pw.println("mSkipRoutingControl: " + mSkipRoutingControl);
pw.println("CEC devices:");
pw.increaseIndent();
for (HdmiDeviceInfo info : mSafeAllDeviceInfos) {
pw.println(info);
}
pw.decreaseIndent();
}
}
|