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
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
|
/*
* Copyright (C) 2013 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.
*/
#define LOG_TAG "Camera3-Device"
#define ATRACE_TAG ATRACE_TAG_CAMERA
//#define LOG_NDEBUG 0
//#define LOG_NNDEBUG 0 // Per-frame verbose logging
#ifdef LOG_NNDEBUG
#define ALOGVV(...) ALOGV(__VA_ARGS__)
#else
#define ALOGVV(...) ((void)0)
#endif
// Convenience macro for transient errors
#define CLOGE(fmt, ...) ALOGE("Camera %d: %s: " fmt, mId, __FUNCTION__, \
##__VA_ARGS__)
// Convenience macros for transitioning to the error state
#define SET_ERR(fmt, ...) setErrorState( \
"%s: " fmt, __FUNCTION__, \
##__VA_ARGS__)
#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
"%s: " fmt, __FUNCTION__, \
##__VA_ARGS__)
#include <utils/Log.h>
#include <utils/Trace.h>
#include <utils/Timers.h>
#include "Camera3Device.h"
#include "camera3/Camera3OutputStream.h"
using namespace android::camera3;
namespace android {
Camera3Device::Camera3Device(int id):
mId(id),
mHal3Device(NULL),
mStatus(STATUS_UNINITIALIZED),
mNextResultFrameNumber(0),
mNextShutterFrameNumber(0),
mListener(NULL)
{
ATRACE_CALL();
camera3_callback_ops::notify = &sNotify;
camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
ALOGV("%s: Created device for camera %d", __FUNCTION__, id);
}
Camera3Device::~Camera3Device()
{
ATRACE_CALL();
ALOGV("%s: Tearing down for camera id %d", __FUNCTION__, mId);
disconnect();
}
int Camera3Device::getId() const {
return mId;
}
/**
* CameraDeviceBase interface
*/
status_t Camera3Device::initialize(camera_module_t *module)
{
ATRACE_CALL();
Mutex::Autolock l(mLock);
ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mId);
if (mStatus != STATUS_UNINITIALIZED) {
CLOGE("Already initialized!");
return INVALID_OPERATION;
}
/** Open HAL device */
status_t res;
String8 deviceName = String8::format("%d", mId);
camera3_device_t *device;
res = module->common.methods->open(&module->common, deviceName.string(),
reinterpret_cast<hw_device_t**>(&device));
if (res != OK) {
SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
return res;
}
/** Cross-check device version */
if (device->common.version != CAMERA_DEVICE_API_VERSION_3_0) {
SET_ERR_L("Could not open camera: "
"Camera device is not version %x, reports %x instead",
CAMERA_DEVICE_API_VERSION_3_0,
device->common.version);
device->common.close(&device->common);
return BAD_VALUE;
}
camera_info info;
res = module->get_camera_info(mId, &info);
if (res != OK) return res;
if (info.device_version != device->common.version) {
SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
" and device version (%x).",
device->common.version, info.device_version);
device->common.close(&device->common);
return BAD_VALUE;
}
/** Initialize device with callback functions */
res = device->ops->initialize(device, this);
if (res != OK) {
SET_ERR_L("Unable to initialize HAL device: %s (%d)",
strerror(-res), res);
device->common.close(&device->common);
return BAD_VALUE;
}
/** Get vendor metadata tags */
mVendorTagOps.get_camera_vendor_section_name = NULL;
device->ops->get_metadata_vendor_tag_ops(device, &mVendorTagOps);
if (mVendorTagOps.get_camera_vendor_section_name != NULL) {
res = set_camera_metadata_vendor_tag_ops(&mVendorTagOps);
if (res != OK) {
SET_ERR_L("Unable to set tag ops: %s (%d)",
strerror(-res), res);
device->common.close(&device->common);
return res;
}
}
/** Start up request queue thread */
mRequestThread = new RequestThread(this, device);
res = mRequestThread->run(String8::format("C3Dev-%d-ReqQueue", mId).string());
if (res != OK) {
SET_ERR_L("Unable to start request queue thread: %s (%d)",
strerror(-res), res);
device->common.close(&device->common);
mRequestThread.clear();
return res;
}
/** Everything is good to go */
mDeviceInfo = info.static_camera_characteristics;
mHal3Device = device;
mStatus = STATUS_IDLE;
mNextStreamId = 0;
return OK;
}
status_t Camera3Device::disconnect() {
ATRACE_CALL();
Mutex::Autolock l(mLock);
ALOGV("%s: E", __FUNCTION__);
status_t res;
if (mStatus == STATUS_UNINITIALIZED) return OK;
if (mStatus == STATUS_ACTIVE ||
(mStatus == STATUS_ERROR && mRequestThread != NULL)) {
res = mRequestThread->clearRepeatingRequests();
if (res != OK) {
SET_ERR_L("Can't stop streaming");
return res;
}
res = waitUntilDrainedLocked();
if (res != OK) {
SET_ERR_L("Timeout waiting for HAL to drain");
return res;
}
}
assert(mStatus == STATUS_IDLE || mStatus == STATUS_ERROR);
if (mRequestThread != NULL) {
mRequestThread->requestExit();
}
mOutputStreams.clear();
mInputStream.clear();
if (mRequestThread != NULL) {
mRequestThread->join();
mRequestThread.clear();
}
if (mHal3Device != NULL) {
mHal3Device->common.close(&mHal3Device->common);
mHal3Device = NULL;
}
mStatus = STATUS_UNINITIALIZED;
ALOGV("%s: X", __FUNCTION__);
return OK;
}
status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
ATRACE_CALL();
(void)args;
String8 lines;
const char *status =
mStatus == STATUS_ERROR ? "ERROR" :
mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
mStatus == STATUS_IDLE ? "IDLE" :
mStatus == STATUS_ACTIVE ? "ACTIVE" :
"Unknown";
lines.appendFormat(" Device status: %s\n", status);
if (mStatus == STATUS_ERROR) {
lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
}
lines.appendFormat(" Stream configuration:\n");
if (mInputStream != NULL) {
write(fd, lines.string(), lines.size());
mInputStream->dump(fd, args);
} else {
lines.appendFormat(" No input stream.\n");
write(fd, lines.string(), lines.size());
}
for (size_t i = 0; i < mOutputStreams.size(); i++) {
mOutputStreams[i]->dump(fd,args);
}
lines = String8(" In-flight requests:\n");
if (mInFlightMap.size() == 0) {
lines.append(" None\n");
} else {
for (size_t i = 0; i < mInFlightMap.size(); i++) {
InFlightRequest r = mInFlightMap.valueAt(i);
lines.appendFormat(" Frame %d | Timestamp: %lld, metadata"
" arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
r.captureTimestamp, r.haveResultMetadata ? "true" : "false",
r.numBuffersLeft);
}
}
write(fd, lines.string(), lines.size());
if (mHal3Device != NULL) {
lines = String8(" HAL device dump:\n");
write(fd, lines.string(), lines.size());
mHal3Device->ops->dump(mHal3Device, fd);
}
return OK;
}
const CameraMetadata& Camera3Device::info() const {
ALOGVV("%s: E", __FUNCTION__);
if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
mStatus == STATUS_ERROR)) {
ALOGW("%s: Access to static info %s!", __FUNCTION__,
mStatus == STATUS_ERROR ?
"when in error state" : "before init");
}
return mDeviceInfo;
}
status_t Camera3Device::capture(CameraMetadata &request) {
ATRACE_CALL();
Mutex::Autolock l(mLock);
// TODO: take ownership of the request
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device not initialized");
return INVALID_OPERATION;
case STATUS_IDLE:
case STATUS_ACTIVE:
// OK
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
sp<CaptureRequest> newRequest = setUpRequestLocked(request);
if (newRequest == NULL) {
CLOGE("Can't create capture request");
return BAD_VALUE;
}
return mRequestThread->queueRequest(newRequest);
}
status_t Camera3Device::setStreamingRequest(const CameraMetadata &request) {
ATRACE_CALL();
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device not initialized");
return INVALID_OPERATION;
case STATUS_IDLE:
case STATUS_ACTIVE:
// OK
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
sp<CaptureRequest> newRepeatingRequest = setUpRequestLocked(request);
if (newRepeatingRequest == NULL) {
CLOGE("Can't create repeating request");
return BAD_VALUE;
}
RequestList newRepeatingRequests;
newRepeatingRequests.push_back(newRepeatingRequest);
return mRequestThread->setRepeatingRequests(newRepeatingRequests);
}
sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
const CameraMetadata &request) {
status_t res;
if (mStatus == STATUS_IDLE) {
res = configureStreamsLocked();
if (res != OK) {
SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res);
return NULL;
}
}
sp<CaptureRequest> newRequest = createCaptureRequest(request);
return newRequest;
}
status_t Camera3Device::clearStreamingRequest() {
ATRACE_CALL();
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device not initialized");
return INVALID_OPERATION;
case STATUS_IDLE:
case STATUS_ACTIVE:
// OK
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
return mRequestThread->clearRepeatingRequests();
}
status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
ATRACE_CALL();
return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
}
status_t Camera3Device::createStream(sp<ANativeWindow> consumer,
uint32_t width, uint32_t height, int format, size_t size, int *id) {
ATRACE_CALL();
Mutex::Autolock l(mLock);
status_t res;
bool wasActive = false;
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device not initialized");
return INVALID_OPERATION;
case STATUS_IDLE:
// OK
break;
case STATUS_ACTIVE:
ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
mRequestThread->setPaused(true);
res = waitUntilDrainedLocked();
if (res != OK) {
ALOGE("%s: Can't pause captures to reconfigure streams!",
__FUNCTION__);
return res;
}
wasActive = true;
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
assert(mStatus == STATUS_IDLE);
sp<Camera3OutputStream> newStream;
if (format == HAL_PIXEL_FORMAT_BLOB) {
newStream = new Camera3OutputStream(mNextStreamId, consumer,
width, height, size, format);
} else {
newStream = new Camera3OutputStream(mNextStreamId, consumer,
width, height, format);
}
res = mOutputStreams.add(mNextStreamId, newStream);
if (res < 0) {
SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
return res;
}
*id = mNextStreamId++;
// Continue captures if active at start
if (wasActive) {
ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
res = configureStreamsLocked();
if (res != OK) {
CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
mNextStreamId, strerror(-res), res);
return res;
}
mRequestThread->setPaused(false);
}
return OK;
}
status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
ATRACE_CALL();
(void)outputId; (void)id;
CLOGE("Unimplemented");
return INVALID_OPERATION;
}
status_t Camera3Device::getStreamInfo(int id,
uint32_t *width, uint32_t *height, uint32_t *format) {
ATRACE_CALL();
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device not initialized!");
return INVALID_OPERATION;
case STATUS_IDLE:
case STATUS_ACTIVE:
// OK
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
ssize_t idx = mOutputStreams.indexOfKey(id);
if (idx == NAME_NOT_FOUND) {
CLOGE("Stream %d is unknown", id);
return idx;
}
if (width) *width = mOutputStreams[idx]->getWidth();
if (height) *height = mOutputStreams[idx]->getHeight();
if (format) *format = mOutputStreams[idx]->getFormat();
return OK;
}
status_t Camera3Device::setStreamTransform(int id,
int transform) {
ATRACE_CALL();
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device not initialized");
return INVALID_OPERATION;
case STATUS_IDLE:
case STATUS_ACTIVE:
// OK
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
ssize_t idx = mOutputStreams.indexOfKey(id);
if (idx == NAME_NOT_FOUND) {
CLOGE("Stream %d does not exist",
id);
return BAD_VALUE;
}
return mOutputStreams.editValueAt(idx)->setTransform(transform);
}
status_t Camera3Device::deleteStream(int id) {
ATRACE_CALL();
Mutex::Autolock l(mLock);
status_t res;
// CameraDevice semantics require device to already be idle before
// deleteStream is called, unlike for createStream.
if (mStatus != STATUS_IDLE) {
CLOGE("Device not idle");
return INVALID_OPERATION;
}
sp<Camera3Stream> deletedStream;
if (mInputStream != NULL && id == mInputStream->getId()) {
deletedStream = mInputStream;
mInputStream.clear();
} else {
ssize_t idx = mOutputStreams.indexOfKey(id);
if (idx == NAME_NOT_FOUND) {
CLOGE("Stream %d does not exist", id);
return BAD_VALUE;
}
deletedStream = mOutputStreams.editValueAt(idx);
mOutputStreams.removeItem(id);
}
// Free up the stream endpoint so that it can be used by some other stream
res = deletedStream->disconnect();
if (res != OK) {
SET_ERR_L("Can't disconnect deleted stream %d", id);
// fall through since we want to still list the stream as deleted.
}
mDeletedStreams.add(deletedStream);
return res;
}
status_t Camera3Device::deleteReprocessStream(int id) {
ATRACE_CALL();
(void)id;
CLOGE("Unimplemented");
return INVALID_OPERATION;
}
status_t Camera3Device::createDefaultRequest(int templateId,
CameraMetadata *request) {
ATRACE_CALL();
ALOGV("%s: E", __FUNCTION__);
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device is not initialized!");
return INVALID_OPERATION;
case STATUS_IDLE:
case STATUS_ACTIVE:
// OK
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
const camera_metadata_t *rawRequest;
rawRequest = mHal3Device->ops->construct_default_request_settings(
mHal3Device, templateId);
if (rawRequest == NULL) {
SET_ERR_L("HAL is unable to construct default settings for template %d",
templateId);
return DEAD_OBJECT;
}
*request = rawRequest;
return OK;
}
status_t Camera3Device::waitUntilDrained() {
ATRACE_CALL();
Mutex::Autolock l(mLock);
return waitUntilDrainedLocked();
}
status_t Camera3Device::waitUntilDrainedLocked() {
ATRACE_CALL();
status_t res;
switch (mStatus) {
case STATUS_UNINITIALIZED:
case STATUS_IDLE:
ALOGV("%s: Already idle", __FUNCTION__);
return OK;
case STATUS_ERROR:
case STATUS_ACTIVE:
// Need to shut down
break;
default:
SET_ERR_L("Unexpected status: %d",mStatus);
return INVALID_OPERATION;
}
if (mRequestThread != NULL) {
res = mRequestThread->waitUntilPaused(kShutdownTimeout);
if (res != OK) {
SET_ERR_L("Can't stop request thread in %f seconds!",
kShutdownTimeout/1e9);
return res;
}
}
if (mInputStream != NULL) {
res = mInputStream->waitUntilIdle(kShutdownTimeout);
if (res != OK) {
SET_ERR_L("Can't idle input stream %d in %f seconds!",
mInputStream->getId(), kShutdownTimeout/1e9);
return res;
}
}
for (size_t i = 0; i < mOutputStreams.size(); i++) {
res = mOutputStreams.editValueAt(i)->waitUntilIdle(kShutdownTimeout);
if (res != OK) {
SET_ERR_L("Can't idle output stream %d in %f seconds!",
mOutputStreams.keyAt(i), kShutdownTimeout/1e9);
return res;
}
}
if (mStatus != STATUS_ERROR) {
mStatus = STATUS_IDLE;
}
return OK;
}
status_t Camera3Device::setNotifyCallback(NotificationListener *listener) {
ATRACE_CALL();
Mutex::Autolock l(mOutputLock);
if (listener != NULL && mListener != NULL) {
ALOGW("%s: Replacing old callback listener", __FUNCTION__);
}
mListener = listener;
return OK;
}
status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
ATRACE_CALL();
status_t res;
Mutex::Autolock l(mOutputLock);
while (mResultQueue.empty()) {
res = mResultSignal.waitRelative(mOutputLock, timeout);
if (res == TIMED_OUT) {
return res;
} else if (res != OK) {
ALOGW("%s: Camera %d: No frame in %lld ns: %s (%d)",
__FUNCTION__, mId, timeout, strerror(-res), res);
return res;
}
}
return OK;
}
status_t Camera3Device::getNextFrame(CameraMetadata *frame) {
ATRACE_CALL();
Mutex::Autolock l(mOutputLock);
if (mResultQueue.empty()) {
return NOT_ENOUGH_DATA;
}
CameraMetadata &result = *(mResultQueue.begin());
frame->acquire(result);
mResultQueue.erase(mResultQueue.begin());
return OK;
}
status_t Camera3Device::triggerAutofocus(uint32_t id) {
ATRACE_CALL();
ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
// Mix-in this trigger into the next request and only the next request.
RequestTrigger trigger[] = {
{
ANDROID_CONTROL_AF_TRIGGER,
ANDROID_CONTROL_AF_TRIGGER_START
},
{
ANDROID_CONTROL_AF_TRIGGER_ID,
static_cast<int32_t>(id)
},
};
return mRequestThread->queueTrigger(trigger,
sizeof(trigger)/sizeof(trigger[0]));
}
status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
ATRACE_CALL();
ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
// Mix-in this trigger into the next request and only the next request.
RequestTrigger trigger[] = {
{
ANDROID_CONTROL_AF_TRIGGER,
ANDROID_CONTROL_AF_TRIGGER_CANCEL
},
{
ANDROID_CONTROL_AF_TRIGGER_ID,
static_cast<int32_t>(id)
},
};
return mRequestThread->queueTrigger(trigger,
sizeof(trigger)/sizeof(trigger[0]));
}
status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
ATRACE_CALL();
ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
// Mix-in this trigger into the next request and only the next request.
RequestTrigger trigger[] = {
{
ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
},
{
ANDROID_CONTROL_AE_PRECAPTURE_ID,
static_cast<int32_t>(id)
},
};
return mRequestThread->queueTrigger(trigger,
sizeof(trigger)/sizeof(trigger[0]));
}
status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
ATRACE_CALL();
(void)reprocessStreamId; (void)buffer; (void)listener;
CLOGE("Unimplemented");
return INVALID_OPERATION;
}
/**
* Camera3Device private methods
*/
sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
const CameraMetadata &request) {
ATRACE_CALL();
status_t res;
sp<CaptureRequest> newRequest = new CaptureRequest;
newRequest->mSettings = request;
camera_metadata_entry_t inputStreams =
newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
if (inputStreams.count > 0) {
if (mInputStream == NULL ||
mInputStream->getId() != inputStreams.data.u8[0]) {
CLOGE("Request references unknown input stream %d",
inputStreams.data.u8[0]);
return NULL;
}
// Lazy completion of stream configuration (allocation/registration)
// on first use
if (mInputStream->isConfiguring()) {
res = mInputStream->finishConfiguration(mHal3Device);
if (res != OK) {
SET_ERR_L("Unable to finish configuring input stream %d:"
" %s (%d)",
mInputStream->getId(), strerror(-res), res);
return NULL;
}
}
newRequest->mInputStream = mInputStream;
newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
}
camera_metadata_entry_t streams =
newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
if (streams.count == 0) {
CLOGE("Zero output streams specified!");
return NULL;
}
for (size_t i = 0; i < streams.count; i++) {
int idx = mOutputStreams.indexOfKey(streams.data.u8[i]);
if (idx == NAME_NOT_FOUND) {
CLOGE("Request references unknown stream %d",
streams.data.u8[i]);
return NULL;
}
sp<Camera3OutputStream> stream = mOutputStreams.editValueAt(idx);
// Lazy completion of stream configuration (allocation/registration)
// on first use
if (stream->isConfiguring()) {
res = stream->finishConfiguration(mHal3Device);
if (res != OK) {
SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
stream->getId(), strerror(-res), res);
return NULL;
}
}
newRequest->mOutputStreams.push(stream);
}
newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
return newRequest;
}
status_t Camera3Device::configureStreamsLocked() {
ATRACE_CALL();
status_t res;
if (mStatus != STATUS_IDLE) {
CLOGE("Not idle");
return INVALID_OPERATION;
}
// Start configuring the streams
camera3_stream_configuration config;
config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
Vector<camera3_stream_t*> streams;
streams.setCapacity(config.num_streams);
if (mInputStream != NULL) {
camera3_stream_t *inputStream;
inputStream = mInputStream->startConfiguration();
if (inputStream == NULL) {
SET_ERR_L("Can't start input stream configuration");
return INVALID_OPERATION;
}
streams.add(inputStream);
}
for (size_t i = 0; i < mOutputStreams.size(); i++) {
camera3_stream_t *outputStream;
outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
if (outputStream == NULL) {
SET_ERR_L("Can't start output stream configuration");
return INVALID_OPERATION;
}
streams.add(outputStream);
}
config.streams = streams.editArray();
// Do the HAL configuration; will potentially touch stream
// max_buffers, usage, priv fields.
res = mHal3Device->ops->configure_streams(mHal3Device, &config);
if (res != OK) {
SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
strerror(-res), res);
return res;
}
// Finish all stream configuration immediately.
// TODO: Try to relax this later back to lazy completion, which should be
// faster
if (mInputStream != NULL) {
res = mInputStream->finishConfiguration(mHal3Device);
if (res != OK) {
SET_ERR_L("Can't finish configuring input stream %d: %s (%d)",
mInputStream->getId(), strerror(-res), res);
return res;
}
}
for (size_t i = 0; i < mOutputStreams.size(); i++) {
res = mOutputStreams.editValueAt(i)->finishConfiguration(mHal3Device);
if (res != OK) {
SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
mOutputStreams[i]->getId(), strerror(-res), res);
return res;
}
}
// Request thread needs to know to avoid using repeat-last-settings protocol
// across configure_streams() calls
mRequestThread->configurationComplete();
// Finish configuring the streams lazily on first reference
mStatus = STATUS_ACTIVE;
return OK;
}
void Camera3Device::setErrorState(const char *fmt, ...) {
Mutex::Autolock l(mLock);
va_list args;
va_start(args, fmt);
setErrorStateLockedV(fmt, args);
va_end(args);
}
void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Mutex::Autolock l(mLock);
setErrorStateLockedV(fmt, args);
}
void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
setErrorStateLockedV(fmt, args);
va_end(args);
}
void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
// Print out all error messages to log
String8 errorCause = String8::formatV(fmt, args);
ALOGE("Camera %d: %s", mId, errorCause.string());
// But only do error state transition steps for the first error
if (mStatus == STATUS_ERROR) return;
mErrorCause = errorCause;
mRequestThread->setPaused(true);
mStatus = STATUS_ERROR;
}
/**
* In-flight request management
*/
status_t Camera3Device::registerInFlight(int32_t frameNumber,
int32_t numBuffers) {
ATRACE_CALL();
Mutex::Autolock l(mInFlightLock);
ssize_t res;
res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers));
if (res < 0) return res;
return OK;
}
/**
* Camera HAL device callback methods
*/
void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
ATRACE_CALL();
status_t res;
uint32_t frameNumber = result->frame_number;
if (result->result == NULL && result->num_output_buffers == 0) {
SET_ERR("No result data provided by HAL for frame %d",
frameNumber);
return;
}
// Get capture timestamp from list of in-flight requests, where it was added
// by the shutter notification for this frame. Then update the in-flight
// status and remove the in-flight entry if all result data has been
// received.
nsecs_t timestamp = 0;
{
Mutex::Autolock l(mInFlightLock);
ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
if (idx == NAME_NOT_FOUND) {
SET_ERR("Unknown frame number for capture result: %d",
frameNumber);
return;
}
InFlightRequest &request = mInFlightMap.editValueAt(idx);
timestamp = request.captureTimestamp;
if (timestamp == 0) {
SET_ERR("Called before shutter notify for frame %d",
frameNumber);
return;
}
if (result->result != NULL) {
if (request.haveResultMetadata) {
SET_ERR("Called multiple times with metadata for frame %d",
frameNumber);
return;
}
request.haveResultMetadata = true;
}
request.numBuffersLeft -= result->num_output_buffers;
if (request.numBuffersLeft < 0) {
SET_ERR("Too many buffers returned for frame %d",
frameNumber);
return;
}
if (request.haveResultMetadata && request.numBuffersLeft == 0) {
mInFlightMap.removeItemsAt(idx, 1);
}
// Sanity check - if we have too many in-flight frames, something has
// likely gone wrong
if (mInFlightMap.size() > kInFlightWarnLimit) {
CLOGE("In-flight list too large: %d", mInFlightMap.size());
}
}
AlgState cur3aState;
AlgState new3aState;
int32_t aeTriggerId = 0;
int32_t afTriggerId = 0;
NotificationListener *listener = NULL;
// Process the result metadata, if provided
if (result->result != NULL) {
Mutex::Autolock l(mOutputLock);
if (frameNumber != mNextResultFrameNumber) {
SET_ERR("Out-of-order capture result metadata submitted! "
"(got frame number %d, expecting %d)",
frameNumber, mNextResultFrameNumber);
return;
}
mNextResultFrameNumber++;
CameraMetadata &captureResult =
*mResultQueue.insert(mResultQueue.end(), CameraMetadata());
captureResult = result->result;
if (captureResult.update(ANDROID_REQUEST_FRAME_COUNT,
(int32_t*)&frameNumber, 1) != OK) {
SET_ERR("Failed to set frame# in metadata (%d)",
frameNumber);
} else {
ALOGVV("%s: Camera %d: Set frame# in metadata (%d)",
__FUNCTION__, mId, frameNumber);
}
// Check that there's a timestamp in the result metadata
camera_metadata_entry entry =
captureResult.find(ANDROID_SENSOR_TIMESTAMP);
if (entry.count == 0) {
SET_ERR("No timestamp provided by HAL for frame %d!",
frameNumber);
}
if (timestamp != entry.data.i64[0]) {
SET_ERR("Timestamp mismatch between shutter notify and result"
" metadata for frame %d (%lld vs %lld respectively)",
frameNumber, timestamp, entry.data.i64[0]);
}
// Get 3A states from result metadata
entry = captureResult.find(ANDROID_CONTROL_AE_STATE);
if (entry.count == 0) {
CLOGE("No AE state provided by HAL for frame %d!",
frameNumber);
} else {
new3aState.aeState =
static_cast<camera_metadata_enum_android_control_ae_state>(
entry.data.u8[0]);
}
entry = captureResult.find(ANDROID_CONTROL_AF_STATE);
if (entry.count == 0) {
CLOGE("No AF state provided by HAL for frame %d!",
frameNumber);
} else {
new3aState.afState =
static_cast<camera_metadata_enum_android_control_af_state>(
entry.data.u8[0]);
}
entry = captureResult.find(ANDROID_CONTROL_AWB_STATE);
if (entry.count == 0) {
CLOGE("No AWB state provided by HAL for frame %d!",
frameNumber);
} else {
new3aState.awbState =
static_cast<camera_metadata_enum_android_control_awb_state>(
entry.data.u8[0]);
}
entry = captureResult.find(ANDROID_CONTROL_AF_TRIGGER_ID);
if (entry.count == 0) {
CLOGE("No AF trigger ID provided by HAL for frame %d!",
frameNumber);
} else {
afTriggerId = entry.data.i32[0];
}
entry = captureResult.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
if (entry.count == 0) {
CLOGE("No AE precapture trigger ID provided by HAL"
" for frame %d!", frameNumber);
} else {
aeTriggerId = entry.data.i32[0];
}
listener = mListener;
cur3aState = m3AState;
m3AState = new3aState;
} // scope for mOutputLock
// Return completed buffers to their streams with the timestamp
for (size_t i = 0; i < result->num_output_buffers; i++) {
Camera3Stream *stream =
Camera3Stream::cast(result->output_buffers[i].stream);
res = stream->returnBuffer(result->output_buffers[i], timestamp);
// Note: stream may be deallocated at this point, if this buffer was the
// last reference to it.
if (res != OK) {
SET_ERR("Can't return buffer %d for frame %d to its stream: "
" %s (%d)", i, frameNumber, strerror(-res), res);
}
}
// Finally, dispatch any 3A change events to listeners if we got metadata
if (result->result != NULL && listener != NULL) {
if (new3aState.aeState != cur3aState.aeState) {
ALOGVV("%s: AE state changed from 0x%x to 0x%x",
__FUNCTION__, cur3aState.aeState, new3aState.aeState);
listener->notifyAutoExposure(new3aState.aeState, aeTriggerId);
}
if (new3aState.afState != cur3aState.afState) {
ALOGVV("%s: AF state changed from 0x%x to 0x%x",
__FUNCTION__, cur3aState.afState, new3aState.afState);
listener->notifyAutoFocus(new3aState.afState, afTriggerId);
}
if (new3aState.awbState != cur3aState.awbState) {
listener->notifyAutoWhitebalance(new3aState.awbState, aeTriggerId);
}
}
}
void Camera3Device::notify(const camera3_notify_msg *msg) {
NotificationListener *listener;
{
Mutex::Autolock l(mOutputLock);
listener = mListener;
}
if (msg == NULL) {
SET_ERR("HAL sent NULL notify message!");
return;
}
switch (msg->type) {
case CAMERA3_MSG_ERROR: {
int streamId = 0;
if (msg->message.error.error_stream != NULL) {
Camera3Stream *stream =
Camera3Stream::cast(
msg->message.error.error_stream);
streamId = stream->getId();
}
if (listener != NULL) {
listener->notifyError(msg->message.error.error_code,
msg->message.error.frame_number, streamId);
}
break;
}
case CAMERA3_MSG_SHUTTER: {
ssize_t idx;
uint32_t frameNumber = msg->message.shutter.frame_number;
nsecs_t timestamp = msg->message.shutter.timestamp;
// Verify ordering of shutter notifications
{
Mutex::Autolock l(mOutputLock);
if (frameNumber != mNextShutterFrameNumber) {
SET_ERR("Shutter notification out-of-order. Expected "
"notification for frame %d, got frame %d",
mNextShutterFrameNumber, frameNumber);
break;
}
mNextShutterFrameNumber++;
}
// Set timestamp for the request in the in-flight tracking
{
Mutex::Autolock l(mInFlightLock);
idx = mInFlightMap.indexOfKey(frameNumber);
if (idx >= 0) {
mInFlightMap.editValueAt(idx).captureTimestamp = timestamp;
}
}
if (idx < 0) {
SET_ERR("Shutter notification for non-existent frame number %d",
frameNumber);
break;
}
// Call listener, if any
if (listener != NULL) {
listener->notifyShutter(frameNumber, timestamp);
}
break;
}
default:
SET_ERR("Unknown notify message from HAL: %d",
msg->type);
}
}
/**
* RequestThread inner class methods
*/
Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
camera3_device_t *hal3Device) :
Thread(false),
mParent(parent),
mHal3Device(hal3Device),
mId(getId(parent)),
mReconfigured(false),
mDoPause(false),
mPaused(true),
mFrameNumber(0),
mLatestRequestId(NAME_NOT_FOUND) {
}
void Camera3Device::RequestThread::configurationComplete() {
Mutex::Autolock l(mRequestLock);
mReconfigured = true;
}
status_t Camera3Device::RequestThread::queueRequest(
sp<CaptureRequest> request) {
Mutex::Autolock l(mRequestLock);
mRequestQueue.push_back(request);
return OK;
}
status_t Camera3Device::RequestThread::queueTrigger(
RequestTrigger trigger[],
size_t count) {
Mutex::Autolock l(mTriggerMutex);
status_t ret;
for (size_t i = 0; i < count; ++i) {
ret = queueTriggerLocked(trigger[i]);
if (ret != OK) {
return ret;
}
}
return OK;
}
int Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
sp<Camera3Device> d = device.promote();
if (d != NULL) return d->mId;
return 0;
}
status_t Camera3Device::RequestThread::queueTriggerLocked(
RequestTrigger trigger) {
uint32_t tag = trigger.metadataTag;
ssize_t index = mTriggerMap.indexOfKey(tag);
switch (trigger.getTagType()) {
case TYPE_BYTE:
// fall-through
case TYPE_INT32:
break;
default:
ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
trigger.getTagType());
return INVALID_OPERATION;
}
/**
* Collect only the latest trigger, since we only have 1 field
* in the request settings per trigger tag, and can't send more than 1
* trigger per request.
*/
if (index != NAME_NOT_FOUND) {
mTriggerMap.editValueAt(index) = trigger;
} else {
mTriggerMap.add(tag, trigger);
}
return OK;
}
status_t Camera3Device::RequestThread::setRepeatingRequests(
const RequestList &requests) {
Mutex::Autolock l(mRequestLock);
mRepeatingRequests.clear();
mRepeatingRequests.insert(mRepeatingRequests.begin(),
requests.begin(), requests.end());
return OK;
}
status_t Camera3Device::RequestThread::clearRepeatingRequests() {
Mutex::Autolock l(mRequestLock);
mRepeatingRequests.clear();
return OK;
}
void Camera3Device::RequestThread::setPaused(bool paused) {
Mutex::Autolock l(mPauseLock);
mDoPause = paused;
mDoPauseSignal.signal();
}
status_t Camera3Device::RequestThread::waitUntilPaused(nsecs_t timeout) {
status_t res;
Mutex::Autolock l(mPauseLock);
while (!mPaused) {
res = mPausedSignal.waitRelative(mPauseLock, timeout);
if (res == TIMED_OUT) {
return res;
}
}
return OK;
}
status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
int32_t requestId, nsecs_t timeout) {
Mutex::Autolock l(mLatestRequestMutex);
status_t res;
while (mLatestRequestId != requestId) {
nsecs_t startTime = systemTime();
res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
if (res != OK) return res;
timeout -= (systemTime() - startTime);
}
return OK;
}
bool Camera3Device::RequestThread::threadLoop() {
status_t res;
// Handle paused state.
if (waitIfPaused()) {
return true;
}
// Get work to do
sp<CaptureRequest> nextRequest = waitForNextRequest();
if (nextRequest == NULL) {
return true;
}
// Create request to HAL
camera3_capture_request_t request = camera3_capture_request_t();
Vector<camera3_stream_buffer_t> outputBuffers;
// Insert any queued triggers (before metadata is locked)
int32_t triggerCount;
res = insertTriggers(nextRequest);
if (res < 0) {
SET_ERR("RequestThread: Unable to insert triggers "
"(capture request %d, HAL device: %s (%d)",
(mFrameNumber+1), strerror(-res), res);
cleanUpFailedRequest(request, nextRequest, outputBuffers);
return false;
}
triggerCount = res;
bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
// If the request is the same as last, or we had triggers last time
if (mPrevRequest != nextRequest || triggersMixedIn) {
/**
* The request should be presorted so accesses in HAL
* are O(logn). Sidenote, sorting a sorted metadata is nop.
*/
nextRequest->mSettings.sort();
request.settings = nextRequest->mSettings.getAndLock();
mPrevRequest = nextRequest;
ALOGVV("%s: Request settings are NEW", __FUNCTION__);
IF_ALOGV() {
camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
find_camera_metadata_ro_entry(
request.settings,
ANDROID_CONTROL_AF_TRIGGER,
&e
);
if (e.count > 0) {
ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
__FUNCTION__,
mFrameNumber+1,
e.data.u8[0]);
}
}
} else {
// leave request.settings NULL to indicate 'reuse latest given'
ALOGVV("%s: Request settings are REUSED",
__FUNCTION__);
}
camera3_stream_buffer_t inputBuffer;
// Fill in buffers
if (nextRequest->mInputStream != NULL) {
request.input_buffer = &inputBuffer;
res = nextRequest->mInputStream->getBuffer(&inputBuffer);
if (res != OK) {
SET_ERR("RequestThread: Can't get input buffer, skipping request:"
" %s (%d)", strerror(-res), res);
cleanUpFailedRequest(request, nextRequest, outputBuffers);
return true;
}
} else {
request.input_buffer = NULL;
}
outputBuffers.insertAt(camera3_stream_buffer_t(), 0,
nextRequest->mOutputStreams.size());
request.output_buffers = outputBuffers.array();
for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) {
res = nextRequest->mOutputStreams.editItemAt(i)->
getBuffer(&outputBuffers.editItemAt(i));
if (res != OK) {
SET_ERR("RequestThread: Can't get output buffer, skipping request:"
"%s (%d)", strerror(-res), res);
cleanUpFailedRequest(request, nextRequest, outputBuffers);
return true;
}
request.num_output_buffers++;
}
request.frame_number = mFrameNumber++;
// Log request in the in-flight queue
sp<Camera3Device> parent = mParent.promote();
if (parent == NULL) {
CLOGE("RequestThread: Parent is gone");
cleanUpFailedRequest(request, nextRequest, outputBuffers);
return false;
}
res = parent->registerInFlight(request.frame_number,
request.num_output_buffers);
if (res != OK) {
SET_ERR("RequestThread: Unable to register new in-flight request:"
" %s (%d)", strerror(-res), res);
cleanUpFailedRequest(request, nextRequest, outputBuffers);
return false;
}
// Submit request and block until ready for next one
res = mHal3Device->ops->process_capture_request(mHal3Device, &request);
if (res != OK) {
SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
" device: %s (%d)", request.frame_number, strerror(-res), res);
cleanUpFailedRequest(request, nextRequest, outputBuffers);
return false;
}
if (request.settings != NULL) {
nextRequest->mSettings.unlock(request.settings);
}
// Remove any previously queued triggers (after unlock)
res = removeTriggers(mPrevRequest);
if (res != OK) {
SET_ERR("RequestThread: Unable to remove triggers "
"(capture request %d, HAL device: %s (%d)",
request.frame_number, strerror(-res), res);
return false;
}
mPrevTriggers = triggerCount;
// Read android.request.id from the request settings metadata
// - inform waitUntilRequestProcessed thread of a new request ID
{
Mutex::Autolock al(mLatestRequestMutex);
camera_metadata_entry_t requestIdEntry =
nextRequest->mSettings.find(ANDROID_REQUEST_ID);
if (requestIdEntry.count > 0) {
mLatestRequestId = requestIdEntry.data.i32[0];
} else {
ALOGW("%s: Did not have android.request.id set in the request",
__FUNCTION__);
mLatestRequestId = NAME_NOT_FOUND;
}
mLatestRequestSignal.signal();
}
return true;
}
void Camera3Device::RequestThread::cleanUpFailedRequest(
camera3_capture_request_t &request,
sp<CaptureRequest> &nextRequest,
Vector<camera3_stream_buffer_t> &outputBuffers) {
if (request.settings != NULL) {
nextRequest->mSettings.unlock(request.settings);
}
if (request.input_buffer != NULL) {
request.input_buffer->status = CAMERA3_BUFFER_STATUS_ERROR;
nextRequest->mInputStream->returnBuffer(*(request.input_buffer), 0);
}
for (size_t i = 0; i < request.num_output_buffers; i++) {
outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
nextRequest->mOutputStreams.editItemAt(i)->returnBuffer(
outputBuffers[i], 0);
}
}
sp<Camera3Device::CaptureRequest>
Camera3Device::RequestThread::waitForNextRequest() {
status_t res;
sp<CaptureRequest> nextRequest;
// Optimized a bit for the simple steady-state case (single repeating
// request), to avoid putting that request in the queue temporarily.
Mutex::Autolock l(mRequestLock);
while (mRequestQueue.empty()) {
if (!mRepeatingRequests.empty()) {
// Always atomically enqueue all requests in a repeating request
// list. Guarantees a complete in-sequence set of captures to
// application.
const RequestList &requests = mRepeatingRequests;
RequestList::const_iterator firstRequest =
requests.begin();
nextRequest = *firstRequest;
mRequestQueue.insert(mRequestQueue.end(),
++firstRequest,
requests.end());
// No need to wait any longer
break;
}
res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
if (res == TIMED_OUT) {
// Signal that we're paused by starvation
Mutex::Autolock pl(mPauseLock);
if (mPaused == false) {
mPaused = true;
mPausedSignal.signal();
}
// Stop waiting for now and let thread management happen
return NULL;
}
}
if (nextRequest == NULL) {
// Don't have a repeating request already in hand, so queue
// must have an entry now.
RequestList::iterator firstRequest =
mRequestQueue.begin();
nextRequest = *firstRequest;
mRequestQueue.erase(firstRequest);
}
// Not paused
Mutex::Autolock pl(mPauseLock);
mPaused = false;
// Check if we've reconfigured since last time, and reset the preview
// request if so. Can't use 'NULL request == repeat' across configure calls.
if (mReconfigured) {
mPrevRequest.clear();
mReconfigured = false;
}
return nextRequest;
}
bool Camera3Device::RequestThread::waitIfPaused() {
status_t res;
Mutex::Autolock l(mPauseLock);
while (mDoPause) {
// Signal that we're paused by request
if (mPaused == false) {
mPaused = true;
mPausedSignal.signal();
}
res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
if (res == TIMED_OUT) {
return true;
}
}
// We don't set mPaused to false here, because waitForNextRequest needs
// to further manage the paused state in case of starvation.
return false;
}
void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
sp<Camera3Device> parent = mParent.promote();
if (parent != NULL) {
va_list args;
va_start(args, fmt);
parent->setErrorStateV(fmt, args);
va_end(args);
}
}
status_t Camera3Device::RequestThread::insertTriggers(
const sp<CaptureRequest> &request) {
Mutex::Autolock al(mTriggerMutex);
CameraMetadata &metadata = request->mSettings;
size_t count = mTriggerMap.size();
for (size_t i = 0; i < count; ++i) {
RequestTrigger trigger = mTriggerMap.valueAt(i);
uint32_t tag = trigger.metadataTag;
camera_metadata_entry entry = metadata.find(tag);
if (entry.count > 0) {
/**
* Already has an entry for this trigger in the request.
* Rewrite it with our requested trigger value.
*/
RequestTrigger oldTrigger = trigger;
oldTrigger.entryValue = entry.data.u8[0];
mTriggerReplacedMap.add(tag, oldTrigger);
} else {
/**
* More typical, no trigger entry, so we just add it
*/
mTriggerRemovedMap.add(tag, trigger);
}
status_t res;
switch (trigger.getTagType()) {
case TYPE_BYTE: {
uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
res = metadata.update(tag,
&entryValue,
/*count*/1);
break;
}
case TYPE_INT32:
res = metadata.update(tag,
&trigger.entryValue,
/*count*/1);
break;
default:
ALOGE("%s: Type not supported: 0x%x",
__FUNCTION__,
trigger.getTagType());
return INVALID_OPERATION;
}
if (res != OK) {
ALOGE("%s: Failed to update request metadata with trigger tag %s"
", value %d", __FUNCTION__, trigger.getTagName(),
trigger.entryValue);
return res;
}
ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
trigger.getTagName(),
trigger.entryValue);
}
mTriggerMap.clear();
return count;
}
status_t Camera3Device::RequestThread::removeTriggers(
const sp<CaptureRequest> &request) {
Mutex::Autolock al(mTriggerMutex);
CameraMetadata &metadata = request->mSettings;
/**
* Replace all old entries with their old values.
*/
for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
status_t res;
uint32_t tag = trigger.metadataTag;
switch (trigger.getTagType()) {
case TYPE_BYTE: {
uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
res = metadata.update(tag,
&entryValue,
/*count*/1);
break;
}
case TYPE_INT32:
res = metadata.update(tag,
&trigger.entryValue,
/*count*/1);
break;
default:
ALOGE("%s: Type not supported: 0x%x",
__FUNCTION__,
trigger.getTagType());
return INVALID_OPERATION;
}
if (res != OK) {
ALOGE("%s: Failed to restore request metadata with trigger tag %s"
", trigger value %d", __FUNCTION__,
trigger.getTagName(), trigger.entryValue);
return res;
}
}
mTriggerReplacedMap.clear();
/**
* Remove all new entries.
*/
for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
status_t res = metadata.erase(trigger.metadataTag);
if (res != OK) {
ALOGE("%s: Failed to erase metadata with trigger tag %s"
", trigger value %d", __FUNCTION__,
trigger.getTagName(), trigger.entryValue);
return res;
}
}
mTriggerRemovedMap.clear();
return OK;
}
/**
* Static callback forwarding methods from HAL to instance
*/
void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
const camera3_capture_result *result) {
Camera3Device *d =
const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
d->processCaptureResult(result);
}
void Camera3Device::sNotify(const camera3_callback_ops *cb,
const camera3_notify_msg *msg) {
Camera3Device *d =
const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
d->notify(msg);
}
}; // namespace android
|