Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06bd9d775d | ||
|
|
d6487e24c9 | ||
|
|
c404589382 | ||
|
|
f1689a7794 | ||
|
|
a861a4110f | ||
|
|
e7809b3160 | ||
|
|
edd0618e64 | ||
|
|
849e62df7e | ||
|
|
e1c0df3bd7 | ||
|
|
349b5b0513 | ||
|
|
3ad049cb28 | ||
|
|
656cf1158b | ||
|
|
f3cb508649 | ||
|
|
c39b5a5cf1 | ||
|
|
9ff3099a9d | ||
|
|
c24a2aade0 | ||
|
|
8f862d1ca0 | ||
|
|
b56608f94f | ||
|
|
2876e1bf78 | ||
|
|
ebd850b0d5 | ||
|
|
f3f962a7c9 | ||
|
|
49ae1fdc34 | ||
|
|
dc769bda41 | ||
|
|
75ba6b0627 | ||
|
|
1e40d21bd8 | ||
|
|
3c43874342 | ||
|
|
4f422f1485 | ||
|
|
85d9b6ebab | ||
|
|
90662e2173 | ||
|
|
24980aff95 | ||
|
|
804261605b | ||
|
|
8a65c78999 | ||
|
|
979db254d1 | ||
|
|
18ebe77806 | ||
|
|
0de856e929 | ||
|
|
a6d82b4637 | ||
|
|
acfb79c857 | ||
|
|
dcfe0f8308 | ||
|
|
23a423fe85 | ||
|
|
b2cb874b73 | ||
|
|
f671f367ea | ||
|
|
665603b314 | ||
|
|
0d7dd093c4 | ||
|
|
c849a213f0 | ||
|
|
49ff0854c0 | ||
|
|
5047057521 | ||
|
|
e28e2b9371 | ||
|
|
bb92b6083b | ||
|
|
acdae74587 | ||
|
|
5e4449247b | ||
|
|
c2fe142293 | ||
|
|
431b0f9b0c | ||
|
|
959e6e9398 | ||
|
|
18e47d2327 | ||
|
|
b2e5e02204 | ||
|
|
e6a488a4e2 | ||
|
|
75d0164a8b | ||
|
|
05251edaf3 | ||
|
|
892dfee381 | ||
|
|
7f1eb3a818 | ||
|
|
bd0a0c5d6b | ||
|
|
71b05fd4b2 | ||
|
|
587609d7f6 | ||
|
|
cceba28d0a | ||
|
|
03c623e8c7 | ||
|
|
2b34f4a9d7 | ||
|
|
ad3cc6b986 | ||
|
|
133db721a2 | ||
|
|
a03d30fa45 | ||
|
|
62abd3c30a | ||
|
|
97ba02f45e | ||
|
|
0f1bf5e011 | ||
|
|
d816d82a38 | ||
|
|
c89c88647e | ||
|
|
3599b0b0e1 | ||
|
|
1adb89c6b3 | ||
|
|
7ec1c2ebdc | ||
|
|
7ec062deaf | ||
|
|
a5c7d5b52a | ||
|
|
e54bbd11f1 | ||
|
|
38afdab2e4 | ||
|
|
f214c50c15 | ||
|
|
1fc081ed6b | ||
|
|
cbaed8cdfb | ||
|
|
eac0e26696 | ||
|
|
77af810d1f | ||
|
|
1292d7ac34 | ||
|
|
e75ab94eb9 | ||
|
|
804bea8e9a | ||
|
|
0502dd7ba0 | ||
|
|
3221a0cb1a | ||
|
|
e7efa458e5 | ||
|
|
9b48f26463 | ||
|
|
903b8eced8 | ||
|
|
3753967caf | ||
|
|
516925cf50 | ||
|
|
cd9498abb8 | ||
|
|
18642cae15 | ||
|
|
92063bd58f | ||
|
|
726281ed44 | ||
|
|
e02daa89b8 | ||
|
|
7de7802368 | ||
|
|
d44a8994ce | ||
|
|
42d9168941 | ||
|
|
38616770e5 | ||
|
|
bf7558f80d | ||
|
|
381e82d61a | ||
|
|
9cebcb97c5 | ||
|
|
eef73e6447 | ||
|
|
e8df18e7b2 | ||
|
|
54512b8f93 | ||
|
|
1e0988e381 | ||
|
|
8efd8f1dc8 | ||
|
|
38868e0078 | ||
|
|
273d0c7985 | ||
|
|
4728564e0c | ||
|
|
489bf914af | ||
|
|
248b5fd91a | ||
|
|
bbf7b1f9da | ||
|
|
83899a38f3 | ||
|
|
cda4c1e78a | ||
|
|
01e5814943 | ||
|
|
3cca29512d | ||
|
|
8139fc2b17 | ||
|
|
1ef4032666 | ||
|
|
4c4b18e2cd | ||
|
|
f74314bbf0 | ||
|
|
32421e4c84 | ||
|
|
d90cc61541 | ||
|
|
6b3e49d410 | ||
|
|
a9b812f66c | ||
|
|
0fd0506551 | ||
|
|
e6ca5f254d | ||
|
|
de3219abb9 | ||
|
|
8201d8dcda | ||
|
|
aed420525c | ||
|
|
75b1c86306 | ||
|
|
43012da2b8 | ||
|
|
145881318e | ||
|
|
79c06b82d3 | ||
|
|
e5bbdc06f9 | ||
|
|
0e7ff609b6 | ||
|
|
f3e108e867 | ||
|
|
92bfae322e | ||
|
|
08491511e9 | ||
|
|
24b5080c38 | ||
|
|
985c279b1f | ||
|
|
cb2e56442d | ||
|
|
a425798bae | ||
|
|
1020188883 | ||
|
|
caf192fd78 | ||
|
|
74b8dc4561 | ||
|
|
7b59dac26b | ||
|
|
09f5121732 | ||
|
|
8f9d20a2e4 | ||
|
|
273f129b68 | ||
|
|
483c0b504e | ||
|
|
7c38668a51 | ||
|
|
eba553413c | ||
|
|
f8658027b8 | ||
|
|
58bceb29cb | ||
|
|
c5d8f9c62b | ||
|
|
4ffa3d30f6 | ||
|
|
d5c8778074 | ||
|
|
c6c76d6828 | ||
|
|
9cfc6c0f4a | ||
|
|
2eae450aa0 | ||
|
|
1b5334e72f | ||
|
|
e3db54940d | ||
|
|
656d512858 | ||
|
|
d9135e0d25 | ||
|
|
4f636dfffd | ||
|
|
6438b444bf | ||
|
|
8413e1e5a7 | ||
|
|
5671f6e5d1 | ||
|
|
a4a0475fdb | ||
|
|
9a740b91c1 | ||
|
|
63ab80fa82 | ||
|
|
0bb085c70c | ||
|
|
9825ce3c7c | ||
|
|
f5012b36ea | ||
|
|
6111c381af | ||
|
|
00fce3a997 | ||
|
|
b8417f0277 | ||
|
|
4148c1c8ff | ||
|
|
9e5098f356 | ||
|
|
139eed9ca9 | ||
|
|
23efb02636 | ||
|
|
294996eac1 | ||
|
|
a4f0b92b4e | ||
|
|
7cac050500 | ||
|
|
1685ecc991 | ||
|
|
a71711de5f | ||
|
|
7534a6c60a | ||
|
|
dba01f14bb | ||
|
|
d93ea9813f | ||
|
|
7501f461b9 | ||
|
|
5e5702c961 | ||
|
|
4b477a4fe3 | ||
|
|
50ff514be8 | ||
|
|
1c7a083d6c | ||
|
|
097e48d705 | ||
|
|
a931d5910b | ||
|
|
1cd585eecb | ||
|
|
9981b277c6 | ||
|
|
2b7ea5fe02 | ||
|
|
47276e1bac | ||
|
|
c8670a8d6a | ||
|
|
9cc32e125b | ||
|
|
4217da1a8f | ||
|
|
704c37f97f | ||
|
|
0c8e0fc2ec | ||
|
|
d6315a0f75 | ||
|
|
92cdbdd723 | ||
|
|
3939ba809f | ||
|
|
6642348a96 | ||
|
|
0b29673a5e | ||
|
|
3747a74cb3 | ||
|
|
bcb7f1d3c1 | ||
|
|
7b56b90f24 | ||
|
|
ba62129414 | ||
|
|
e559a6125d | ||
|
|
869b4fe230 | ||
|
|
3b4110d7e5 | ||
|
|
7b4e399013 | ||
|
|
5788d93e89 | ||
|
|
08a806e457 | ||
|
|
e45bfadc14 | ||
|
|
56cfb95af5 | ||
|
|
8e8942fb36 | ||
|
|
02f2657d18 | ||
|
|
39709e5c42 | ||
|
|
a101ee76d6 | ||
|
|
4eadec5b17 | ||
|
|
be86a33057 | ||
|
|
ce19b9dfa7 | ||
|
|
15cc85147a | ||
|
|
3fc3baef83 | ||
|
|
91b926acac | ||
|
|
8b2ff18842 | ||
|
|
1958f8ca7e | ||
|
|
8e53232961 | ||
|
|
cec8993b80 | ||
|
|
366ae67341 | ||
|
|
50be8565d9 | ||
|
|
9365fcf246 | ||
|
|
8d4ef2757a | ||
|
|
6b147e2053 | ||
|
|
5fa8326341 | ||
|
|
c8cded70ef | ||
|
|
8fe51075be | ||
|
|
d24c95f1e1 | ||
|
|
1c8be031ae | ||
|
|
83c47b529c | ||
|
|
9dce396fb4 | ||
|
|
eeaa831cc2 | ||
|
|
f1a02ade17 | ||
|
|
dcd0b03096 | ||
|
|
a189ee5774 | ||
|
|
e74df0d245 | ||
|
|
d980540c09 | ||
|
|
a51215952f | ||
|
|
993a0e4666 | ||
|
|
4c43d6fdec | ||
|
|
1c58a12c90 | ||
|
|
b6d23ed089 | ||
|
|
3a042d79f6 | ||
|
|
1a73fc585b | ||
|
|
8ec2795da1 | ||
|
|
cbea1c8d8f | ||
|
|
048d22cb99 | ||
|
|
31c01ab3e0 | ||
|
|
16e31303ae | ||
|
|
e301fec38c | ||
|
|
e1e9adbb01 | ||
|
|
636ecc9d3a | ||
|
|
fc231a9e72 | ||
|
|
c354193187 | ||
|
|
bb7ed72073 | ||
|
|
fea973a72a | ||
|
|
487c7b87f6 | ||
|
|
afc94a50fc | ||
|
|
2ebd730201 | ||
|
|
0dd7d7c522 | ||
|
|
eaf0f4fa1a | ||
|
|
743a8668ec | ||
|
|
6a74ff083f | ||
|
|
9dc3a1a1b1 | ||
|
|
2b45557743 | ||
|
|
11b97e626e | ||
|
|
d8f69f7acd | ||
|
|
b547f8a47f | ||
|
|
f4c83bedc0 | ||
|
|
0582ab2947 | ||
|
|
209101796b | ||
|
|
448a5d084c | ||
|
|
1ebfee9354 | ||
|
|
29e0654d47 | ||
|
|
f565684842 | ||
|
|
5d6f34f756 | ||
|
|
73735c5a00 | ||
|
|
c93a266722 | ||
|
|
2b167a60f5 | ||
|
|
63e807dd58 | ||
|
|
16e3500c49 | ||
|
|
6e47a5fbcf | ||
|
|
b18774d60b | ||
|
|
0383a77b56 | ||
|
|
d58007a9e2 | ||
|
|
7d60875e19 | ||
|
|
6be1b7c486 | ||
|
|
88c65e1857 | ||
|
|
95ff95d397 | ||
|
|
1978d710da | ||
|
|
423be62218 | ||
|
|
d2650667b8 | ||
|
|
48cf8accfa | ||
|
|
565885cc1e | ||
|
|
d0e74151b8 | ||
|
|
89c9c6c49b | ||
|
|
e98d7febdd | ||
|
|
55ee2c270d | ||
|
|
81b05f00df | ||
|
|
f4f2571168 | ||
|
|
d85a622fbe | ||
|
|
d3e8dcef86 | ||
|
|
e9c93415a8 | ||
|
|
68e27fdbb3 | ||
|
|
a679bae354 | ||
|
|
5a68711f7b | ||
|
|
324d145292 | ||
|
|
d004342c98 | ||
|
|
d3d7957b62 | ||
|
|
0e94558548 | ||
|
|
8d14a14781 | ||
|
|
20f704a56d | ||
|
|
93f0da7a27 | ||
|
|
8b3f8856f7 | ||
|
|
39fb828580 | ||
|
|
3e0f7b4f86 | ||
|
|
7e9f62dc7f | ||
|
|
c855dba3be | ||
|
|
e726f9f528 | ||
|
|
2c54baca34 | ||
|
|
232d98c4ce | ||
|
|
d93c81a7cb | ||
|
|
326d53415b | ||
|
|
87db591792 | ||
|
|
6bad454830 | ||
|
|
cfd4aa307d | ||
|
|
3798a0c332 | ||
|
|
be0e9686b5 | ||
|
|
7ec45274bd | ||
|
|
3e74937386 | ||
|
|
310c4280fc | ||
|
|
ee6e327b12 | ||
|
|
e71dcdaa6c | ||
|
|
1b969953b5 | ||
|
|
7690a16efe | ||
|
|
91298294b0 | ||
|
|
5df3ec0c12 | ||
|
|
ef4980db09 | ||
|
|
e37602421b | ||
|
|
562d19c207 | ||
|
|
e54bbb2214 | ||
|
|
db2a2c34d2 | ||
|
|
12b006ee0c | ||
|
|
be3efa8335 | ||
|
|
d1d549d602 | ||
|
|
7de2a62c55 | ||
|
|
7b4a37e576 | ||
|
|
5a46857035 | ||
|
|
7ffb20b501 | ||
|
|
856ac83e6a | ||
|
|
fb8fc1db1c | ||
|
|
76e8ea6901 | ||
|
|
e8c27f00a7 | ||
|
|
9f19f550c3 | ||
|
|
fce794cd6c | ||
|
|
8f9947a874 | ||
|
|
126e6b9349 | ||
|
|
fcbe459177 | ||
|
|
0e296f8659 | ||
|
|
12073ea134 | ||
|
|
8aea796dbd | ||
|
|
9af6f32157 | ||
|
|
b0f1a5d4f1 | ||
|
|
de62c8530f | ||
|
|
0f4629f52b | ||
|
|
de129fbb0a | ||
|
|
3a01fa25a7 | ||
|
|
86c19fc1fc | ||
|
|
ae1f6d7822 | ||
|
|
4577f26aa8 | ||
|
|
fd26f470a5 | ||
|
|
bae127e459 | ||
|
|
606627cd0c | ||
|
|
3ddd89113c | ||
|
|
5139e39ed4 | ||
|
|
3a6012cc21 | ||
|
|
37b1a26cde | ||
|
|
e5922f4870 | ||
|
|
ae7f4a7871 | ||
|
|
9e85aa7be6 | ||
|
|
fd69fe668a | ||
|
|
9085d4d94b | ||
|
|
0775ea0d26 | ||
|
|
d901f5efc2 | ||
|
|
fcd8198fcb | ||
|
|
fd1eaf9d96 | ||
|
|
d0bd919ff4 | ||
|
|
2bbd31d927 | ||
|
|
617f200cb5 | ||
|
|
b96d734e8c | ||
|
|
89f256138d | ||
|
|
9b248a7a5b | ||
|
|
8d76dff353 | ||
|
|
eff75d2029 | ||
|
|
f9615491b3 | ||
|
|
4252bd88e9 | ||
|
|
00917a0393 | ||
|
|
4cdcd2f2e4 | ||
|
|
27006cfa99 | ||
|
|
bdbd667584 | ||
|
|
4b243d38b9 | ||
|
|
cd31b2e2e6 | ||
|
|
f185ebd554 | ||
|
|
7d679c9d78 | ||
|
|
17184881f3 | ||
|
|
a39a2a25eb | ||
|
|
e0f1695260 | ||
|
|
d0ffd49f69 | ||
|
|
bfb6aa01b9 | ||
|
|
6f273b0aa8 | ||
|
|
3a93ec80ec | ||
|
|
dd0fd1c828 | ||
|
|
ec93062600 | ||
|
|
822333bf34 | ||
|
|
ffc20b26d4 | ||
|
|
3a612df3d3 | ||
|
|
afda61119e | ||
|
|
bb66ab6526 | ||
|
|
ec2b94e367 | ||
|
|
5401b5005f | ||
|
|
d38f7cf78f | ||
|
|
633ce11c88 | ||
|
|
7a3f63683e | ||
|
|
3e6ebcdb6a | ||
|
|
c38c0cf55d | ||
|
|
5d2302b322 | ||
|
|
51a8b971f6 | ||
|
|
3319df4538 | ||
|
|
1e6bd01987 | ||
|
|
e10cc7d273 | ||
|
|
19dea4b31e | ||
|
|
653fada5dc | ||
|
|
65b42bca3f | ||
|
|
5fe5534bae | ||
|
|
f07feaaa52 | ||
|
|
92014404f5 | ||
|
|
e2a7a7ab4b | ||
|
|
cedd448ef2 | ||
|
|
2208d6c637 | ||
|
|
187eeb19d3 | ||
|
|
955c75db60 | ||
|
|
9446f976a4 | ||
|
|
7988c83bec | ||
|
|
ebec3ad20c | ||
|
|
3b18b44cd2 | ||
|
|
cf4fc74d68 | ||
|
|
c75c87f527 | ||
|
|
e71c39271c | ||
|
|
de547884f8 | ||
|
|
4700cc5bd4 | ||
|
|
07d25f5d5f | ||
|
|
1f09c07e96 | ||
|
|
e8769e7059 | ||
|
|
88430ba7b6 | ||
|
|
25a2187bf4 | ||
|
|
fb084d3ea1 | ||
|
|
da7aef4548 | ||
|
|
91c23786f2 | ||
|
|
18a5041334 | ||
|
|
94dbae0af9 | ||
|
|
05c4d6dff3 | ||
|
|
ef2db78310 | ||
|
|
955bc9548c | ||
|
|
ef8026797c | ||
|
|
ed4be7b96d | ||
|
|
fdaff3687d | ||
|
|
f573eda657 | ||
|
|
708a1391e3 | ||
|
|
9e4230597f | ||
|
|
720d0d2604 | ||
|
|
dee12ac336 | ||
|
|
5f9f0964b2 | ||
|
|
bf89925d6a | ||
|
|
aa6e9648bb | ||
|
|
c4b9da0950 | ||
|
|
c7b023222c | ||
|
|
060926b749 | ||
|
|
aa3c83bad1 | ||
|
|
70606c8ac5 | ||
|
|
5010833da9 | ||
|
|
f5901389e0 | ||
|
|
11e1a1464e | ||
|
|
2664caf004 | ||
|
|
8594a7bc52 | ||
|
|
8a7d767e54 | ||
|
|
d09893470f | ||
|
|
a40879849b | ||
|
|
20953152b6 | ||
|
|
876a44b244 | ||
|
|
e9a706fa72 | ||
|
|
8820c0e059 | ||
|
|
45770e1ad6 | ||
|
|
afdec05dbf | ||
|
|
81e036dc4f | ||
|
|
8555254e81 | ||
|
|
1781fc06ae | ||
|
|
810f1e5da5 | ||
|
|
244b291255 | ||
|
|
7fc136f592 | ||
|
|
130e0d6f40 | ||
|
|
8fabf56337 | ||
|
|
b1e218f0ad | ||
|
|
624e8a2991 | ||
|
|
0ac5f49e5e | ||
|
|
de6f8d6cb6 | ||
|
|
b42ee26840 | ||
|
|
50bc245677 | ||
|
|
646832c6b1 | ||
|
|
43242673fb | ||
|
|
87aa7d9d81 | ||
|
|
91d9aad721 | ||
|
|
221902c946 | ||
|
|
8a8c2ecb87 | ||
|
|
f6c6808352 | ||
|
|
036d99f11f | ||
|
|
e78f7cee5e | ||
|
|
f03c84e8dc | ||
|
|
d5a12c404a | ||
|
|
dc74300ef5 | ||
|
|
b2c3fe61b3 | ||
|
|
97e65a811c | ||
|
|
d9d66fe54e | ||
|
|
ed7dae601a | ||
|
|
024af35bf5 | ||
|
|
9bd5732f2b | ||
|
|
117d1b8882 | ||
|
|
f6aad1b8fc | ||
|
|
c602936d2a | ||
|
|
a351ca70ba | ||
|
|
396a5a8453 | ||
|
|
db6d5cadd9 | ||
|
|
5568266c99 | ||
|
|
a605db31f9 | ||
|
|
35ca723c20 | ||
|
|
7057ee93ac | ||
|
|
6cde5b6bd1 | ||
|
|
08564bba20 | ||
|
|
495f2e3640 | ||
|
|
31d2d9dc98 | ||
|
|
68d34f81a0 | ||
|
|
e733a0abc7 | ||
|
|
c800baeb25 | ||
|
|
4080c812d2 |
@@ -0,0 +1,9 @@
|
||||
BasedOnStyle: Google
|
||||
AlignAfterOpenBracket: AlwaysBreak
|
||||
ColumnLimit: 120
|
||||
IndentWidth: 2
|
||||
ContinuationIndentWidth: 4
|
||||
DerivePointerAlignment: false
|
||||
LineEnding: LF
|
||||
PointerAlignment: Left
|
||||
SortIncludes: true
|
||||
@@ -0,0 +1,28 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.{c,cc,cpp,h,hpp,m,mm}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.dart]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.{kt,kts,java}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
|
||||
ktlint_code_style = android_studio
|
||||
ktlint_standard_max-line-length = disabled
|
||||
ktlint_standard_no-wildcard-imports = disabled
|
||||
ktlint_standard_property-naming = disabled
|
||||
|
||||
[*.swift]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
@@ -68,16 +68,31 @@ body:
|
||||
- Windows
|
||||
- macOS
|
||||
- Android TV
|
||||
- tvOS
|
||||
- Linux
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: media-server
|
||||
attributes:
|
||||
label: Media Server
|
||||
description: Are you using Jellyfin or Plex?
|
||||
multiple: true
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: device
|
||||
attributes:
|
||||
label: Device Information
|
||||
description: What device are you using?
|
||||
placeholder: e.g., iPhone 14 Pro, Pixel 7, Chrome on macOS
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
|
||||
@@ -41,6 +41,8 @@ body:
|
||||
1. As a user, I would...
|
||||
2. This would help me...
|
||||
3. The benefit would be...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: platform
|
||||
@@ -54,8 +56,23 @@ body:
|
||||
- Windows
|
||||
- macOS
|
||||
- Android TV
|
||||
- tvOS
|
||||
- Linux
|
||||
- All platforms
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: media-server
|
||||
attributes:
|
||||
label: Media Server
|
||||
description: Which media server(s) is this for?
|
||||
multiple: true
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
|
||||
@@ -2,15 +2,45 @@ name: Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_android:
|
||||
description: Build Android
|
||||
default: true
|
||||
type: boolean
|
||||
build_ios:
|
||||
description: Build iOS
|
||||
default: true
|
||||
type: boolean
|
||||
build_macos:
|
||||
description: Build macOS
|
||||
default: true
|
||||
type: boolean
|
||||
build_windows:
|
||||
description: Build Windows
|
||||
default: true
|
||||
type: boolean
|
||||
build_linux:
|
||||
description: Build Linux
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
env:
|
||||
SENTRY_DART_DEFINE: ${{ github.repository == 'edde746/plezy' && '--dart-define=ENABLE_SENTRY=true' || '' }}
|
||||
GIT_COMMIT_DART_DEFINE: --dart-define=GIT_COMMIT=${{ github.sha }}
|
||||
SENTRY_ENV_DART_DEFINE: --dart-define=SENTRY_ENVIRONMENT=github
|
||||
DONATIONS_DART_DEFINE: --dart-define=ENABLE_DONATIONS=true
|
||||
LINUX_APT_PACKAGES: >
|
||||
clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev
|
||||
libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev
|
||||
libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev
|
||||
libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev
|
||||
libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev
|
||||
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
|
||||
ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
if: ${{ inputs.build_android }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -29,16 +59,16 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache Gradle
|
||||
uses: actions/cache@v4
|
||||
@@ -51,7 +81,7 @@ jobs:
|
||||
${{ runner.os }}-gradle-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Configure Android signing
|
||||
run: |
|
||||
@@ -64,39 +94,14 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Build APKs
|
||||
run: flutter build apk --release --split-per-abi --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --obfuscate --split-debug-info=debug-info/android-apk
|
||||
run: flutter build apk --release --split-per-abi --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-android-apk ${{ env.DONATIONS_DART_DEFINE }} --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/android-apk"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/android-apk" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/android-apk" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/app/intermediates/merged_native_libs" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/app/intermediates/merged_native_libs -name '*.so' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-android-apk
|
||||
path: symbol-inputs/android-apk
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-android-apk
|
||||
run: ./scripts/upload-symbols.sh android-apk
|
||||
|
||||
- name: Clean up keystore
|
||||
if: always()
|
||||
@@ -126,6 +131,7 @@ jobs:
|
||||
plezy-android-x86_64.tar.gz
|
||||
|
||||
build-ios:
|
||||
if: ${{ inputs.build_ios }}
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -138,16 +144,16 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache CocoaPods
|
||||
uses: actions/cache@v4
|
||||
@@ -161,42 +167,17 @@ jobs:
|
||||
${{ runner.os }}-pods-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build iOS (no codesign)
|
||||
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/ios
|
||||
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-ios ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/ios
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/ios"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/ios" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/ios" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/ios" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/ios -path '*.dSYM/Contents/Resources/DWARF/*' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-ios
|
||||
path: symbol-inputs/ios
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-ios
|
||||
run: ./scripts/upload-symbols.sh ios
|
||||
|
||||
- name: Create IPA
|
||||
run: |
|
||||
@@ -216,6 +197,7 @@ jobs:
|
||||
path: plezy-ios.ipa
|
||||
|
||||
build-macos:
|
||||
if: ${{ inputs.build_macos }}
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -228,16 +210,16 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache CocoaPods
|
||||
uses: actions/cache@v4
|
||||
@@ -251,42 +233,17 @@ jobs:
|
||||
${{ runner.os }}-macos-pods-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build macOS
|
||||
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/macos
|
||||
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-macos ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/macos
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/macos"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/macos" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/macos" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/macos/Build/Products/Release" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/macos/Build/Products/Release -path '*.dSYM/Contents/Resources/DWARF/*' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-macos
|
||||
path: symbol-inputs/macos
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-macos
|
||||
run: ./scripts/upload-symbols.sh macos
|
||||
|
||||
- name: Import Code Signing Certificate
|
||||
env:
|
||||
@@ -342,6 +299,11 @@ jobs:
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
echo "Verifying signature..."
|
||||
codesign -dvvv "$APP_PATH"
|
||||
echo "Verifying signed entitlements..."
|
||||
codesign -d --entitlements :- "$APP_PATH" > "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-jit" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-unsigned-executable-memory" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
|
||||
- name: Notarize Application
|
||||
@@ -412,6 +374,7 @@ jobs:
|
||||
macos-dmg-size.txt
|
||||
|
||||
build-windows-x64:
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -422,62 +385,36 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\AppData\Local\Pub\Cache
|
||||
key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache Windows native dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: build/windows/x64/_deps
|
||||
key: windows-native-x64-${{ hashFiles('windows/CMakeLists.txt') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build Windows x64
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-x64
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-x64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-x64
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
continue-on-error: true
|
||||
run: |
|
||||
$symbolRoot = 'symbol-inputs/windows-x64'
|
||||
Remove-Item -Path $symbolRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Path $symbolRoot -Force | Out-Null
|
||||
|
||||
$debugInfo = 'debug-info/windows-x64'
|
||||
if (Test-Path $debugInfo) {
|
||||
$debugInfoRoot = Join-Path $symbolRoot 'debug-info'
|
||||
New-Item -ItemType Directory -Path $debugInfoRoot -Force | Out-Null
|
||||
Copy-Item -Path $debugInfo -Destination $debugInfoRoot -Recurse -Force
|
||||
}
|
||||
|
||||
$pdbRoot = 'build/windows/x64/runner/Release'
|
||||
if (Test-Path $pdbRoot) {
|
||||
Get-ChildItem -Path $pdbRoot -Filter '*.pdb' -Recurse | ForEach-Object {
|
||||
$relative = [System.IO.Path]::GetRelativePath((Get-Location).Path, $_.FullName)
|
||||
$destination = Join-Path $symbolRoot $relative
|
||||
New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force | Out-Null
|
||||
Copy-Item -Path $_.FullName -Destination $destination -Force
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Get-ChildItem -Path $symbolRoot -File -Recurse)) {
|
||||
throw 'No symbol files staged'
|
||||
}
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-windows-x64
|
||||
path: symbol-inputs/windows-x64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-windows-x64
|
||||
run: .\scripts\upload-symbols.ps1 windows-x64
|
||||
|
||||
- name: Upload x64 build
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -486,75 +423,54 @@ jobs:
|
||||
path: build/windows/x64/runner/Release/
|
||||
|
||||
build-windows-arm64:
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-11-arm
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cache Windows native dependencies
|
||||
id: windows-native-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
build/windows/arm64/_deps
|
||||
build/windows/arm64/mpv-dev-arm64
|
||||
key: windows-native-arm64-${{ hashFiles('windows/CMakeLists.txt') }}
|
||||
|
||||
- name: Install 7-Zip
|
||||
if: steps.windows-native-cache.outputs.cache-hit != 'true'
|
||||
run: choco install 7zip -y
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "master"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\AppData\Local\Pub\Cache
|
||||
key: ${{ runner.os }}-arm64-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-arm64-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --no-example
|
||||
|
||||
- name: Build Windows arm64
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-arm64
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-arm64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-arm64
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
continue-on-error: true
|
||||
run: |
|
||||
$symbolRoot = 'symbol-inputs/windows-arm64'
|
||||
Remove-Item -Path $symbolRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Path $symbolRoot -Force | Out-Null
|
||||
|
||||
$debugInfo = 'debug-info/windows-arm64'
|
||||
if (Test-Path $debugInfo) {
|
||||
$debugInfoRoot = Join-Path $symbolRoot 'debug-info'
|
||||
New-Item -ItemType Directory -Path $debugInfoRoot -Force | Out-Null
|
||||
Copy-Item -Path $debugInfo -Destination $debugInfoRoot -Recurse -Force
|
||||
}
|
||||
|
||||
$pdbRoot = 'build/windows/arm64/runner/Release'
|
||||
if (Test-Path $pdbRoot) {
|
||||
Get-ChildItem -Path $pdbRoot -Filter '*.pdb' -Recurse | ForEach-Object {
|
||||
$relative = [System.IO.Path]::GetRelativePath((Get-Location).Path, $_.FullName)
|
||||
$destination = Join-Path $symbolRoot $relative
|
||||
New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force | Out-Null
|
||||
Copy-Item -Path $_.FullName -Destination $destination -Force
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Get-ChildItem -Path $symbolRoot -File -Recurse)) {
|
||||
throw 'No symbol files staged'
|
||||
}
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-windows-arm64
|
||||
path: symbol-inputs/windows-arm64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-windows-arm64
|
||||
run: .\scripts\upload-symbols.ps1 windows-arm64
|
||||
|
||||
- name: Upload arm64 build
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -564,6 +480,7 @@ jobs:
|
||||
|
||||
package-windows:
|
||||
needs: [build-windows-x64, build-windows-arm64]
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -646,6 +563,7 @@ jobs:
|
||||
win-installer-size.txt
|
||||
|
||||
build-linux-x64:
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -658,27 +576,38 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
packages: ${{ env.LINUX_APT_PACKAGES }}
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
read -r -a packages <<< "$LINUX_APT_PACKAGES"
|
||||
|
||||
for attempt in 1 2 3; do
|
||||
if sudo apt-get update -o Acquire::Retries=3 && sudo apt-get install -y -o Acquire::Retries=3 "${packages[@]}"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sudo apt-get clean
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
sleep $((attempt * 15))
|
||||
done
|
||||
|
||||
exit 1
|
||||
|
||||
- name: Cache libmpv build
|
||||
id: libmpv-cache
|
||||
@@ -695,44 +624,19 @@ jobs:
|
||||
run: sudo gem install fpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build Linux x64
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-x64
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-x64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-x64
|
||||
env:
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/x86_64-linux-gnu/pkgconfig
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/linux-x64"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/linux-x64" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/linux-x64" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/linux" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/linux -path '*/release/bundle/plezy' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-linux-x64
|
||||
path: symbol-inputs/linux-x64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-linux-x64
|
||||
run: ./scripts/upload-symbols.sh linux-x64
|
||||
|
||||
- name: Build Linux Packages
|
||||
run: ARCH_SUFFIX=x64 OUTPUT_DIR=$GITHUB_WORKSPACE python3 linux/packaging/build-packages.py
|
||||
@@ -786,6 +690,7 @@ jobs:
|
||||
plezy-linux-x64.pkg.tar.zst
|
||||
|
||||
build-linux-arm64:
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -798,27 +703,38 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "master"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-arm64-pub-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-arm64-pub-
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
packages: ${{ env.LINUX_APT_PACKAGES }}
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
read -r -a packages <<< "$LINUX_APT_PACKAGES"
|
||||
|
||||
for attempt in 1 2 3; do
|
||||
if sudo apt-get update -o Acquire::Retries=3 && sudo apt-get install -y -o Acquire::Retries=3 "${packages[@]}"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sudo apt-get clean
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
sleep $((attempt * 15))
|
||||
done
|
||||
|
||||
exit 1
|
||||
|
||||
- name: Cache libmpv build
|
||||
id: libmpv-cache
|
||||
@@ -835,44 +751,19 @@ jobs:
|
||||
run: sudo gem install fpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
run: flutter pub get --no-example
|
||||
|
||||
- name: Build Linux arm64
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-arm64
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-arm64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-arm64
|
||||
env:
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/aarch64-linux-gnu/pkgconfig
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/linux-arm64"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/linux-arm64" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/linux-arm64" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/linux" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/linux -path '*/release/bundle/plezy' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-linux-arm64
|
||||
path: symbol-inputs/linux-arm64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-linux-arm64
|
||||
run: ./scripts/upload-symbols.sh linux-arm64
|
||||
|
||||
- name: Find bundle directory
|
||||
id: find-bundle
|
||||
@@ -935,53 +826,9 @@ jobs:
|
||||
plezy-linux-arm64.rpm
|
||||
plezy-linux-arm64.pkg.tar.zst
|
||||
|
||||
upload-symbols:
|
||||
if: github.repository == 'edde746/plezy'
|
||||
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, build-linux-x64, build-linux-arm64]
|
||||
runs-on: ${{ matrix.os }}
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: android-apk
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh android-apk symbol-inputs/android-apk
|
||||
- platform: ios
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh ios symbol-inputs/ios
|
||||
- platform: macos
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh macos symbol-inputs/macos
|
||||
- platform: windows-x64
|
||||
os: windows-latest
|
||||
command: ./scripts/upload-symbols.ps1 windows-x64 symbol-inputs/windows-x64
|
||||
- platform: windows-arm64
|
||||
os: windows-latest
|
||||
command: ./scripts/upload-symbols.ps1 windows-arm64 symbol-inputs/windows-arm64
|
||||
- platform: linux-x64
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh linux-x64 symbol-inputs/linux-x64
|
||||
- platform: linux-arm64
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh linux-arm64 symbol-inputs/linux-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Download symbols artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: symbols-${{ matrix.platform }}
|
||||
path: symbol-inputs/${{ matrix.platform }}
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
run: ${{ matrix.command }}
|
||||
|
||||
create-release:
|
||||
needs: [build-android, build-ios, build-macos, package-windows, build-linux-x64, build-linux-arm64]
|
||||
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, package-windows, build-linux-x64, build-linux-arm64]
|
||||
if: ${{ always() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && (inputs.build_android || inputs.build_ios || inputs.build_macos || inputs.build_windows || inputs.build_linux) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -992,48 +839,56 @@ jobs:
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Download Android artifacts
|
||||
if: ${{ inputs.build_android }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: android-apk
|
||||
path: artifacts/android-apk
|
||||
|
||||
- name: Download iOS artifact
|
||||
if: ${{ inputs.build_ios }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ios-ipa
|
||||
path: artifacts/ios-ipa
|
||||
|
||||
- name: Download macOS artifact
|
||||
if: ${{ inputs.build_macos }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: macos-dmg
|
||||
path: artifacts/macos-dmg
|
||||
|
||||
- name: Download Windows x64 artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-x64-portable
|
||||
path: artifacts/windows-x64-portable
|
||||
|
||||
- name: Download Windows arm64 artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-arm64-portable
|
||||
path: artifacts/windows-arm64-portable
|
||||
|
||||
- name: Download Windows installer artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-installer
|
||||
path: artifacts/windows-installer
|
||||
|
||||
- name: Download Linux x64 artifacts
|
||||
if: ${{ inputs.build_linux }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: linux-x64
|
||||
path: artifacts/linux-x64
|
||||
|
||||
- name: Download Linux arm64 artifacts
|
||||
if: ${{ inputs.build_linux }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: linux-arm64
|
||||
@@ -1120,21 +975,39 @@ jobs:
|
||||
echo "Generated appcast.xml:"
|
||||
cat appcast.xml
|
||||
|
||||
- name: Collect release files
|
||||
id: release-files
|
||||
run: |
|
||||
{
|
||||
echo 'files<<EOF'
|
||||
if [ "${{ inputs.build_android }}" = "true" ]; then
|
||||
echo artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
|
||||
echo artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
|
||||
echo artifacts/android-apk/plezy-android-x86_64.tar.gz
|
||||
fi
|
||||
if [ "${{ inputs.build_ios }}" = "true" ]; then
|
||||
echo artifacts/ios-ipa/plezy-ios.ipa
|
||||
fi
|
||||
if [ "${{ inputs.build_macos }}" = "true" ]; then
|
||||
echo artifacts/macos-dmg/plezy-macos.dmg
|
||||
fi
|
||||
if [ "${{ inputs.build_windows }}" = "true" ]; then
|
||||
echo artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
|
||||
echo artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
|
||||
echo artifacts/windows-installer/plezy-windows-installer.exe
|
||||
fi
|
||||
if [ "${{ inputs.build_linux }}" = "true" ]; then
|
||||
echo 'artifacts/linux-x64/*'
|
||||
echo 'artifacts/linux-arm64/*'
|
||||
fi
|
||||
echo appcast.xml
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: |
|
||||
artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
|
||||
artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
|
||||
artifacts/android-apk/plezy-android-x86_64.tar.gz
|
||||
artifacts/ios-ipa/plezy-ios.ipa
|
||||
artifacts/macos-dmg/plezy-macos.dmg
|
||||
artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
|
||||
artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
|
||||
artifacts/windows-installer/plezy-windows-installer.exe
|
||||
artifacts/linux-x64/*
|
||||
artifacts/linux-arm64/*
|
||||
appcast.xml
|
||||
files: ${{ steps.release-files.outputs.files }}
|
||||
draft: true
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -23,22 +23,31 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v2-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-v2-
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
|
||||
flutter pub get
|
||||
|
||||
- name: Verify generated files committed
|
||||
run: |
|
||||
scripts/codegen.sh
|
||||
if ! git diff --exit-code lib/; then
|
||||
echo "::error::Generated files (.g.dart / .freezed.dart) are out of date."
|
||||
echo "Run 'scripts/codegen.sh' and commit the result."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Verify formatting
|
||||
run: |
|
||||
# Find all Dart files excluding generated files
|
||||
@@ -106,16 +115,16 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v2-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-v2-
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
@@ -130,6 +139,24 @@ jobs:
|
||||
echo "No tests found, skipping test execution"
|
||||
fi
|
||||
|
||||
native-format:
|
||||
name: Native Formatting
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
|
||||
- name: Verify native formatting
|
||||
run: scripts/format_native.sh --check
|
||||
|
||||
dependency-check:
|
||||
name: Dependency Validation
|
||||
runs-on: ubuntu-latest
|
||||
@@ -143,16 +170,16 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v2-${{ hashFiles('**/pubspec.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pub-v2-
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Verify dependencies
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"indentation" : {
|
||||
"spaces" : 2
|
||||
},
|
||||
"lineLength" : 120,
|
||||
"maximumBlankLines" : 1,
|
||||
"respectsExistingLineBreaks" : true,
|
||||
"rules" : {},
|
||||
"version" : 1
|
||||
}
|
||||
@@ -10,7 +10,8 @@
|
||||
## Development
|
||||
|
||||
- Follow Dart/Flutter conventions
|
||||
- Run `dart format .` to format your code (note: generated files like `*.g.dart` are excluded from CI checks)
|
||||
- Run `dart format .` to format Dart code (note: generated files like `*.g.dart` are excluded from CI checks)
|
||||
- Run `scripts/format_native.sh --fix` to format Kotlin, Swift, C++, C, Objective-C, and native headers
|
||||
- Run `flutter analyze` before submitting to check for issues
|
||||
- Run `flutter test` if tests are available
|
||||
- Test your changes thoroughly
|
||||
@@ -19,8 +20,9 @@
|
||||
|
||||
The project includes automated CI checks that run on all pull requests:
|
||||
|
||||
1. **Code Formatting**: Ensures code follows Dart formatting standards
|
||||
- Run locally: `dart format .` to format all files
|
||||
1. **Code Formatting**: Ensures code follows Dart and native formatting standards
|
||||
- Run locally: `dart format .` to format Dart files
|
||||
- Run locally: `scripts/format_native.sh --fix` to format native files
|
||||
- Note: CI only checks non-generated files (excludes `.g.dart`, `.freezed.dart`)
|
||||
- Generated files are reformatted automatically by build tools
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
cask "plezy" do
|
||||
version "1.35.1"
|
||||
sha256 "47fbcb070c6d7b8e6df7fd178946cbfa8426d6028541e1b8a9ef85afbeda8d33"
|
||||
version "2.6.0"
|
||||
sha256 "e408fe84c07e0ff4a2f1a78e8dcfc418233c66ca98c79028a7b099499307a59e"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
desc "Modern Plex client built with Flutter"
|
||||
desc "Modern Plex and Jellyfin client built with Flutter"
|
||||
homepage "https://github.com/edde746/plezy"
|
||||
|
||||
livecheck do
|
||||
|
||||
@@ -3,13 +3,19 @@
|
||||
Plezy
|
||||
</h1>
|
||||
|
||||
A modern Plex client for desktop and mobile. Built with Flutter for native performance and a clean interface.
|
||||
A modern client for Plex and Jellyfin on desktop, mobile, and TV. Built with Flutter for native performance and a clean interface.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
|
||||
<p>
|
||||
<a href="https://plezy.app">Website</a> ·
|
||||
<a href="https://plezy.app/#screenshots">Screenshots</a> ·
|
||||
<a href="#download">Download</a> ·
|
||||
<a href="CONTRIBUTING.md">Contributing</a> ·
|
||||
<a href="LICENSE">License</a>
|
||||
</p>
|
||||
|
||||
*More screenshots in the [screenshots folder](assets/screenshots/#readme)*
|
||||
<p align="center">
|
||||
<img src="assets/readme-showcase.webp" alt="Plezy mobile screenshots" width="900" />
|
||||
</p>
|
||||
|
||||
## Download
|
||||
|
||||
@@ -17,9 +23,15 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
|
||||
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
|
||||
<a href='https://www.amazon.com/gp/product/B0GK65CVS1'><img height='60' alt='Available at the Amazon App Store' src='./assets/amazon-badge.png'/></a>
|
||||
|
||||
- [Windows (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
|
||||
- [macOS (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
|
||||
- [Linux (x64, arm64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
|
||||
| Platform | Download |
|
||||
| --- | --- |
|
||||
| Windows | [Installer (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe) · [Portable x64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-x64-portable.7z) · [Portable arm64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-arm64-portable.7z) |
|
||||
| macOS | [DMG (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg) |
|
||||
| Linux x64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz) |
|
||||
| Linux arm64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.tar.gz) |
|
||||
|
||||
Package managers:
|
||||
|
||||
- [Nix](https://search.nixos.org/packages?channel=unstable&query=plezy) - Community package by [@mio-19](https://github.com/mio-19) and [@MiniHarinn](https://github.com/MiniHarinn)
|
||||
- **Homebrew** (macOS):
|
||||
```bash
|
||||
@@ -32,38 +44,37 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
|
||||
```
|
||||
- **WinGet** (Windows):
|
||||
```bash
|
||||
winget install edde746.plezy
|
||||
winget install edde746.Plezy
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
### <img src="assets/readme_icons/browse.svg" height="20" alt="" align="center" /> Browse & Discover
|
||||
- Libraries, collections, and playlists
|
||||
- Discover hub — On Deck, trending, and personalized recommendations
|
||||
- Discover hub — Continue Watching, Next Up, trending, and recommendations
|
||||
- Cross-server search
|
||||
- Filtering, sorting, and alphabetical jump navigation
|
||||
- Extras — trailers, deleted scenes, behind-the-scenes
|
||||
|
||||
### <img src="assets/readme_icons/playback.svg" height="20" alt="" align="center" /> Playback
|
||||
- Wide codec support (HEVC, AV1, VP9, and more)
|
||||
- HDR and Dolby Vision (not Linux)
|
||||
- HDR and Dolby Vision[^1]
|
||||
- Full ASS/SSA subtitles with customizable styling
|
||||
- Online subtitle search & download
|
||||
- Audio & subtitle preferences synced with Plex profile
|
||||
- Online subtitle search & download[^2]
|
||||
- Audio & subtitle choices remembered per title
|
||||
- Progress sync and resume
|
||||
- Auto-play next episode with skip intro / skip credits
|
||||
- Chapter navigation with BIF thumbnail scrub previews
|
||||
- Chapter navigation with thumbnail scrub previews
|
||||
- Playback speed, audio sync offset, sleep timer
|
||||
- Ambient lighting and GLSL shader presets
|
||||
- Picture-in-Picture on Android, iOS, and macOS
|
||||
- Refresh-rate matching on Windows and Android
|
||||
- Ambient lighting and GLSL shader presets[^3]
|
||||
- Picture-in-Picture[^4]
|
||||
- Refresh-rate matching[^5]
|
||||
- External player launch (VLC, MX Player, etc.)
|
||||
|
||||
### <img src="assets/readme_icons/live-tv.svg" height="20" alt="" align="center" /> Live TV & DVR
|
||||
- EPG guide grid
|
||||
- Channel tuning with favorites
|
||||
- DVR recording rules and scheduled recordings
|
||||
- Multi-server DVR support
|
||||
- Live TV channel browsing with favorites
|
||||
- DVR support with EPG guide, recording rules, and scheduled recordings[^2]
|
||||
- Multi-server Live TV support where available
|
||||
|
||||
### <img src="assets/readme_icons/downloads.svg" height="20" alt="" align="center" /> Downloads & Offline
|
||||
- Download media for offline viewing
|
||||
@@ -76,22 +87,31 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
|
||||
- Real-time play / pause / seek sync
|
||||
|
||||
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
|
||||
- Discord Rich Presence
|
||||
- Trakt scrobbling
|
||||
- Discord Rich Presence[^7]
|
||||
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
|
||||
- Plezy Remote — control desktop and TV from mobile
|
||||
- Android TV Watch Next row
|
||||
- Watch Next row[^6]
|
||||
|
||||
### <img src="assets/readme_icons/customization.svg" height="20" alt="" align="center" /> Platform & Customization
|
||||
- Desktop, mobile, and TV — full D-pad, keyboard, and gamepad support
|
||||
- Customizable keyboard shortcuts on desktop
|
||||
- In-app metadata and artwork editing
|
||||
- Localized in 14 languages
|
||||
- Customizable keyboard shortcuts[^7]
|
||||
- Metadata and artwork editing[^2]
|
||||
- Settings import/export
|
||||
- Localized in English plus 14 translations
|
||||
|
||||
[^1]: Not available on Linux.
|
||||
[^2]: Plex only.
|
||||
[^3]: Not available on iOS or tvOS.
|
||||
[^4]: Android, iOS, and macOS.
|
||||
[^5]: Windows, Android, and tvOS.
|
||||
[^6]: Android TV only.
|
||||
[^7]: Desktop only.
|
||||
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites
|
||||
- Flutter SDK 3.8.1+
|
||||
- A Plex account with server access
|
||||
- Flutter SDK 3.38.4+
|
||||
- A Plex account or Jellyfin server with user credentials
|
||||
|
||||
### Setup
|
||||
|
||||
@@ -99,20 +119,46 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
|
||||
git clone https://github.com/edde746/plezy.git
|
||||
cd plezy
|
||||
flutter pub get
|
||||
dart run build_runner build
|
||||
scripts/codegen.sh
|
||||
flutter run
|
||||
```
|
||||
|
||||
### Code Generation
|
||||
|
||||
After modifying model classes:
|
||||
After modifying model classes or other generated sources:
|
||||
|
||||
```bash
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
scripts/codegen.sh
|
||||
```
|
||||
|
||||
After modifying translations:
|
||||
|
||||
```bash
|
||||
dart run slang
|
||||
```
|
||||
|
||||
### Local Checks
|
||||
|
||||
```bash
|
||||
scripts/ci_checks.sh
|
||||
```
|
||||
|
||||
To install the same pre-commit checks locally:
|
||||
|
||||
```bash
|
||||
scripts/setup_hooks.sh
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for development workflow, formatting, tests, and translation guidelines.
|
||||
|
||||
## License
|
||||
|
||||
Plezy is licensed under [GPL-3.0](LICENSE).
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
- Built with [Flutter](https://flutter.dev)
|
||||
- Designed for [Plex Media Server](https://www.plex.tv)
|
||||
- Playback powered by [mpv](https://mpv.io) via [MPVKit](https://github.com/mpvkit/MPVKit) and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
|
||||
- Supports [Plex Media Server](https://www.plex.tv) and [Jellyfin](https://jellyfin.org)
|
||||
- Playback powered by [mpv](https://mpv.io), [MPVKit](https://github.com/mpvkit/MPVKit), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), [libass-android](https://github.com/peerless2012/libass-android), and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import java.util.Properties
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
val mpvVersion = "v1.0.7"
|
||||
@@ -13,180 +13,216 @@ val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile
|
||||
val mpvAar = "libmpv-release.aar"
|
||||
|
||||
val downloadLibmpv by tasks.registering {
|
||||
val stamp = File(mpvDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == mpvVersion }
|
||||
doLast {
|
||||
mpvDir.mkdirs()
|
||||
val url = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
|
||||
exec { commandLine("curl", "-sfL", url, "-o", File(mpvDir, mpvAar).absolutePath) }
|
||||
stamp.writeText(mpvVersion)
|
||||
}
|
||||
val stamp = File(mpvDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == mpvVersion }
|
||||
doLast {
|
||||
mpvDir.mkdirs()
|
||||
val url = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
|
||||
exec { commandLine("curl", "-sfL", url, "-o", File(mpvDir, mpvAar).absolutePath) }
|
||||
stamp.writeText(mpvVersion)
|
||||
}
|
||||
}
|
||||
|
||||
val assVersion = "fp-3"
|
||||
val assDir = layout.buildDirectory.dir("libass").get().asFile
|
||||
val assAars = listOf("lib_ass-release.aar", "lib_ass_kt-release.aar", "lib_ass_media-release.aar")
|
||||
|
||||
val downloadLibass by tasks.registering {
|
||||
val stamp = File(assDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == assVersion }
|
||||
doLast {
|
||||
assDir.mkdirs()
|
||||
val baseUrl = "https://github.com/edde746/libass-android/releases/download/$assVersion"
|
||||
assAars.forEach { name ->
|
||||
val dest = File(assDir, name)
|
||||
exec { commandLine("curl", "-sfL", "$baseUrl/$name", "-o", dest.absolutePath) }
|
||||
}
|
||||
stamp.writeText(assVersion)
|
||||
// Extract libc++_shared.so from the libmpv AAR so the app source set can package
|
||||
// it with top merge priority (see packaging { jniLibs } and sourceSets below).
|
||||
val extractMpvLibcxx by tasks.registering {
|
||||
dependsOn(downloadLibmpv)
|
||||
val aar = File(mpvDir, mpvAar)
|
||||
val outDir = File(mpvDir, "libcxx")
|
||||
inputs.file(aar)
|
||||
outputs.dir(outDir)
|
||||
doLast {
|
||||
outDir.deleteRecursively() // drop stale ABIs from a previous AAR version
|
||||
outDir.mkdirs()
|
||||
exec {
|
||||
commandLine(
|
||||
"unzip",
|
||||
"-q",
|
||||
"-o",
|
||||
aar.absolutePath,
|
||||
"jni/*/libc++_shared.so",
|
||||
"-d",
|
||||
outDir.absolutePath
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val doviVersion = "2.3.1"
|
||||
val doviDir = layout.buildDirectory.dir("libdovi").get().asFile
|
||||
val doviAbis = mapOf(
|
||||
"arm64-v8a" to "aarch64-linux-android",
|
||||
"armeabi-v7a" to "armv7-linux-androideabi",
|
||||
"x86" to "i686-linux-android",
|
||||
"x86_64" to "x86_64-linux-android",
|
||||
"arm64-v8a" to "aarch64-linux-android",
|
||||
"armeabi-v7a" to "armv7-linux-androideabi",
|
||||
"x86" to "i686-linux-android",
|
||||
"x86_64" to "x86_64-linux-android"
|
||||
)
|
||||
|
||||
val downloadLibdovi by tasks.registering {
|
||||
val stamp = File(doviDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == doviVersion }
|
||||
doLast {
|
||||
doviDir.mkdirs()
|
||||
val baseUrl = "https://github.com/edde746/libdovi-builds/releases/download/v$doviVersion"
|
||||
doviAbis.forEach { (abi, triple) ->
|
||||
val archive = File(doviDir, "$triple.tar.gz")
|
||||
exec { commandLine("curl", "-sfL", "$baseUrl/libdovi-$triple.tar.gz", "-o", archive.absolutePath) }
|
||||
val outDir = File(doviDir, "$abi/lib")
|
||||
outDir.mkdirs()
|
||||
exec { commandLine("tar", "-xzf", archive.absolutePath, "-C", outDir.absolutePath) }
|
||||
archive.delete()
|
||||
}
|
||||
stamp.writeText(doviVersion)
|
||||
val stamp = File(doviDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == doviVersion }
|
||||
doLast {
|
||||
doviDir.mkdirs()
|
||||
val baseUrl = "https://github.com/edde746/libdovi-builds/releases/download/v$doviVersion"
|
||||
doviAbis.forEach { (abi, triple) ->
|
||||
val archive = File(doviDir, "$triple.tar.gz")
|
||||
exec { commandLine("curl", "-sfL", "$baseUrl/libdovi-$triple.tar.gz", "-o", archive.absolutePath) }
|
||||
val outDir = File(doviDir, "$abi/lib")
|
||||
outDir.mkdirs()
|
||||
exec { commandLine("tar", "-xzf", archive.absolutePath, "-C", outDir.absolutePath) }
|
||||
archive.delete()
|
||||
}
|
||||
stamp.writeText(doviVersion)
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.edde746.plezy"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
namespace = "com.edde746.plezy"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.edde746.plezy"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
arguments += listOf(
|
||||
"-DDOVI_ENABLE_LIBDOVI=ON",
|
||||
"-DDOVI_LIBDOVI_PREBUILT_ROOT=${doviDir.absolutePath}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (System.getenv("AMAZON") != null) {
|
||||
versionCode = (flutter.versionCode ?: 0) + 3000
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
|
||||
}
|
||||
}
|
||||
}
|
||||
defaultConfig {
|
||||
applicationId = "com.edde746.plezy"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
}
|
||||
cmake {
|
||||
arguments += listOf(
|
||||
"-DDOVI_ENABLE_LIBDOVI=ON",
|
||||
"-DDOVI_LIBDOVI_PREBUILT_ROOT=${doviDir.absolutePath}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
val keystoreProperties = Properties()
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
|
||||
keyAlias = keystoreProperties["keyAlias"] as String
|
||||
keyPassword = keystoreProperties["keyPassword"] as String
|
||||
storeFile = file(keystoreProperties["storeFile"] as String)
|
||||
storePassword = keystoreProperties["storePassword"] as String
|
||||
}
|
||||
}
|
||||
if (System.getenv("AMAZON") != null) {
|
||||
versionCode = (flutter.versionCode ?: 0) + 3000
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// Only use release signing if key.properties exists (not in CI/CD)
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
// If key.properties doesn't exist, it will use debug signing for CI builds
|
||||
ndk {
|
||||
debugSymbolLevel = "FULL"
|
||||
}
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
}
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// Resolve conflict between libass-android and libmpv native libraries
|
||||
pickFirsts.add("lib/*/libc++_shared.so")
|
||||
}
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
val keystoreProperties = Properties()
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
|
||||
keyAlias = keystoreProperties["keyAlias"] as String
|
||||
keyPassword = keystoreProperties["keyPassword"] as String
|
||||
storeFile = file(keystoreProperties["storeFile"] as String)
|
||||
storePassword = keystoreProperties["storePassword"] as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// Only use release signing if key.properties exists (not in CI/CD)
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
// If key.properties doesn't exist, it will use debug signing for CI builds
|
||||
ndk {
|
||||
debugSymbolLevel = "FULL"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// Three copies of libc++_shared.so reach the merge: the libmpv AAR's
|
||||
// (NDK r29 — exports std::from_chars<float> that libmpv.so needs), the
|
||||
// :libass module's CMake-contributed copy (NDK 28.2 — lacks it), and
|
||||
// peerless2012:ass's bundled copy (also old). pickFirst keeps the merge
|
||||
// from erroring on the duplicates; WHICH copy wins is pinned by the
|
||||
// sourceSets block below: extractMpvLibcxx unpacks the libmpv AAR's copy
|
||||
// into an app jniLibs dir, and PROJECT-scope sources beat sub-projects
|
||||
// and external AARs. libc++ is backward ABI-compatible, so the older-NDK
|
||||
// consumers (libass.so, libasskt.so, ffmpeg decoder, cronet) run fine
|
||||
// against the newer copy.
|
||||
pickFirsts.add("lib/*/libc++_shared.so")
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
// libc++_shared.so extracted from the libmpv AAR by extractMpvLibcxx.
|
||||
// App source-set jniLibs sit in the PROJECT scope, merged ahead of
|
||||
// subprojects (:libass) and external AARs, so with the pickFirst rule
|
||||
// above this copy deterministically wins regardless of dependency order.
|
||||
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
// Download libdovi before any CMake/native build task
|
||||
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
|
||||
dependsOn(downloadLibdovi)
|
||||
dependsOn(downloadLibdovi)
|
||||
}
|
||||
|
||||
// Download libmpv and libass AARs before compilation
|
||||
// Download the libmpv AAR before compilation
|
||||
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
|
||||
dependsOn(downloadLibmpv)
|
||||
dependsOn(downloadLibass)
|
||||
dependsOn(downloadLibmpv, extractMpvLibcxx)
|
||||
}
|
||||
// merge{Debug,Profile,Release}JniLibFolders snapshot jniLibs source dirs as inputs;
|
||||
// Gradle 8 requires an explicit dependency on the producing task.
|
||||
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
|
||||
dependsOn(extractMpvLibcxx)
|
||||
}
|
||||
|
||||
|
||||
dependencies {
|
||||
implementation(files(File(mpvDir, mpvAar)))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
implementation(files(File(mpvDir, mpvAar)))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
|
||||
// Android TV Watch Next integration
|
||||
implementation("androidx.tvprovider:tvprovider:1.0.0")
|
||||
// Android TV Watch Next integration
|
||||
implementation("androidx.tvprovider:tvprovider:1.0.0")
|
||||
|
||||
// Media3 ExoPlayer for Android
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
implementation("androidx.media3:media3-exoplayer-hls:1.9.2")
|
||||
implementation("androidx.media3:media3-ui:1.9.2")
|
||||
implementation("androidx.media3:media3-common:1.9.2")
|
||||
// Media3 ExoPlayer for Android
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
implementation("androidx.media3:media3-exoplayer-hls:1.9.2")
|
||||
implementation("androidx.media3:media3-ui:1.9.2")
|
||||
implementation("androidx.media3:media3-common:1.9.2")
|
||||
|
||||
// Cronet for HTTP/2 multiplexing + better connection management
|
||||
implementation("androidx.media3:media3-datasource-cronet:1.9.2")
|
||||
implementation("org.chromium.net:cronet-embedded:143.7445.0")
|
||||
// Cronet for HTTP/2 multiplexing + better connection management
|
||||
implementation("androidx.media3:media3-datasource-cronet:1.9.2")
|
||||
implementation("org.chromium.net:cronet-embedded:143.7445.0")
|
||||
|
||||
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
|
||||
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
|
||||
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
|
||||
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
|
||||
|
||||
// libass-android for ASS/SSA subtitle rendering
|
||||
assAars.forEach { implementation(files(File(assDir, it))) }
|
||||
// libass ASS/SSA subtitle rendering: optimized native core (libass.so +
|
||||
// prefab headers) from the edde746/libass-android fork's releases; Kotlin/JNI
|
||||
// bindings + Media3 glue live in the android/libass module. -PlocalAssCore
|
||||
// swaps in a mavenLocal()-published core (0.4.0-local) for native A/B tests.
|
||||
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
|
||||
implementation("io.github.peerless2012:ass:$assCoreVersion@aar")
|
||||
implementation(project(":libass"))
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
|
||||
<!-- Internet access permissions -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
|
||||
|
||||
|
||||
<!-- PIP and media session foreground service permissions -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||
<uses-permission android:name="android.permission.REORDER_TASKS"/>
|
||||
|
||||
<!-- Background download notifications and foreground service -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
@@ -58,6 +60,9 @@
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"
|
||||
/>
|
||||
<meta-data
|
||||
android:name="flutter_deeplinking_enabled"
|
||||
android:value="false" />
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
#define TAG "DoviBridge"
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
||||
@@ -12,115 +14,133 @@
|
||||
#endif
|
||||
|
||||
static const char* BRIDGE_VERSION = "1.0.0";
|
||||
static constexpr jint CONVERT_FAILED = -1;
|
||||
static constexpr jint DESTINATION_TOO_SMALL = -2;
|
||||
static constexpr jint MAX_RPU_INPUT_SIZE = 8192;
|
||||
static constexpr size_t MAX_RPU_OUTPUT_SIZE = 16384;
|
||||
|
||||
extern "C" JNIEXPORT jbyteArray JNICALL
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeConvertDv7RpuToDv81(
|
||||
JNIEnv *env, jclass, jbyteArray payload, jint mode) {
|
||||
extern "C" JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_DoviBridge_nativeConvertDv7RpuToDv81(
|
||||
JNIEnv* env, jclass, jbyteArray payload, jint payload_offset, jint payload_length, jbyteArray output,
|
||||
jint output_offset, jint output_capacity, jint mode) {
|
||||
#if !DOVI_REAL_LINKED
|
||||
return nullptr;
|
||||
return CONVERT_FAILED;
|
||||
#else
|
||||
if (payload == nullptr) return nullptr;
|
||||
if (payload == nullptr || output == nullptr) return CONVERT_FAILED;
|
||||
if (payload_offset < 0 || payload_length <= 0 || output_offset < 0 || output_capacity < 0) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
jsize len = env->GetArrayLength(payload);
|
||||
if (len <= 0) return nullptr;
|
||||
const jsize payload_array_len = env->GetArrayLength(payload);
|
||||
const jsize output_array_len = env->GetArrayLength(output);
|
||||
if (payload_offset > payload_array_len || payload_length > payload_array_len - payload_offset) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
if (output_offset > output_array_len) return DESTINATION_TOO_SMALL;
|
||||
|
||||
// Valid RPU NALs are typically <2 KiB; reject unreasonable sizes
|
||||
if (len > 8192) {
|
||||
LOGW("RPU payload too large (%d bytes), skipping", len);
|
||||
return nullptr;
|
||||
}
|
||||
const jsize logical_output_len = output_capacity < output_array_len ? output_capacity : output_array_len;
|
||||
if (output_offset > logical_output_len) return DESTINATION_TOO_SMALL;
|
||||
|
||||
// Copy to native heap so libdovi never touches JVM heap memory.
|
||||
// GetByteArrayElements on ART may return a direct heap pointer; any
|
||||
// out-of-bounds access by libdovi would corrupt adjacent JVM objects.
|
||||
auto *buf = new (std::nothrow) uint8_t[static_cast<size_t>(len)];
|
||||
if (buf == nullptr) return nullptr;
|
||||
// Valid RPU NALs are typically <2 KiB; reject unreasonable sizes
|
||||
if (payload_length > MAX_RPU_INPUT_SIZE) {
|
||||
LOGW("RPU payload too large (%d bytes), skipping", payload_length);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
env->GetByteArrayRegion(payload, 0, len, reinterpret_cast<jbyte *>(buf));
|
||||
if (env->ExceptionCheck()) {
|
||||
delete[] buf;
|
||||
return nullptr;
|
||||
}
|
||||
// Copy to native heap so libdovi never touches JVM heap memory.
|
||||
// Do not use GetPrimitiveArrayCritical here: it can block concurrent GC
|
||||
// compaction during sustained playback. A thread-local scratch buffer avoids
|
||||
// per-frame heap churn while keeping libdovi away from JVM heap memory.
|
||||
thread_local std::vector<uint8_t> scratch;
|
||||
try {
|
||||
scratch.resize(static_cast<size_t>(payload_length));
|
||||
} catch (...) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
// Try dovi_parse_unspec62_nalu first (handles escaped NALs), fallback to dovi_parse_rpu
|
||||
DoviRpuOpaque *rpu = dovi_parse_unspec62_nalu(buf, static_cast<size_t>(len));
|
||||
env->GetByteArrayRegion(payload, payload_offset, payload_length, reinterpret_cast<jbyte*>(scratch.data()));
|
||||
if (env->ExceptionCheck()) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
// Try dovi_parse_unspec62_nalu first (handles escaped NALs), fallback to dovi_parse_rpu
|
||||
const auto rpu_len = static_cast<size_t>(payload_length);
|
||||
DoviRpuOpaque* rpu = dovi_parse_unspec62_nalu(scratch.data(), rpu_len);
|
||||
|
||||
if (rpu == nullptr) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
const char* err = dovi_rpu_get_error(rpu);
|
||||
if (err != nullptr) {
|
||||
// Fallback: try dovi_parse_rpu (raw RPU without NAL framing)
|
||||
dovi_rpu_free(rpu);
|
||||
rpu = dovi_parse_rpu(scratch.data(), rpu_len);
|
||||
if (rpu == nullptr) {
|
||||
delete[] buf;
|
||||
return nullptr;
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
const char *err = dovi_rpu_get_error(rpu);
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
if (err != nullptr) {
|
||||
// Fallback: try dovi_parse_rpu (raw RPU without NAL framing)
|
||||
dovi_rpu_free(rpu);
|
||||
rpu = dovi_parse_rpu(buf, static_cast<size_t>(len));
|
||||
if (rpu == nullptr) {
|
||||
delete[] buf;
|
||||
return nullptr;
|
||||
}
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
if (err != nullptr) {
|
||||
LOGW("RPU parse failed: %s", err);
|
||||
dovi_rpu_free(rpu);
|
||||
delete[] buf;
|
||||
return nullptr;
|
||||
}
|
||||
LOGW("RPU parse failed: %s", err);
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
delete[] buf;
|
||||
// Mode 2 matches Kodi's P8.1 compatibility path and sets luma/chroma curves to no-op.
|
||||
int32_t ret = dovi_convert_rpu_with_mode(rpu, static_cast<uint8_t>(mode));
|
||||
if (ret != 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
LOGW("RPU conversion failed (mode %d): %s", mode, err ? err : "unknown");
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
// Convert to target profile (mode 2 = P8.1 with no-op curves)
|
||||
int32_t ret = dovi_convert_rpu_with_mode(rpu, static_cast<uint8_t>(mode));
|
||||
if (ret != 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
LOGW("RPU conversion failed (mode %d): %s", mode, err ? err : "unknown");
|
||||
dovi_rpu_free(rpu);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Write back as UNSPEC62 NAL
|
||||
const DoviData *out = dovi_write_unspec62_nalu(rpu);
|
||||
if (out == nullptr || out->data == nullptr || out->len == 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
LOGW("RPU write failed: %s", err ? err : "unknown");
|
||||
if (out != nullptr) dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (out->len > 16384) {
|
||||
LOGW("RPU output unexpectedly large (%zu bytes), discarding", out->len);
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jbyteArray result = env->NewByteArray(static_cast<jsize>(out->len));
|
||||
if (result != nullptr) {
|
||||
env->SetByteArrayRegion(result, 0, static_cast<jsize>(out->len),
|
||||
reinterpret_cast<const jbyte *>(out->data));
|
||||
}
|
||||
// Write back as UNSPEC62 NAL
|
||||
const DoviData* out = dovi_write_unspec62_nalu(rpu);
|
||||
if (out == nullptr || out->data == nullptr || out->len == 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
LOGW("RPU write failed: %s", err ? err : "unknown");
|
||||
if (out != nullptr) dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
if (out->len > MAX_RPU_OUTPUT_SIZE) {
|
||||
LOGW("RPU output unexpectedly large (%zu bytes), discarding", out->len);
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
return result;
|
||||
const auto writable = static_cast<size_t>(logical_output_len - output_offset);
|
||||
if (out->len > writable) {
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return DESTINATION_TOO_SMALL;
|
||||
}
|
||||
|
||||
env->SetByteArrayRegion(
|
||||
output, output_offset, static_cast<jsize>(out->len), reinterpret_cast<const jbyte*>(out->data));
|
||||
const bool write_failed = env->ExceptionCheck();
|
||||
const auto written = static_cast<jint>(out->len);
|
||||
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
|
||||
return write_failed ? CONVERT_FAILED : written;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeIsConversionPathReady(
|
||||
JNIEnv *, jclass) {
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeIsConversionPathReady(JNIEnv*, jclass) {
|
||||
#if DOVI_REAL_LINKED
|
||||
return JNI_TRUE;
|
||||
return JNI_TRUE;
|
||||
#else
|
||||
return JNI_FALSE;
|
||||
return JNI_FALSE;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jstring JNICALL
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeGetBridgeVersion(
|
||||
JNIEnv *env, jclass) {
|
||||
return env->NewStringUTF(BRIDGE_VERSION);
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeGetBridgeVersion(JNIEnv* env, jclass) {
|
||||
return env->NewStringUTF(BRIDGE_VERSION);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.media.audiofx.DynamicsProcessing
|
||||
import android.media.audiofx.LoudnessEnhancer
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
|
||||
/**
|
||||
* Session-bound loudness normalization approximating mpv's
|
||||
* `loudnorm=I=-14:TP=-3:LRA=4` filter (#1289).
|
||||
*
|
||||
* API 28+: DynamicsProcessing with a single full-range compressor band as a
|
||||
* slow AGC plus a limiter for the true-peak ceiling. API 25-27, or when the
|
||||
* device lacks the DynamicsProcessing effect HAL: LoudnessEnhancer (fixed
|
||||
* makeup gain with built-in limiting).
|
||||
*
|
||||
* Effects bind to the audio session, so they survive AudioTrack re-creation
|
||||
* (seeks, format changes) while the session id is stable. They only process
|
||||
* PCM mixer streams — the caller must force decoded PCM output and disable
|
||||
* tunneling while enabled. DynamicsProcessing parameters are per-channel, so
|
||||
* the effect is re-created when the output channel count changes (dialogue
|
||||
* lives in the center channel of 5.1 PCM).
|
||||
*/
|
||||
class AudioNormalizationEffect(private val log: (String, String, String) -> Unit) {
|
||||
|
||||
private companion object {
|
||||
const val EFFECT_PRIORITY = 0
|
||||
|
||||
// DynamicsProcessing — tuned for movie mixes whose dialogue sits around
|
||||
// -27 LUFS: compress above threshold, make up toward I=-14, limit at TP=-3.
|
||||
const val FRAME_DURATION_MS = 10f
|
||||
const val MBC_CUTOFF_HZ = 20_000f
|
||||
const val MBC_ATTACK_MS = 30f
|
||||
const val MBC_RELEASE_MS = 300f
|
||||
const val MBC_RATIO = 4f
|
||||
const val MBC_THRESHOLD_DB = -34f
|
||||
const val MBC_KNEE_DB = 6f
|
||||
const val MBC_NOISE_GATE_DB = -90f // effectively disabled
|
||||
const val MBC_EXPANDER_RATIO = 1f // no downward expansion
|
||||
const val MBC_POST_GAIN_DB = 15f
|
||||
const val LIMITER_ATTACK_MS = 1f
|
||||
const val LIMITER_RELEASE_MS = 60f
|
||||
const val LIMITER_RATIO = 10f
|
||||
const val LIMITER_THRESHOLD_DB = -3f
|
||||
const val DEFAULT_CHANNEL_COUNT = 2
|
||||
const val MAX_CHANNEL_COUNT = 8
|
||||
|
||||
// LoudnessEnhancer fallback: fixed boost, internally limited.
|
||||
const val LOUDNESS_ENHANCER_GAIN_MB = 900 // +9 dB
|
||||
}
|
||||
|
||||
private var dynamicsProcessing: DynamicsProcessing? = null
|
||||
private var loudnessEnhancer: LoudnessEnhancer? = null
|
||||
private var attachedSessionId = 0
|
||||
private var attachedChannelCount = 0
|
||||
|
||||
val isActive: Boolean get() = dynamicsProcessing != null || loudnessEnhancer != null
|
||||
|
||||
/** For stats/QA: which engine is processing. */
|
||||
val describe: String
|
||||
get() = when {
|
||||
dynamicsProcessing != null -> "DynamicsProcessing"
|
||||
loudnessEnhancer != null -> "LoudnessEnhancer"
|
||||
else -> "off"
|
||||
}
|
||||
|
||||
/** Attach to [sessionId]; idempotent for an unchanged (session, channels) pair. */
|
||||
fun attach(sessionId: Int, channelCount: Int?) {
|
||||
val channels = (channelCount ?: DEFAULT_CHANNEL_COUNT).coerceIn(1, MAX_CHANNEL_COUNT)
|
||||
if (sessionId == attachedSessionId && channels == attachedChannelCount && isActive) return
|
||||
release()
|
||||
if (sessionId == 0) return // AUDIO_SESSION_ID_UNSET — retry on onAudioSessionIdChanged
|
||||
attachedSessionId = sessionId
|
||||
attachedChannelCount = channels
|
||||
if (Build.VERSION.SDK_INT >= 28 && tryDynamicsProcessing(sessionId, channels)) return
|
||||
tryLoudnessEnhancer(sessionId)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
dynamicsProcessing?.let { effect ->
|
||||
runCatching { effect.setEnabled(false) }
|
||||
runCatching { effect.release() }
|
||||
}
|
||||
dynamicsProcessing = null
|
||||
loudnessEnhancer?.let { effect ->
|
||||
runCatching { effect.setEnabled(false) }
|
||||
runCatching { effect.release() }
|
||||
}
|
||||
loudnessEnhancer = null
|
||||
attachedSessionId = 0
|
||||
attachedChannelCount = 0
|
||||
}
|
||||
|
||||
@RequiresApi(28)
|
||||
private fun tryDynamicsProcessing(sessionId: Int, channelCount: Int): Boolean = try {
|
||||
val band = DynamicsProcessing.MbcBand(
|
||||
// inUse
|
||||
true,
|
||||
MBC_CUTOFF_HZ,
|
||||
MBC_ATTACK_MS,
|
||||
MBC_RELEASE_MS,
|
||||
MBC_RATIO,
|
||||
MBC_THRESHOLD_DB,
|
||||
MBC_KNEE_DB,
|
||||
MBC_NOISE_GATE_DB,
|
||||
MBC_EXPANDER_RATIO,
|
||||
// preGain
|
||||
0f,
|
||||
MBC_POST_GAIN_DB
|
||||
)
|
||||
val mbc = DynamicsProcessing.Mbc(
|
||||
// inUse
|
||||
true,
|
||||
// enabled
|
||||
true,
|
||||
// bandCount
|
||||
1
|
||||
).apply { setBand(0, band) }
|
||||
val limiter = DynamicsProcessing.Limiter(
|
||||
// inUse
|
||||
true,
|
||||
// enabled
|
||||
true,
|
||||
// linkGroup
|
||||
0,
|
||||
LIMITER_ATTACK_MS,
|
||||
LIMITER_RELEASE_MS,
|
||||
LIMITER_RATIO,
|
||||
LIMITER_THRESHOLD_DB,
|
||||
// postGain
|
||||
0f
|
||||
)
|
||||
val channel = DynamicsProcessing.Channel(
|
||||
// inputGain
|
||||
0f,
|
||||
// preEqInUse
|
||||
false,
|
||||
// preEqBandCount
|
||||
0,
|
||||
// mbcInUse
|
||||
true,
|
||||
// mbcBandCount
|
||||
1,
|
||||
// postEqInUse
|
||||
false,
|
||||
// postEqBandCount
|
||||
0,
|
||||
// limiterInUse
|
||||
true
|
||||
).apply {
|
||||
setMbc(mbc)
|
||||
setLimiter(limiter)
|
||||
}
|
||||
val config = DynamicsProcessing.Config.Builder(
|
||||
DynamicsProcessing.VARIANT_FAVOR_FREQUENCY_RESOLUTION,
|
||||
channelCount,
|
||||
// preEqInUse
|
||||
false,
|
||||
// preEqBandCount
|
||||
0,
|
||||
// mbcInUse
|
||||
true,
|
||||
// mbcBandCount
|
||||
1,
|
||||
// postEqInUse
|
||||
false,
|
||||
// postEqBandCount
|
||||
0,
|
||||
// limiterInUse
|
||||
true
|
||||
)
|
||||
.setPreferredFrameDuration(FRAME_DURATION_MS)
|
||||
.setAllChannelsTo(channel)
|
||||
.build()
|
||||
dynamicsProcessing = DynamicsProcessing(EFFECT_PRIORITY, sessionId, config).apply { setEnabled(true) }
|
||||
log("info", "audio-normalization", "DynamicsProcessing attached (session=$sessionId, channels=$channelCount)")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
log(
|
||||
"warn",
|
||||
"audio-normalization",
|
||||
"DynamicsProcessing unavailable (${e.javaClass.simpleName}: ${e.message}); trying LoudnessEnhancer"
|
||||
)
|
||||
dynamicsProcessing = null
|
||||
false
|
||||
}
|
||||
|
||||
private fun tryLoudnessEnhancer(sessionId: Int) {
|
||||
try {
|
||||
loudnessEnhancer = LoudnessEnhancer(sessionId).apply {
|
||||
setTargetGain(LOUDNESS_ENHANCER_GAIN_MB)
|
||||
setEnabled(true)
|
||||
}
|
||||
log("info", "audio-normalization", "LoudnessEnhancer attached (session=$sessionId, gain=${LOUDNESS_ENHANCER_GAIN_MB}mB)")
|
||||
} catch (e: Exception) {
|
||||
loudnessEnhancer = null
|
||||
attachedSessionId = 0
|
||||
attachedChannelCount = 0
|
||||
log(
|
||||
"warn",
|
||||
"audio-normalization",
|
||||
"No loudness effect available on this device (${e.javaClass.simpleName}: ${e.message})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,149 +19,151 @@ import androidx.media3.extractor.TrackOutput
|
||||
*/
|
||||
@androidx.media3.common.util.UnstableApi
|
||||
class CuelessSeekExtractorWrapper(
|
||||
private val delegate: Extractor,
|
||||
private val delegate: Extractor
|
||||
) : Extractor {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "CuelessSeek"
|
||||
// MKV Cluster element ID: 0x1F43B675 (4-byte EBML Class-D ID)
|
||||
private val CLUSTER_ID = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
|
||||
private const val SCAN_BUFFER_SIZE = 8192
|
||||
// Max bytes to scan for a Cluster boundary before giving up
|
||||
private const val MAX_SCAN_BYTES = 1024 * 1024 // 1 MB
|
||||
companion object {
|
||||
private const val TAG = "CuelessSeek"
|
||||
|
||||
// MKV Cluster element ID: 0x1F43B675 (4-byte EBML Class-D ID)
|
||||
private val CLUSTER_ID = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
|
||||
private const val SCAN_BUFFER_SIZE = 8192
|
||||
|
||||
// Max bytes to scan for a Cluster boundary before giving up
|
||||
private const val MAX_SCAN_BYTES = 1024 * 1024 // 1 MB
|
||||
}
|
||||
|
||||
private var inputLength: Long = C.LENGTH_UNSET.toLong()
|
||||
private var needsClusterResync = false
|
||||
private var isApproximateSeeking = false
|
||||
private var pendingSeekTimeUs: Long = C.TIME_UNSET
|
||||
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(SeekInterceptingOutput(output))
|
||||
}
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
if (inputLength == C.LENGTH_UNSET.toLong()) {
|
||||
inputLength = input.length
|
||||
}
|
||||
|
||||
private var inputLength: Long = C.LENGTH_UNSET.toLong()
|
||||
private var needsClusterResync = false
|
||||
private var isApproximateSeeking = false
|
||||
private var pendingSeekTimeUs: Long = C.TIME_UNSET
|
||||
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(SeekInterceptingOutput(output))
|
||||
if (needsClusterResync) {
|
||||
needsClusterResync = false
|
||||
return scanForCluster(input, seekPosition)
|
||||
}
|
||||
return delegate.read(input, seekPosition)
|
||||
}
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
if (inputLength == C.LENGTH_UNSET.toLong()) {
|
||||
inputLength = input.length
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
if (isApproximateSeeking && position > 0) {
|
||||
needsClusterResync = true
|
||||
pendingSeekTimeUs = timeUs
|
||||
}
|
||||
delegate.seek(position, timeUs)
|
||||
}
|
||||
|
||||
override fun release() = delegate.release()
|
||||
|
||||
/**
|
||||
* Scan forward from the current input position to find the next MKV Cluster
|
||||
* element ID (0x1F43B675). Returns [Extractor.RESULT_SEEK] with the Cluster's
|
||||
* byte position so ExoPlayer repositions the DataSource there.
|
||||
*/
|
||||
private fun scanForCluster(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
val buffer = ByteArray(SCAN_BUFFER_SIZE)
|
||||
var totalScanned = 0L
|
||||
// Carry over last 3 bytes across buffer boundaries to detect split IDs
|
||||
var carry = ByteArray(0)
|
||||
|
||||
while (totalScanned < MAX_SCAN_BYTES) {
|
||||
val toRead = minOf(SCAN_BUFFER_SIZE, (MAX_SCAN_BYTES - totalScanned).toInt())
|
||||
val bytesRead: Int
|
||||
try {
|
||||
bytesRead = input.read(buffer, 0, toRead)
|
||||
} catch (_: Exception) {
|
||||
break
|
||||
}
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT) break
|
||||
|
||||
// Combine carry + new data for scanning
|
||||
val scanData = if (carry.isNotEmpty()) carry + buffer.copyOf(bytesRead) else buffer.copyOf(bytesRead)
|
||||
|
||||
for (i in 0..scanData.size - 4) {
|
||||
if (scanData[i] == CLUSTER_ID[0] &&
|
||||
scanData[i + 1] == CLUSTER_ID[1] &&
|
||||
scanData[i + 2] == CLUSTER_ID[2] &&
|
||||
scanData[i + 3] == CLUSTER_ID[3]
|
||||
) {
|
||||
// Compute the absolute byte position of this Cluster
|
||||
val clusterPosition = input.position - bytesRead - carry.size + i
|
||||
Log.d(TAG, "Found Cluster at byte $clusterPosition (scanned ${totalScanned + i} bytes)")
|
||||
seekPosition.position = clusterPosition
|
||||
delegate.seek(clusterPosition, pendingSeekTimeUs)
|
||||
pendingSeekTimeUs = C.TIME_UNSET
|
||||
return Extractor.RESULT_SEEK
|
||||
}
|
||||
if (needsClusterResync) {
|
||||
needsClusterResync = false
|
||||
return scanForCluster(input, seekPosition)
|
||||
}
|
||||
return delegate.read(input, seekPosition)
|
||||
}
|
||||
|
||||
// Keep last 3 bytes as carry for next iteration
|
||||
carry = if (scanData.size >= 3) scanData.copyOfRange(scanData.size - 3, scanData.size) else scanData.copyOf()
|
||||
totalScanned += bytesRead
|
||||
}
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
if (isApproximateSeeking && position > 0) {
|
||||
needsClusterResync = true
|
||||
pendingSeekTimeUs = timeUs
|
||||
// Failed to find a Cluster — fall back to position 0
|
||||
Log.w(TAG, "No Cluster found after scanning $totalScanned bytes, resetting to start")
|
||||
seekPosition.position = 0
|
||||
delegate.seek(0, 0)
|
||||
return Extractor.RESULT_SEEK
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that intercepts [seekMap] calls to replace
|
||||
* [SeekMap.Unseekable] with an approximate proportional SeekMap.
|
||||
*/
|
||||
private inner class SeekInterceptingOutput(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
|
||||
override fun seekMap(seekMap: SeekMap) {
|
||||
if (seekMap is SeekMap.Unseekable) {
|
||||
val durationUs = seekMap.durationUs
|
||||
if (durationUs != C.TIME_UNSET && durationUs > 0) {
|
||||
Log.i(TAG, "Replacing Unseekable with approximate SeekMap (duration=${durationUs / 1_000_000}s)")
|
||||
isApproximateSeeking = true
|
||||
delegate.seekMap(ApproximateSeekMap(durationUs))
|
||||
return
|
||||
}
|
||||
delegate.seek(position, timeUs)
|
||||
}
|
||||
// File has real Cues or unknown duration — pass through
|
||||
isApproximateSeeking = false
|
||||
delegate.seekMap(seekMap)
|
||||
}
|
||||
}
|
||||
|
||||
override fun release() = delegate.release()
|
||||
/**
|
||||
* Approximate SeekMap that estimates byte positions proportionally.
|
||||
* Used when the MKV has no Cues but has a known duration.
|
||||
*/
|
||||
private inner class ApproximateSeekMap(
|
||||
private val durationUs: Long
|
||||
) : SeekMap {
|
||||
|
||||
/**
|
||||
* Scan forward from the current input position to find the next MKV Cluster
|
||||
* element ID (0x1F43B675). Returns [Extractor.RESULT_SEEK] with the Cluster's
|
||||
* byte position so ExoPlayer repositions the DataSource there.
|
||||
*/
|
||||
private fun scanForCluster(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
val buffer = ByteArray(SCAN_BUFFER_SIZE)
|
||||
var totalScanned = 0L
|
||||
// Carry over last 3 bytes across buffer boundaries to detect split IDs
|
||||
var carry = ByteArray(0)
|
||||
override fun isSeekable(): Boolean = true
|
||||
|
||||
while (totalScanned < MAX_SCAN_BYTES) {
|
||||
val toRead = minOf(SCAN_BUFFER_SIZE, (MAX_SCAN_BYTES - totalScanned).toInt())
|
||||
val bytesRead: Int
|
||||
try {
|
||||
bytesRead = input.read(buffer, 0, toRead)
|
||||
} catch (_: Exception) {
|
||||
break
|
||||
}
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT) break
|
||||
override fun getDurationUs(): Long = durationUs
|
||||
|
||||
// Combine carry + new data for scanning
|
||||
val scanData = if (carry.isNotEmpty()) carry + buffer.copyOf(bytesRead) else buffer.copyOf(bytesRead)
|
||||
|
||||
for (i in 0..scanData.size - 4) {
|
||||
if (scanData[i] == CLUSTER_ID[0] &&
|
||||
scanData[i + 1] == CLUSTER_ID[1] &&
|
||||
scanData[i + 2] == CLUSTER_ID[2] &&
|
||||
scanData[i + 3] == CLUSTER_ID[3]
|
||||
) {
|
||||
// Compute the absolute byte position of this Cluster
|
||||
val clusterPosition = input.position - bytesRead - carry.size + i
|
||||
Log.d(TAG, "Found Cluster at byte $clusterPosition (scanned ${totalScanned + i} bytes)")
|
||||
seekPosition.position = clusterPosition
|
||||
delegate.seek(clusterPosition, pendingSeekTimeUs)
|
||||
pendingSeekTimeUs = C.TIME_UNSET
|
||||
return Extractor.RESULT_SEEK
|
||||
}
|
||||
}
|
||||
|
||||
// Keep last 3 bytes as carry for next iteration
|
||||
carry = if (scanData.size >= 3) scanData.copyOfRange(scanData.size - 3, scanData.size) else scanData.copyOf()
|
||||
totalScanned += bytesRead
|
||||
}
|
||||
|
||||
// Failed to find a Cluster — fall back to position 0
|
||||
Log.w(TAG, "No Cluster found after scanning $totalScanned bytes, resetting to start")
|
||||
seekPosition.position = 0
|
||||
delegate.seek(0, 0)
|
||||
return Extractor.RESULT_SEEK
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that intercepts [seekMap] calls to replace
|
||||
* [SeekMap.Unseekable] with an approximate proportional SeekMap.
|
||||
*/
|
||||
private inner class SeekInterceptingOutput(
|
||||
private val delegate: ExtractorOutput,
|
||||
) : ExtractorOutput {
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
|
||||
override fun seekMap(seekMap: SeekMap) {
|
||||
if (seekMap is SeekMap.Unseekable) {
|
||||
val durationUs = seekMap.durationUs
|
||||
if (durationUs != C.TIME_UNSET && durationUs > 0) {
|
||||
Log.i(TAG, "Replacing Unseekable with approximate SeekMap (duration=${durationUs / 1_000_000}s)")
|
||||
isApproximateSeeking = true
|
||||
delegate.seekMap(ApproximateSeekMap(durationUs))
|
||||
return
|
||||
}
|
||||
}
|
||||
// File has real Cues or unknown duration — pass through
|
||||
isApproximateSeeking = false
|
||||
delegate.seekMap(seekMap)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximate SeekMap that estimates byte positions proportionally.
|
||||
* Used when the MKV has no Cues but has a known duration.
|
||||
*/
|
||||
private inner class ApproximateSeekMap(
|
||||
private val durationUs: Long,
|
||||
) : SeekMap {
|
||||
|
||||
override fun isSeekable(): Boolean = true
|
||||
|
||||
override fun getDurationUs(): Long = durationUs
|
||||
|
||||
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
|
||||
val length = inputLength
|
||||
if (length == C.LENGTH_UNSET.toLong() || durationUs <= 0) {
|
||||
return SeekMap.SeekPoints(SeekPoint(0, 0))
|
||||
}
|
||||
val clampedTimeUs = timeUs.coerceIn(0, durationUs)
|
||||
val position = (clampedTimeUs.toDouble() / durationUs * length).toLong().coerceIn(0, length)
|
||||
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
|
||||
}
|
||||
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
|
||||
val length = inputLength
|
||||
if (length == C.LENGTH_UNSET.toLong() || durationUs <= 0) {
|
||||
return SeekMap.SeekPoints(SeekPoint(0, 0))
|
||||
}
|
||||
val clampedTimeUs = timeUs.coerceIn(0, durationUs)
|
||||
val position = (clampedTimeUs.toDouble() / durationUs * length).toLong().coerceIn(0, length)
|
||||
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,85 +1,362 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.content.Context
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaCodecList
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
|
||||
enum class DvConversionMode { DISABLED, DV81, HEVC_STRIP }
|
||||
|
||||
object DoviBridge {
|
||||
private const val TAG = "DoviBridge"
|
||||
private const val TAG = "DoviBridge"
|
||||
|
||||
private val nativeLoaded: Boolean by lazy {
|
||||
try {
|
||||
System.loadLibrary("dovi_bridge")
|
||||
true
|
||||
} catch (_: UnsatisfiedLinkError) {
|
||||
Log.w(TAG, "Native lib not found")
|
||||
false
|
||||
data class DvAutoDecision(
|
||||
val mode: DvConversionMode,
|
||||
val reason: String,
|
||||
val bridgeReady: Boolean,
|
||||
val displayDv: Boolean,
|
||||
val nativeDecoder: Boolean,
|
||||
val advertisedP7: Boolean,
|
||||
val advertisedP8: Boolean,
|
||||
val decoders: String,
|
||||
val displayHdr: String
|
||||
) {
|
||||
fun logMessage(): String = "AUTO P7 DV decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
|
||||
"displayDV=$displayDv, nativeDecoder=$nativeDecoder, advertisedP7=$advertisedP7, " +
|
||||
"advertisedP8=$advertisedP8, decoders=$decoders, displayHdr=$displayHdr"
|
||||
}
|
||||
|
||||
data class Dv7FallbackDecision(
|
||||
val mode: DvConversionMode,
|
||||
val reason: String,
|
||||
val bridgeReady: Boolean,
|
||||
val displayDv: Boolean,
|
||||
val advertisedP8: Boolean,
|
||||
val displayHdr: String
|
||||
) {
|
||||
fun logMessage(): String = "DV7 fallback decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
|
||||
"displayDV=$displayDv, advertisedP8=$advertisedP8, displayHdr=$displayHdr"
|
||||
}
|
||||
|
||||
private val DOLBY_VISION_MIME_TYPES = setOf(
|
||||
"video/dolby-vision",
|
||||
"video/hevcdv",
|
||||
"video/dv_hevc"
|
||||
)
|
||||
|
||||
const val CONVERT_FAILED = -1
|
||||
const val DESTINATION_TOO_SMALL = -2
|
||||
|
||||
private data class DvProfileLevel(val profile: Int, val level: Int)
|
||||
|
||||
private data class DvDecoderCapability(
|
||||
val name: String,
|
||||
val mimeType: String,
|
||||
val profileLevels: List<DvProfileLevel>
|
||||
)
|
||||
|
||||
private val nativeLoaded: Boolean by lazy {
|
||||
try {
|
||||
System.loadLibrary("dovi_bridge")
|
||||
true
|
||||
} catch (_: UnsatisfiedLinkError) {
|
||||
Log.w(TAG, "Native lib not found")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private val conversionPathReady: Boolean by lazy {
|
||||
nativeLoaded && runCatching { nativeIsConversionPathReady() }.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun isAvailable(): Boolean = conversionPathReady
|
||||
|
||||
private val dolbyVisionDecoders: List<DvDecoderCapability> by lazy {
|
||||
try {
|
||||
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
|
||||
codecList.codecInfos.flatMap { info ->
|
||||
if (info.isEncoder) {
|
||||
emptyList()
|
||||
} else {
|
||||
info.supportedTypes.mapNotNull { type ->
|
||||
if (!DOLBY_VISION_MIME_TYPES.contains(type.lowercase())) return@mapNotNull null
|
||||
val capabilities = runCatching { info.getCapabilitiesForType(type) }
|
||||
.onFailure { Log.w(TAG, "Failed to query ${info.name} capabilities for $type", it) }
|
||||
.getOrNull()
|
||||
?: return@mapNotNull null
|
||||
DvDecoderCapability(
|
||||
name = info.name,
|
||||
mimeType = type,
|
||||
profileLevels = capabilities.profileLevels.map { DvProfileLevel(it.profile, it.level) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to query native Dolby Vision decoder support", e)
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
val hasNativeDolbyVisionDecoder: Boolean by lazy {
|
||||
dolbyVisionDecoders.isNotEmpty().also {
|
||||
Log.i(TAG, "Native Dolby Vision decoder available: $it; decoders=${describeDolbyVisionDecoders()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceAdvertisesDvProfile(profile: Int, minApi: Int = 0): Boolean {
|
||||
if (Build.VERSION.SDK_INT < minApi) return false
|
||||
return dolbyVisionDecoders.any { decoder ->
|
||||
decoder.profileLevels.any { it.profile == profile }
|
||||
}
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile7: Boolean by lazy {
|
||||
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb)
|
||||
.also { Log.i(TAG, "Device advertises exact DV Profile 7 (DvheDtb): $it") }
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile8: Boolean by lazy {
|
||||
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
|
||||
.also { Log.i(TAG, "Device advertises DV Profile 8 (DvheSt): $it") }
|
||||
}
|
||||
|
||||
fun displaySupportsDolbyVision(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||
Log.i(TAG, "Display Dolby Vision support: false (HDR capabilities require API 24, device API=${Build.VERSION.SDK_INT})")
|
||||
return false
|
||||
}
|
||||
|
||||
fun isAvailable(): Boolean = nativeLoaded &&
|
||||
runCatching { nativeIsConversionPathReady() }.getOrDefault(false)
|
||||
val display = getCurrentDisplay(context)
|
||||
if (display == null) {
|
||||
Log.i(TAG, "Display Dolby Vision support: false (no active display)")
|
||||
return false
|
||||
}
|
||||
|
||||
private fun deviceSupportsDvProfile(profile: Int, minApi: Int = 0): Boolean {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT < minApi) return false
|
||||
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
|
||||
return codecList.codecInfos.any { info ->
|
||||
!info.isEncoder && info.supportedTypes.any { type ->
|
||||
type.equals("video/dolby-vision", ignoreCase = true) &&
|
||||
info.getCapabilitiesForType(type).profileLevels.any { it.profile == profile }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to query DV profile $profile support", e)
|
||||
return false
|
||||
val hdrTypes = runCatching { getDisplayHdrTypes(display) }.getOrElse { error ->
|
||||
Log.w(TAG, "Display Dolby Vision support: false (failed to query HDR types)", error)
|
||||
return false
|
||||
}
|
||||
val supported = hdrTypes.contains(Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION)
|
||||
Log.i(TAG, "Display Dolby Vision support: $supported; ${describeDisplayHdrCapabilities(display)}")
|
||||
return supported
|
||||
}
|
||||
|
||||
fun describeDisplayHdrCapabilities(context: Context): String {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "HDR capabilities unavailable (API=${Build.VERSION.SDK_INT})"
|
||||
val display = getCurrentDisplay(context) ?: return "HDR capabilities unavailable (no active display)"
|
||||
return describeDisplayHdrCapabilities(display)
|
||||
}
|
||||
|
||||
fun logSupportSummary(context: Context) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"DV support summary: bridgeReady=${isAvailable()}, displayDV=${displaySupportsDolbyVision(context)}, " +
|
||||
"nativeDecoder=$hasNativeDolbyVisionDecoder, advertisedP7=$deviceSupportsDvProfile7, " +
|
||||
"advertisedP8=$deviceSupportsDvProfile8, decoders=${describeDolbyVisionDecoders()}, " +
|
||||
"displayHdr=${describeDisplayHdrCapabilities(context)}"
|
||||
)
|
||||
}
|
||||
|
||||
fun getConversionDecision(context: Context): DvAutoDecision {
|
||||
val bridgeReady = isAvailable()
|
||||
val displayDv = displaySupportsDolbyVision(context)
|
||||
val nativeDecoder = hasNativeDolbyVisionDecoder
|
||||
val advertisedP7 = deviceSupportsDvProfile7
|
||||
val advertisedP8 = deviceSupportsDvProfile8
|
||||
|
||||
val mode = when {
|
||||
!displayDv -> DvConversionMode.HEVC_STRIP
|
||||
advertisedP7 -> DvConversionMode.DISABLED
|
||||
advertisedP8 && bridgeReady -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
}
|
||||
val reason = when {
|
||||
!displayDv -> "active display does not support Dolby Vision; stripping DV metadata for HEVC fallback"
|
||||
advertisedP7 -> "active display supports Dolby Vision and decoder advertises exact Profile 7; trying native DV first"
|
||||
advertisedP8 && bridgeReady -> "active display supports Dolby Vision and decoder advertises Profile 8; converting to Profile 8.1"
|
||||
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
|
||||
else -> "Dolby Vision output path is unavailable; stripping DV metadata for HEVC fallback"
|
||||
}
|
||||
val decision = DvAutoDecision(
|
||||
mode = mode,
|
||||
reason = reason,
|
||||
bridgeReady = bridgeReady,
|
||||
displayDv = displayDv,
|
||||
nativeDecoder = nativeDecoder,
|
||||
advertisedP7 = advertisedP7,
|
||||
advertisedP8 = advertisedP8,
|
||||
decoders = describeDolbyVisionDecoders(),
|
||||
displayHdr = describeDisplayHdrCapabilities(context)
|
||||
)
|
||||
Log.i(TAG, decision.logMessage())
|
||||
return decision
|
||||
}
|
||||
|
||||
fun getConversionMode(context: Context): DvConversionMode = getConversionDecision(context).mode
|
||||
|
||||
/** Get the fallback mode when native DV7 decoding fails. */
|
||||
fun getDv7FallbackDecision(context: Context): Dv7FallbackDecision {
|
||||
val bridgeReady = isAvailable()
|
||||
val displayDv = displaySupportsDolbyVision(context)
|
||||
val advertisedP8 = deviceSupportsDvProfile8
|
||||
val mode = if (displayDv && advertisedP8 && bridgeReady) DvConversionMode.DV81 else DvConversionMode.HEVC_STRIP
|
||||
val reason = when {
|
||||
mode == DvConversionMode.DV81 -> "display supports Dolby Vision and decoder advertises Profile 8"
|
||||
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
|
||||
else -> "Dolby Vision output or Profile 8 support is unavailable"
|
||||
}
|
||||
val decision = Dv7FallbackDecision(
|
||||
mode = mode,
|
||||
reason = reason,
|
||||
bridgeReady = bridgeReady,
|
||||
displayDv = displayDv,
|
||||
advertisedP8 = advertisedP8,
|
||||
displayHdr = describeDisplayHdrCapabilities(context)
|
||||
)
|
||||
Log.i(TAG, decision.logMessage())
|
||||
return decision
|
||||
}
|
||||
|
||||
fun getDv7FallbackMode(context: Context): DvConversionMode = getDv7FallbackDecision(context).mode
|
||||
|
||||
private fun getCurrentDisplay(context: Context): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
context.display
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
(context.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.defaultDisplay
|
||||
}
|
||||
|
||||
private fun describeDolbyVisionDecoders(): String {
|
||||
if (dolbyVisionDecoders.isEmpty()) return "none"
|
||||
return dolbyVisionDecoders.joinToString { decoder ->
|
||||
val profiles = if (decoder.profileLevels.isEmpty()) {
|
||||
"none"
|
||||
} else {
|
||||
decoder.profileLevels.joinToString(prefix = "[", postfix = "]") {
|
||||
"${describeDvProfile(it.profile)}/${describeDvLevel(it.level)}"
|
||||
}
|
||||
}
|
||||
"${decoder.name}(${decoder.mimeType}, profiles=$profiles)"
|
||||
}
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile7: Boolean by lazy {
|
||||
deviceSupportsDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr)
|
||||
.also { Log.i(TAG, "Device DV Profile 7 support: $it") }
|
||||
private fun describeHdrTypes(hdrTypes: IntArray): String {
|
||||
if (hdrTypes.isEmpty()) return "none"
|
||||
return hdrTypes.joinToString(prefix = "[", postfix = "]") { type ->
|
||||
when (type) {
|
||||
Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "DOLBY_VISION"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10"
|
||||
Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10_PLUS"
|
||||
else -> "unknown(${hex(type)})"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile8: Boolean by lazy {
|
||||
deviceSupportsDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
|
||||
.also { Log.i(TAG, "Device DV Profile 8 support: $it") }
|
||||
private fun describeDisplayHdrCapabilities(display: Display): String {
|
||||
val hdrCapabilities = display.hdrCapabilities
|
||||
val parts = mutableListOf(
|
||||
"display=${display.displayId}:${display.name}",
|
||||
"activeMode=${describeDisplayMode(display.mode)}",
|
||||
"hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}",
|
||||
"desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
|
||||
"maxAvg=${formatLuminance(hdrCapabilities.desiredMaxAverageLuminance)}, " +
|
||||
"min=${formatLuminance(hdrCapabilities.desiredMinLuminance)}"
|
||||
)
|
||||
parts += "supportedModes=${display.supportedModes.joinToString(prefix = "[", postfix = "]") { describeDisplayMode(it) }}"
|
||||
return parts.joinToString(prefix = "{", postfix = "}")
|
||||
}
|
||||
|
||||
private fun getDisplayHdrTypes(display: Display): IntArray = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
display.mode.supportedHdrTypes
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
display.hdrCapabilities.supportedHdrTypes
|
||||
}
|
||||
|
||||
private fun describeDisplayMode(mode: Display.Mode): String {
|
||||
val hdr = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
", hdr=${describeHdrTypes(mode.supportedHdrTypes)}"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz$hdr"
|
||||
}
|
||||
|
||||
fun getConversionMode(): DvConversionMode = when {
|
||||
!isAvailable() -> DvConversionMode.DISABLED
|
||||
deviceSupportsDvProfile7 -> DvConversionMode.DISABLED // try native first; ExoPlayerCore retries with conversion on failure
|
||||
deviceSupportsDvProfile8 -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
private fun formatLuminance(value: Float): String = if (value.isNaN() || value <= 0f) "unknown" else "${value}nits"
|
||||
|
||||
private fun describeDvProfile(profile: Int): String = when (profile) {
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPer -> "P0/DvavPer"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPen -> "P1/DvavPen"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDer -> "P2/DvheDer"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDen -> "P3/DvheDen"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr -> "P4/DvheDtr"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheStn -> "P5/DvheStn"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDth -> "P6/DvheDth"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb -> "P7/DvheDtb"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt -> "P8/DvheSt"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavSe -> "P9/DvavSe"
|
||||
else -> "unknown(${hex(profile)})"
|
||||
}
|
||||
|
||||
private fun describeDvLevel(level: Int): String = when (level) {
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd24 -> "L1/Hd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd30 -> "L2/Hd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd24 -> "L3/Fhd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd30 -> "L4/Fhd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd60 -> "L5/Fhd60"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd24 -> "L6/Uhd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd30 -> "L7/Uhd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd48 -> "L8/Uhd48"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd60 -> "L9/Uhd60"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd120 -> "L10/Uhd120"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k30 -> "L11/8k30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k60 -> "L12/8k60"
|
||||
else -> "unknown(${hex(level)})"
|
||||
}
|
||||
|
||||
private fun hex(value: Int): String = "0x${value.toString(16)}"
|
||||
|
||||
fun convertRpuNalu(
|
||||
payload: ByteArray,
|
||||
payloadOffset: Int,
|
||||
payloadLength: Int,
|
||||
output: ByteArray,
|
||||
outputOffset: Int,
|
||||
outputCapacity: Int,
|
||||
mode: Int = 2
|
||||
): Int {
|
||||
if (!conversionPathReady || payloadLength <= 0) return CONVERT_FAILED
|
||||
return runCatching {
|
||||
nativeConvertDv7RpuToDv81(payload, payloadOffset, payloadLength, output, outputOffset, outputCapacity, mode)
|
||||
}
|
||||
.onFailure { Log.w(TAG, "RPU conversion failed: ${it.message}") }
|
||||
.getOrDefault(CONVERT_FAILED)
|
||||
}
|
||||
|
||||
/** Get the fallback mode when native DV7 decoding fails. */
|
||||
fun getDv7FallbackMode(): DvConversionMode = when {
|
||||
deviceSupportsDvProfile8 -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
}
|
||||
fun getVersion(): String? {
|
||||
if (!nativeLoaded) return null
|
||||
return runCatching { nativeGetBridgeVersion() }.getOrNull()
|
||||
}
|
||||
|
||||
fun convertRpuNalu(payload: ByteArray, mode: Int = 2): ByteArray? {
|
||||
if (!isAvailable() || payload.isEmpty()) return null
|
||||
return runCatching { nativeConvertDv7RpuToDv81(payload, mode) }
|
||||
.onFailure { Log.w(TAG, "RPU conversion failed: ${it.message}") }
|
||||
.getOrNull()
|
||||
}
|
||||
@JvmStatic
|
||||
private external fun nativeConvertDv7RpuToDv81(
|
||||
payload: ByteArray,
|
||||
payloadOffset: Int,
|
||||
payloadLength: Int,
|
||||
output: ByteArray,
|
||||
outputOffset: Int,
|
||||
outputCapacity: Int,
|
||||
mode: Int
|
||||
): Int
|
||||
|
||||
fun getVersion(): String? {
|
||||
if (!nativeLoaded) return null
|
||||
return runCatching { nativeGetBridgeVersion() }.getOrNull()
|
||||
}
|
||||
@JvmStatic
|
||||
private external fun nativeIsConversionPathReady(): Boolean
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeConvertDv7RpuToDv81(payload: ByteArray, mode: Int): ByteArray?
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeIsConversionPathReady(): Boolean
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeGetBridgeVersion(): String
|
||||
@JvmStatic
|
||||
private external fun nativeGetBridgeVersion(): String
|
||||
}
|
||||
|
||||
@@ -14,22 +14,23 @@ import androidx.media3.extractor.TrackOutput
|
||||
* Shared by DoviExtractorWrapper for both MP4 and MKV containers.
|
||||
*/
|
||||
class DoviExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput,
|
||||
private val dvMode: DvConversionMode,
|
||||
private val onVideoTrackWrapped: (DoviConvertingTrackOutput) -> Unit,
|
||||
private val delegate: ExtractorOutput,
|
||||
private val dvMode: DvConversionMode,
|
||||
private val emitLog: ((String, String, String) -> Unit)?,
|
||||
private val onVideoTrackWrapped: (DoviConvertingTrackOutput) -> Unit
|
||||
) : ExtractorOutput {
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (type == C.TRACK_TYPE_VIDEO) {
|
||||
val wrapper = DoviConvertingTrackOutput(original, dvMode)
|
||||
onVideoTrackWrapped(wrapper)
|
||||
return wrapper
|
||||
}
|
||||
return original
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (type == C.TRACK_TYPE_VIDEO) {
|
||||
val wrapper = DoviConvertingTrackOutput(original, dvMode, emitLog)
|
||||
onVideoTrackWrapped(wrapper)
|
||||
return wrapper
|
||||
}
|
||||
return original
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,23 +39,23 @@ class DoviExtractorOutputWrapper(
|
||||
* DV Profile 7 → 8.1 conversion via inline NAL processing.
|
||||
*/
|
||||
class DoviExtractorWrapper(
|
||||
private val delegate: Extractor,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val delegate: Extractor,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val emitLog: ((String, String, String) -> Unit)? = null
|
||||
) : Extractor {
|
||||
|
||||
@Volatile var doviTrackOutput: DoviConvertingTrackOutput? = null
|
||||
private set
|
||||
@Volatile var doviTrackOutput: DoviConvertingTrackOutput? = null
|
||||
private set
|
||||
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(DoviExtractorOutputWrapper(output, dvMode) { doviTrackOutput = it })
|
||||
}
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(DoviExtractorOutputWrapper(output, dvMode, emitLog) { doviTrackOutput = it })
|
||||
}
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int =
|
||||
delegate.read(input, seekPosition)
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int = delegate.read(input, seekPosition)
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) = delegate.seek(position, timeUs)
|
||||
override fun seek(position: Long, timeUs: Long) = delegate.seek(position, timeUs)
|
||||
|
||||
override fun release() = delegate.release()
|
||||
override fun release() = delegate.release()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* In-place sanitizer for HEVC Annex B buffers carrying both Dolby Vision and HDR10+
|
||||
* dynamic metadata. Buggy chipsets (Fire TV 4K Max, MediaTek-based Google TV, ...)
|
||||
* crash or black-screen when a native DV codec also receives in-band HDR10+ SEI, so
|
||||
* only the metadata the active decode path consumes may be kept:
|
||||
*
|
||||
* - Native DV codec: strip HDR10+ SEI NALs (types 39/40 with ST 2094-40 payload),
|
||||
* the decoder follows the DV RPU. Port of androidx/media#3085 / Kodi xbmc#24584.
|
||||
* - HEVC fallback for a DV format: strip DV RPU/EL NALs (types 62/63) instead,
|
||||
* leaving HDR10+ for the display.
|
||||
*
|
||||
* Runs on the playback thread against MediaCodec's direct input buffers, where
|
||||
* per-byte ByteBuffer accessor calls are far too slow for high-bitrate UHD remuxes
|
||||
* (#1313). Each sample is therefore staged through a reusable heap array with a
|
||||
* single bulk get, scanned and compacted with array ops, and only the modified tail
|
||||
* is written back. Instances are not thread-safe: use one per renderer.
|
||||
*
|
||||
* Pure JVM (no android/media3 imports) so it stays unit-testable on the host.
|
||||
*/
|
||||
class DvBitstreamSanitizer {
|
||||
|
||||
private companion object {
|
||||
const val NAL_TYPE_PREFIX_SEI = 39
|
||||
const val NAL_TYPE_SUFFIX_SEI = 40
|
||||
const val NAL_TYPE_UNSPEC62 = 62 // DV RPU
|
||||
const val NAL_TYPE_UNSPEC63 = 63 // DV Enhancement Layer
|
||||
|
||||
const val SEI_PAYLOAD_TYPE_ITU_T_T35 = 4
|
||||
|
||||
const val INITIAL_SCRATCH_SIZE = 256 * 1024
|
||||
}
|
||||
|
||||
/** Reusable staging buffer — grown as needed, never shrunk. */
|
||||
private var scratch = ByteArray(INITIAL_SCRATCH_SIZE)
|
||||
|
||||
/**
|
||||
* Scans `[position, limit)` of [data] for Annex B NAL units and removes the selected
|
||||
* metadata NALs by compacting the buffer in place and reducing its limit. The position
|
||||
* is left unchanged. Returns the number of NAL units stripped.
|
||||
*
|
||||
* A sample with no start codes at all is left untouched: it cannot contain the
|
||||
* targeted NALs, and emptying it would only confuse the decoder.
|
||||
*/
|
||||
fun sanitize(data: ByteBuffer, stripHdr10PlusSei: Boolean, stripDvRpu: Boolean): Int {
|
||||
val startPos = data.position()
|
||||
val len = data.limit() - startPos
|
||||
if (len == 0) return 0
|
||||
if (scratch.size < len) scratch = ByteArray(maxOf(len, scratch.size * 2))
|
||||
val buf = scratch
|
||||
data.get(buf, 0, len)
|
||||
data.position(startPos)
|
||||
|
||||
var writeLen = 0
|
||||
var firstModified = -1
|
||||
var strippedCount = 0
|
||||
var nalStartIndex = -1
|
||||
var startCodeLen = 0
|
||||
|
||||
var i = 0
|
||||
while (i <= len) {
|
||||
// Find next start code or end of buffer.
|
||||
val atEnd = i == len
|
||||
var foundStartCode = false
|
||||
var nextStartCodeLen = 0
|
||||
if (!atEnd && i + 2 < len && buf[i].toInt() == 0 && buf[i + 1].toInt() == 0) {
|
||||
if (buf[i + 2].toInt() == 1) {
|
||||
foundStartCode = true
|
||||
nextStartCodeLen = 3
|
||||
} else if (buf[i + 2].toInt() == 0 && i + 3 < len && buf[i + 3].toInt() == 1) {
|
||||
foundStartCode = true
|
||||
nextStartCodeLen = 4
|
||||
}
|
||||
}
|
||||
|
||||
if (foundStartCode || atEnd) {
|
||||
if (nalStartIndex >= 0) {
|
||||
// Complete NAL unit (including its start code) from nalStartIndex to i.
|
||||
val nalDataStart = nalStartIndex + startCodeLen
|
||||
val nalEnd = i
|
||||
var strip = false
|
||||
|
||||
if (nalEnd - nalDataStart >= 2) {
|
||||
// HEVC NAL header: forbidden_zero_bit(1) + nal_unit_type(6) + nuh_layer_id MSB(1).
|
||||
val nalUnitType = (buf[nalDataStart].toInt() and 0x7E) shr 1
|
||||
strip = when (nalUnitType) {
|
||||
NAL_TYPE_UNSPEC62, NAL_TYPE_UNSPEC63 -> stripDvRpu
|
||||
NAL_TYPE_PREFIX_SEI, NAL_TYPE_SUFFIX_SEI ->
|
||||
stripHdr10PlusSei && isHdr10PlusSeiNalUnit(buf, nalDataStart + 2, nalEnd)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
if (strip) {
|
||||
strippedCount++
|
||||
if (firstModified < 0) firstModified = writeLen
|
||||
} else {
|
||||
if (writeLen != nalStartIndex) {
|
||||
// Also reached with zero strips when bytes precede the first start code.
|
||||
if (firstModified < 0) firstModified = writeLen
|
||||
System.arraycopy(buf, nalStartIndex, buf, writeLen, nalEnd - nalStartIndex)
|
||||
}
|
||||
writeLen += nalEnd - nalStartIndex
|
||||
}
|
||||
}
|
||||
nalStartIndex = i
|
||||
startCodeLen = nextStartCodeLen
|
||||
i += if (nextStartCodeLen > 0) nextStartCodeLen else 1
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if (writeLen == len || firstModified < 0) return 0
|
||||
|
||||
// Bytes before firstModified are byte-identical to the buffer; write back only the tail.
|
||||
data.position(startPos + firstModified)
|
||||
data.put(buf, firstModified, writeLen - firstModified)
|
||||
data.limit(startPos + writeLen)
|
||||
data.position(startPos)
|
||||
return strippedCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the SEI RBSP (starting after the 2-byte HEVC NAL header) begins with an
|
||||
* HDR10+ message: user_data_registered_itu_t_t35 with country code 0xB5 (United States),
|
||||
* provider code 0x003C (Samsung), provider oriented code 0x0001, application identifier 4
|
||||
* (ST 2094-40), application version 0 or 1. Malformed/truncated data returns false so the
|
||||
* NAL is kept.
|
||||
*/
|
||||
private fun isHdr10PlusSeiNalUnit(buf: ByteArray, rbspStart: Int, nalEnd: Int): Boolean {
|
||||
var pos = rbspStart
|
||||
if (pos >= nalEnd) return false
|
||||
|
||||
// SEI payload type: accumulated 0xFF bytes plus the final byte.
|
||||
var payloadType = 0
|
||||
while (pos < nalEnd) {
|
||||
val b = buf[pos++].toInt() and 0xFF
|
||||
payloadType += b
|
||||
if (b != 0xFF) break
|
||||
}
|
||||
|
||||
// SEI payload size, same encoding.
|
||||
var payloadSize = 0
|
||||
while (pos < nalEnd) {
|
||||
val b = buf[pos++].toInt() and 0xFF
|
||||
payloadSize += b
|
||||
if (b != 0xFF) break
|
||||
}
|
||||
|
||||
if (payloadType != SEI_PAYLOAD_TYPE_ITU_T_T35 || payloadSize < 7 || pos + 7 > nalEnd) {
|
||||
return false
|
||||
}
|
||||
|
||||
// The identifier bytes (B5 00 3C 00 01 04 00/01) cannot contain the 0x000003 emulation
|
||||
// prevention pattern, so they can be read without RBSP unescaping.
|
||||
val countryCode = buf[pos].toInt() and 0xFF
|
||||
val providerCode = ((buf[pos + 1].toInt() and 0xFF) shl 8) or (buf[pos + 2].toInt() and 0xFF)
|
||||
val orientedCode = ((buf[pos + 3].toInt() and 0xFF) shl 8) or (buf[pos + 4].toInt() and 0xFF)
|
||||
val appIdentifier = buf[pos + 5].toInt() and 0xFF
|
||||
val appVersion = buf[pos + 6].toInt() and 0xFF
|
||||
|
||||
return countryCode == 0xB5 &&
|
||||
providerCode == 0x003C &&
|
||||
orientedCode == 0x0001 &&
|
||||
appIdentifier == 4 &&
|
||||
(appVersion == 0 || appVersion == 1)
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,16 @@ package com.edde746.plezy.exoplayer
|
||||
import android.content.Context
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.PlaybackParameters
|
||||
import androidx.media3.common.util.Clock
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.decoder.DecoderInputBuffer
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.Renderer
|
||||
import androidx.media3.exoplayer.analytics.PlayerId
|
||||
import androidx.media3.exoplayer.audio.AudioOutput
|
||||
import androidx.media3.exoplayer.audio.AudioOutputProvider
|
||||
@@ -16,7 +21,10 @@ import androidx.media3.exoplayer.audio.AudioTrackAudioOutputProvider
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioSink
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioTrackBufferSizeProvider
|
||||
import androidx.media3.exoplayer.audio.ForwardingAudioSink
|
||||
import androidx.media3.exoplayer.Renderer
|
||||
import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter
|
||||
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
|
||||
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
|
||||
import androidx.media3.exoplayer.video.VideoRendererEventListener
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.math.abs
|
||||
@@ -24,38 +32,93 @@ import kotlin.math.abs
|
||||
@OptIn(UnstableApi::class)
|
||||
class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context) {
|
||||
|
||||
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
|
||||
val audioDelayUs = AtomicLong(0L)
|
||||
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
|
||||
val audioDelayUs = AtomicLong(0L)
|
||||
|
||||
override fun buildAudioSink(
|
||||
context: Context,
|
||||
enableFloatOutput: Boolean,
|
||||
enableAudioOutputPlaybackParams: Boolean
|
||||
): AudioSink {
|
||||
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
|
||||
/** Returns whether direct encoded output should be hidden so decoded PCM output can be selected. */
|
||||
var shouldBlockDirectAudioOutput: ((Format) -> Boolean)? = null
|
||||
|
||||
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
|
||||
.setMinPcmBufferDurationUs(500_000)
|
||||
.setMaxPcmBufferDurationUs(1_000_000)
|
||||
.setPcmBufferMultiplicationFactor(4)
|
||||
.build()
|
||||
/** Called before Media3 reacts to an audio route/capability change. */
|
||||
var onAudioCapabilitiesChanged: (() -> Unit)? = null
|
||||
|
||||
val realProvider = AudioTrackAudioOutputProvider.Builder(context)
|
||||
.setAudioTrackBufferSizeProvider(bufferSizeProvider)
|
||||
.build()
|
||||
var audioDiagnosticsLogger: ((String, String, String) -> Unit)? = null
|
||||
|
||||
// Shared position: RawPositionAudioOutput writes the raw AudioTrack position,
|
||||
// PositionFixAudioSink reads it to bypass DefaultAudioSink's writtenDuration clamp.
|
||||
val rawPositionUs = AtomicLong(Long.MIN_VALUE)
|
||||
var videoDiagnosticsLogger: ((String, String, String) -> Unit)? = null
|
||||
|
||||
val defaultSink = DefaultAudioSink.Builder(context)
|
||||
.setEnableFloatOutput(enableFloatOutput)
|
||||
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
|
||||
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs))
|
||||
.build()
|
||||
override fun buildVideoRenderers(
|
||||
context: Context,
|
||||
extensionRendererMode: Int,
|
||||
mediaCodecSelector: MediaCodecSelector,
|
||||
enableDecoderFallback: Boolean,
|
||||
eventHandler: Handler,
|
||||
eventListener: VideoRendererEventListener,
|
||||
allowedVideoJoiningTimeMs: Long,
|
||||
out: ArrayList<Renderer>
|
||||
) {
|
||||
// Let super build the full list (it also appends extension renderers reflectively,
|
||||
// e.g. the jellyfin ffmpeg artifact's video renderer), then swap the stock
|
||||
// MediaCodecVideoRenderer for the DV-sanitizing variant at the same index.
|
||||
super.buildVideoRenderers(
|
||||
context,
|
||||
extensionRendererMode,
|
||||
mediaCodecSelector,
|
||||
enableDecoderFallback,
|
||||
eventHandler,
|
||||
eventListener,
|
||||
allowedVideoJoiningTimeMs,
|
||||
out
|
||||
)
|
||||
val index = out.indexOfFirst { it.javaClass == MediaCodecVideoRenderer::class.java }
|
||||
if (index < 0) return
|
||||
out[index] = DvSanitizingVideoRenderer(
|
||||
MediaCodecVideoRenderer.Builder(context)
|
||||
.setCodecAdapterFactory(codecAdapterFactory)
|
||||
.setMediaCodecSelector(mediaCodecSelector)
|
||||
.setAllowedJoiningTimeMs(allowedVideoJoiningTimeMs)
|
||||
.setEnableDecoderFallback(enableDecoderFallback)
|
||||
.setEventHandler(eventHandler)
|
||||
.setEventListener(eventListener)
|
||||
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
|
||||
videoDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
|
||||
return PositionFixAudioSink(defaultSink, rawPositionUs, audioDelayUs)
|
||||
}
|
||||
override fun buildAudioSink(
|
||||
context: Context,
|
||||
enableFloatOutput: Boolean,
|
||||
enableAudioOutputPlaybackParams: Boolean
|
||||
): AudioSink {
|
||||
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
|
||||
|
||||
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
|
||||
.setMinPcmBufferDurationUs(500_000)
|
||||
.setMaxPcmBufferDurationUs(1_000_000)
|
||||
.setPcmBufferMultiplicationFactor(4)
|
||||
.build()
|
||||
|
||||
val realProvider = AudioTrackAudioOutputProvider.Builder(context)
|
||||
.setAudioTrackBufferSizeProvider(bufferSizeProvider)
|
||||
.build()
|
||||
|
||||
// Shared position: RawPositionAudioOutput writes the raw AudioTrack position,
|
||||
// PositionFixAudioSink reads it to bypass DefaultAudioSink's writtenDuration clamp.
|
||||
val rawPositionUs = AtomicLong(Long.MIN_VALUE)
|
||||
|
||||
val defaultSink = DefaultAudioSink.Builder(context)
|
||||
.setEnableFloatOutput(enableFloatOutput)
|
||||
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
|
||||
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs, audioDiagnosticsLogger))
|
||||
.build()
|
||||
|
||||
return PositionFixAudioSink(
|
||||
defaultSink,
|
||||
rawPositionUs,
|
||||
audioDelayUs,
|
||||
shouldBlockDirectAudioOutput,
|
||||
onAudioCapabilitiesChanged,
|
||||
audioDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,130 +144,171 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
private class PositionFixAudioSink(
|
||||
sink: AudioSink,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val audioDelayUs: AtomicLong
|
||||
sink: AudioSink,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val audioDelayUs: AtomicLong,
|
||||
private val shouldBlockDirectAudioOutput: ((Format) -> Boolean)?,
|
||||
private val onAudioCapabilitiesChanged: (() -> Unit)?,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : ForwardingAudioSink(sink) {
|
||||
|
||||
private var startMediaTimeUs = Long.MIN_VALUE
|
||||
private var suppressedErrorCount = 0
|
||||
private var startMediaTimeUs = Long.MIN_VALUE
|
||||
private var suppressedErrorCount = 0
|
||||
|
||||
// Speed tracking for position bypass
|
||||
private var currentSpeed = 1.0f
|
||||
private var refMediaTimeUs = Long.MIN_VALUE
|
||||
private var refRawPositionUs = 0L
|
||||
// Speed tracking for position bypass
|
||||
private var currentSpeed = 1.0f
|
||||
private var refMediaTimeUs = Long.MIN_VALUE
|
||||
private var refRawPositionUs = 0L
|
||||
|
||||
// Transient counter-offset: after seek/flush, ramp offset from 0 to full
|
||||
// over recoveryDurationUs to prevent video frame drops.
|
||||
private var recoveryDurationUs = 0L
|
||||
// Transient counter-offset: after seek/flush, ramp offset from 0 to full
|
||||
// over recoveryDurationUs to prevent video frame drops.
|
||||
private var recoveryDurationUs = 0L
|
||||
private val loggedDirectBlockMimeTypes = mutableSetOf<String>()
|
||||
private var loggedFirstBuffer = false
|
||||
|
||||
override fun handleBuffer(
|
||||
buffer: ByteBuffer,
|
||||
presentationTimeUs: Long,
|
||||
encodedAccessUnitCount: Int
|
||||
): Boolean {
|
||||
if (startMediaTimeUs == Long.MIN_VALUE) {
|
||||
startMediaTimeUs = presentationTimeUs
|
||||
refMediaTimeUs = presentationTimeUs
|
||||
refRawPositionUs = 0
|
||||
val delayUs = audioDelayUs.get()
|
||||
recoveryDurationUs = if (delayUs == 0L) 0L else maxOf(200_000L, 2L * abs(delayUs))
|
||||
override fun supportsFormat(format: Format): Boolean {
|
||||
if (blocksDirectAudioOutput(format)) return false
|
||||
return super.supportsFormat(format)
|
||||
}
|
||||
|
||||
override fun getFormatSupport(format: Format): Int {
|
||||
if (blocksDirectAudioOutput(format)) return AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
return super.getFormatSupport(format)
|
||||
}
|
||||
|
||||
private fun blocksDirectAudioOutput(format: Format): Boolean {
|
||||
if (shouldBlockDirectAudioOutput?.invoke(format) != true) return false
|
||||
val mimeType = format.sampleMimeType ?: "unknown"
|
||||
if (loggedDirectBlockMimeTypes.add(mimeType)) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"audio",
|
||||
"Blocking direct $mimeType output; decoded PCM output will be preferred"
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun handleBuffer(
|
||||
buffer: ByteBuffer,
|
||||
presentationTimeUs: Long,
|
||||
encodedAccessUnitCount: Int
|
||||
): Boolean {
|
||||
if (!loggedFirstBuffer && buffer.hasRemaining()) {
|
||||
loggedFirstBuffer = true
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"audio-sink",
|
||||
"First buffer: size=${buffer.remaining()}B, pts=${presentationTimeUs}us, accessUnits=$encodedAccessUnitCount"
|
||||
)
|
||||
}
|
||||
if (startMediaTimeUs == Long.MIN_VALUE) {
|
||||
startMediaTimeUs = presentationTimeUs
|
||||
refMediaTimeUs = presentationTimeUs
|
||||
refRawPositionUs = 0
|
||||
val delayUs = audioDelayUs.get()
|
||||
recoveryDurationUs = if (delayUs == 0L) 0L else maxOf(200_000L, 2L * abs(delayUs))
|
||||
}
|
||||
return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
|
||||
}
|
||||
|
||||
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) {
|
||||
// Capture reference point before speed changes
|
||||
val rawPos = rawPositionUs.get()
|
||||
if (rawPos > 0 && refMediaTimeUs != Long.MIN_VALUE) {
|
||||
refMediaTimeUs = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
|
||||
refRawPositionUs = rawPos
|
||||
}
|
||||
currentSpeed = playbackParameters.speed
|
||||
super.setPlaybackParameters(playbackParameters)
|
||||
}
|
||||
|
||||
override fun getCurrentPositionUs(sourceEnded: Boolean): Long {
|
||||
val delegatePos = super.getCurrentPositionUs(sourceEnded)
|
||||
if (delegatePos == Long.MIN_VALUE || refMediaTimeUs == Long.MIN_VALUE) {
|
||||
return delegatePos
|
||||
}
|
||||
|
||||
val rawPos = rawPositionUs.get()
|
||||
val basePos = if (rawPos <= 0) {
|
||||
delegatePos
|
||||
} else {
|
||||
val expectedPos = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
|
||||
if (expectedPos > delegatePos + 30_000) expectedPos else delegatePos
|
||||
}
|
||||
|
||||
// Audio delay with transient counter-offset to prevent frame drops after seeks.
|
||||
// After flush, offset ramps linearly from 0 to full over recoveryDurationUs.
|
||||
val delayUs = audioDelayUs.get()
|
||||
if (delayUs == 0L) return basePos
|
||||
|
||||
val elapsedUs = basePos - startMediaTimeUs
|
||||
val netOffsetUs = if (recoveryDurationUs <= 0L || elapsedUs >= recoveryDurationUs) {
|
||||
delayUs
|
||||
} else {
|
||||
(delayUs * elapsedUs) / recoveryDurationUs
|
||||
}
|
||||
return basePos + netOffsetUs
|
||||
}
|
||||
|
||||
// --- Suppress timestamp discontinuity errors ---
|
||||
|
||||
override fun setListener(listener: AudioSink.Listener) {
|
||||
super.setListener(
|
||||
@OptIn(UnstableApi::class) object : AudioSink.Listener {
|
||||
override fun onPositionDiscontinuity() = listener.onPositionDiscontinuity()
|
||||
override fun onPositionAdvancing(playoutStartSystemTimeUs: Long) = listener.onPositionAdvancing(playoutStartSystemTimeUs)
|
||||
override fun onUnderrun(bufferSize: Int, bufferSizeMs: Long, elapsedSinceLastFeedMs: Long) = listener.onUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)
|
||||
override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) = listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
|
||||
override fun onOffloadBufferEmptying() = listener.onOffloadBufferEmptying()
|
||||
override fun onOffloadBufferFull() = listener.onOffloadBufferFull()
|
||||
override fun onAudioCapabilitiesChanged() {
|
||||
onAudioCapabilitiesChanged?.invoke()
|
||||
listener.onAudioCapabilitiesChanged()
|
||||
}
|
||||
return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
|
||||
}
|
||||
override fun onAudioTrackInitialized(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackInitialized(audioTrackConfig)
|
||||
override fun onAudioTrackReleased(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackReleased(audioTrackConfig)
|
||||
override fun onSilenceSkipped() = listener.onSilenceSkipped()
|
||||
override fun onAudioSessionIdChanged(audioSessionId: Int) = listener.onAudioSessionIdChanged(audioSessionId)
|
||||
|
||||
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) {
|
||||
// Capture reference point before speed changes
|
||||
val rawPos = rawPositionUs.get()
|
||||
if (rawPos > 0 && refMediaTimeUs != Long.MIN_VALUE) {
|
||||
refMediaTimeUs = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
|
||||
refRawPositionUs = rawPos
|
||||
override fun onAudioSinkError(audioSinkError: Exception) {
|
||||
if (isTimestampDiscontinuity(audioSinkError)) {
|
||||
suppressedErrorCount++
|
||||
return
|
||||
}
|
||||
listener.onAudioSinkError(audioSinkError)
|
||||
}
|
||||
currentSpeed = playbackParameters.speed
|
||||
super.setPlaybackParameters(playbackParameters)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override fun getCurrentPositionUs(sourceEnded: Boolean): Long {
|
||||
val delegatePos = super.getCurrentPositionUs(sourceEnded)
|
||||
if (delegatePos == Long.MIN_VALUE || refMediaTimeUs == Long.MIN_VALUE) {
|
||||
return delegatePos
|
||||
}
|
||||
override fun flush() {
|
||||
startMediaTimeUs = Long.MIN_VALUE
|
||||
refMediaTimeUs = Long.MIN_VALUE
|
||||
refRawPositionUs = 0
|
||||
recoveryDurationUs = 0L
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
super.flush()
|
||||
}
|
||||
|
||||
val rawPos = rawPositionUs.get()
|
||||
val basePos = if (rawPos <= 0) {
|
||||
delegatePos
|
||||
} else {
|
||||
val expectedPos = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
|
||||
if (expectedPos > delegatePos + 30_000) expectedPos else delegatePos
|
||||
}
|
||||
override fun reset() {
|
||||
startMediaTimeUs = Long.MIN_VALUE
|
||||
refMediaTimeUs = Long.MIN_VALUE
|
||||
refRawPositionUs = 0
|
||||
recoveryDurationUs = 0L
|
||||
currentSpeed = 1.0f
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
suppressedErrorCount = 0
|
||||
super.reset()
|
||||
}
|
||||
|
||||
// Audio delay with transient counter-offset to prevent frame drops after seeks.
|
||||
// After flush, offset ramps linearly from 0 to full over recoveryDurationUs.
|
||||
val delayUs = audioDelayUs.get()
|
||||
if (delayUs == 0L) return basePos
|
||||
|
||||
val elapsedUs = basePos - startMediaTimeUs
|
||||
val netOffsetUs = if (recoveryDurationUs <= 0L || elapsedUs >= recoveryDurationUs) {
|
||||
delayUs
|
||||
} else {
|
||||
(delayUs * elapsedUs) / recoveryDurationUs
|
||||
}
|
||||
return basePos + netOffsetUs
|
||||
}
|
||||
|
||||
// --- Suppress timestamp discontinuity errors ---
|
||||
|
||||
override fun setListener(listener: AudioSink.Listener) {
|
||||
super.setListener(@OptIn(UnstableApi::class) object : AudioSink.Listener {
|
||||
override fun onPositionDiscontinuity() = listener.onPositionDiscontinuity()
|
||||
override fun onPositionAdvancing(playoutStartSystemTimeUs: Long) = listener.onPositionAdvancing(playoutStartSystemTimeUs)
|
||||
override fun onUnderrun(bufferSize: Int, bufferSizeMs: Long, elapsedSinceLastFeedMs: Long) = listener.onUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)
|
||||
override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) = listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
|
||||
override fun onOffloadBufferEmptying() = listener.onOffloadBufferEmptying()
|
||||
override fun onOffloadBufferFull() = listener.onOffloadBufferFull()
|
||||
override fun onAudioCapabilitiesChanged() = listener.onAudioCapabilitiesChanged()
|
||||
override fun onAudioTrackInitialized(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackInitialized(audioTrackConfig)
|
||||
override fun onAudioTrackReleased(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackReleased(audioTrackConfig)
|
||||
override fun onSilenceSkipped() = listener.onSilenceSkipped()
|
||||
override fun onAudioSessionIdChanged(audioSessionId: Int) = listener.onAudioSessionIdChanged(audioSessionId)
|
||||
|
||||
override fun onAudioSinkError(audioSinkError: Exception) {
|
||||
if (isTimestampDiscontinuity(audioSinkError)) {
|
||||
suppressedErrorCount++
|
||||
return
|
||||
}
|
||||
listener.onAudioSinkError(audioSinkError)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
override fun flush() {
|
||||
startMediaTimeUs = Long.MIN_VALUE
|
||||
refMediaTimeUs = Long.MIN_VALUE
|
||||
refRawPositionUs = 0
|
||||
recoveryDurationUs = 0L
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
super.flush()
|
||||
}
|
||||
|
||||
override fun reset() {
|
||||
startMediaTimeUs = Long.MIN_VALUE
|
||||
refMediaTimeUs = Long.MIN_VALUE
|
||||
refRawPositionUs = 0
|
||||
recoveryDurationUs = 0L
|
||||
currentSpeed = 1.0f
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
suppressedErrorCount = 0
|
||||
super.reset()
|
||||
}
|
||||
|
||||
private fun isTimestampDiscontinuity(e: Exception): Boolean {
|
||||
val name = e.javaClass.simpleName
|
||||
val msg = e.message ?: ""
|
||||
return name == "InvalidAudioTrackTimestampException" ||
|
||||
name == "UnexpectedDiscontinuityException" ||
|
||||
msg.contains("timestamp discontinuity", ignoreCase = true)
|
||||
}
|
||||
private fun isTimestampDiscontinuity(e: Exception): Boolean {
|
||||
val name = e.javaClass.simpleName
|
||||
val msg = e.message ?: ""
|
||||
return name == "InvalidAudioTrackTimestampException" ||
|
||||
name == "UnexpectedDiscontinuityException" ||
|
||||
msg.contains("timestamp discontinuity", ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,12 +319,102 @@ private class PositionFixAudioSink(
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class SubtitleDelayRenderer(
|
||||
private val delegate: Renderer,
|
||||
private val delayUs: AtomicLong
|
||||
private val delegate: Renderer,
|
||||
private val delayUs: AtomicLong
|
||||
) : Renderer by delegate {
|
||||
override fun render(positionUs: Long, elapsedRealtimeUs: Long) {
|
||||
delegate.render(positionUs - delayUs.get(), elapsedRealtimeUs)
|
||||
override fun render(positionUs: Long, elapsedRealtimeUs: Long) {
|
||||
delegate.render(positionUs - delayUs.get(), elapsedRealtimeUs)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MediaCodecVideoRenderer that resolves the DV / HDR10+ dual-dynamic-metadata conflict
|
||||
* per decode path (#1296, generalizes androidx/media#3085):
|
||||
* - native DV codec selected (media3 only selects one when decoder AND display support DV):
|
||||
* strip in-band HDR10+ SEI — conflicting dynamic metadata crashes Fire TV-class chipsets
|
||||
* - HEVC fallback for an HEVC-based DV format: strip DV RPU/EL NALs (profiles 7/8, where the
|
||||
* base layer remains valid HDR10/HLG), keeping HDR10+ for the display
|
||||
*
|
||||
* Flags are reassigned on every codec init: tunneling toggles and DV retries re-init the
|
||||
* codec without recreating renderers, and decoder fallback can switch the codec MIME.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class DvSanitizingVideoRenderer(
|
||||
builder: Builder,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : MediaCodecVideoRenderer(builder) {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
private var stripHdr10PlusSei = false
|
||||
private var stripDvRpu = false
|
||||
|
||||
// Sanitize diagnostics — playback-thread only, cumulative for the renderer's lifetime.
|
||||
private var sanitizedSampleCount = 0L
|
||||
private var totalSanitizeTimeUs = 0L
|
||||
private var maxSanitizeTimeUs = 0L
|
||||
private var totalStrippedNals = 0L
|
||||
private var totalStrippedBytes = 0L
|
||||
|
||||
override fun onCodecInitialized(
|
||||
name: String,
|
||||
configuration: MediaCodecAdapter.Configuration,
|
||||
initializedTimestampMs: Long,
|
||||
initializationDurationMs: Long
|
||||
) {
|
||||
super.onCodecInitialized(name, configuration, initializedTimestampMs, initializationDurationMs)
|
||||
val codecs = configuration.format.codecs?.lowercase() ?: ""
|
||||
val dvHevcFormat = configuration.format.sampleMimeType == MimeTypes.VIDEO_DOLBY_VISION &&
|
||||
(codecs.startsWith("dvhe.") || codecs.startsWith("dvh1."))
|
||||
val codecMimeType = configuration.codecInfo.codecMimeType
|
||||
val newStripHdr10PlusSei = dvHevcFormat && codecMimeType == MimeTypes.VIDEO_DOLBY_VISION
|
||||
val newStripDvRpu = dvHevcFormat &&
|
||||
codecMimeType == MimeTypes.VIDEO_H265 &&
|
||||
isBlCompatibleDvProfile(codecs)
|
||||
if (newStripHdr10PlusSei != stripHdr10PlusSei || newStripDvRpu != stripDvRpu) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"video",
|
||||
"DV bitstream sanitizing: stripHdr10PlusSei=$newStripHdr10PlusSei, " +
|
||||
"stripDvRpu=$newStripDvRpu (codec=$name, codecs=${configuration.format.codecs})"
|
||||
)
|
||||
}
|
||||
stripHdr10PlusSei = newStripHdr10PlusSei
|
||||
stripDvRpu = newStripDvRpu
|
||||
}
|
||||
|
||||
override fun onQueueInputBuffer(buffer: DecoderInputBuffer) {
|
||||
if (stripHdr10PlusSei || stripDvRpu) {
|
||||
val data = buffer.data
|
||||
if (data != null && data.hasRemaining() && !buffer.isEncrypted) {
|
||||
val sizeBefore = data.remaining()
|
||||
val startNs = System.nanoTime()
|
||||
val stripped = sanitizer.sanitize(data, stripHdr10PlusSei, stripDvRpu)
|
||||
val elapsedUs = (System.nanoTime() - startNs) / 1_000
|
||||
sanitizedSampleCount++
|
||||
totalSanitizeTimeUs += elapsedUs
|
||||
if (elapsedUs > maxSanitizeTimeUs) maxSanitizeTimeUs = elapsedUs
|
||||
totalStrippedNals += stripped
|
||||
totalStrippedBytes += sizeBefore - data.remaining()
|
||||
if (sanitizedSampleCount <= 3 || sanitizedSampleCount % 500 == 0L) {
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"dv-sanitize",
|
||||
"Sample #$sanitizedSampleCount: ${sizeBefore}B -> ${data.remaining()}B, " +
|
||||
"stripped=$stripped, took=${elapsedUs}us " +
|
||||
"(avg=${totalSanitizeTimeUs / sanitizedSampleCount}us, max=${maxSanitizeTimeUs}us, " +
|
||||
"totalNals=$totalStrippedNals, totalBytes=${totalStrippedBytes}B)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
super.onQueueInputBuffer(buffer)
|
||||
}
|
||||
|
||||
private fun isBlCompatibleDvProfile(codecs: String): Boolean = codecs.startsWith("dvhe.07") ||
|
||||
codecs.startsWith("dvh1.07") ||
|
||||
codecs.startsWith("dvhe.08") ||
|
||||
codecs.startsWith("dvh1.08")
|
||||
}
|
||||
|
||||
// --- AudioOutput wrapping: shares raw position with PositionFixAudioSink ---
|
||||
@@ -232,117 +426,147 @@ internal class SubtitleDelayRenderer(
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
private class RawPositionOutputProvider(
|
||||
private val delegate: AudioOutputProvider,
|
||||
private val rawPositionUs: AtomicLong
|
||||
private val delegate: AudioOutputProvider,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : AudioOutputProvider {
|
||||
|
||||
private var cachedOutput: RawPositionAudioOutput? = null
|
||||
private var cachedConfig: AudioOutputProvider.OutputConfig? = null
|
||||
private var cachedOutput: RawPositionAudioOutput? = null
|
||||
private var cachedConfig: AudioOutputProvider.OutputConfig? = null
|
||||
|
||||
override fun getFormatSupport(config: AudioOutputProvider.FormatConfig) =
|
||||
delegate.getFormatSupport(config)
|
||||
override fun getFormatSupport(config: AudioOutputProvider.FormatConfig) = delegate.getFormatSupport(config)
|
||||
|
||||
override fun getOutputConfig(config: AudioOutputProvider.FormatConfig) =
|
||||
delegate.getOutputConfig(config)
|
||||
override fun getOutputConfig(config: AudioOutputProvider.FormatConfig) = delegate.getOutputConfig(config)
|
||||
|
||||
override fun getAudioOutput(config: AudioOutputProvider.OutputConfig): AudioOutput {
|
||||
val cached = cachedOutput
|
||||
if (cached != null && cachedConfig == config) {
|
||||
cachedOutput = null
|
||||
return cached
|
||||
}
|
||||
cached?.forceRelease()
|
||||
cachedOutput = null
|
||||
|
||||
val realOutput = delegate.getAudioOutput(config)
|
||||
cachedConfig = config
|
||||
return RawPositionAudioOutput(realOutput, rawPositionUs, this)
|
||||
override fun getAudioOutput(config: AudioOutputProvider.OutputConfig): AudioOutput {
|
||||
val cached = cachedOutput
|
||||
if (cached != null && cachedConfig == config) {
|
||||
cachedOutput = null
|
||||
return cached
|
||||
}
|
||||
cached?.forceRelease()
|
||||
cachedOutput = null
|
||||
|
||||
fun returnToCache(output: RawPositionAudioOutput) {
|
||||
val existing = cachedOutput
|
||||
if (existing != null && existing !== output) {
|
||||
existing.forceRelease()
|
||||
}
|
||||
cachedOutput = output
|
||||
val realOutput = delegate.getAudioOutput(config)
|
||||
cachedConfig = config
|
||||
return RawPositionAudioOutput(realOutput, rawPositionUs, this, log)
|
||||
}
|
||||
|
||||
fun returnToCache(output: RawPositionAudioOutput) {
|
||||
val existing = cachedOutput
|
||||
if (existing != null && existing !== output) {
|
||||
existing.forceRelease()
|
||||
}
|
||||
cachedOutput = output
|
||||
}
|
||||
|
||||
override fun addListener(listener: AudioOutputProvider.Listener) =
|
||||
delegate.addListener(listener)
|
||||
override fun addListener(listener: AudioOutputProvider.Listener) = delegate.addListener(listener)
|
||||
|
||||
override fun removeListener(listener: AudioOutputProvider.Listener) =
|
||||
delegate.removeListener(listener)
|
||||
override fun removeListener(listener: AudioOutputProvider.Listener) = delegate.removeListener(listener)
|
||||
|
||||
override fun setClock(clock: Clock) = delegate.setClock(clock)
|
||||
override fun setClock(clock: Clock) = delegate.setClock(clock)
|
||||
|
||||
override fun release() {
|
||||
cachedOutput?.forceRelease()
|
||||
cachedOutput = null
|
||||
cachedConfig = null
|
||||
delegate.release()
|
||||
}
|
||||
override fun release() {
|
||||
cachedOutput?.forceRelease()
|
||||
cachedOutput = null
|
||||
cachedConfig = null
|
||||
delegate.release()
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
private class RawPositionAudioOutput(
|
||||
private val delegate: AudioOutput,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val provider: RawPositionOutputProvider
|
||||
private val delegate: AudioOutput,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val provider: RawPositionOutputProvider,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : AudioOutput {
|
||||
|
||||
override fun getPositionUs(): Long {
|
||||
val pos = delegate.getPositionUs()
|
||||
rawPositionUs.set(pos)
|
||||
return pos
|
||||
private var loggedFirstWrite = false
|
||||
private var writeCount = 0L
|
||||
private var writtenBytes = 0L
|
||||
private var failed = false
|
||||
|
||||
override fun getPositionUs(): Long {
|
||||
val pos = delegate.getPositionUs()
|
||||
rawPositionUs.set(pos)
|
||||
return pos
|
||||
}
|
||||
|
||||
override fun play() = delegate.play()
|
||||
override fun pause() = delegate.pause()
|
||||
|
||||
@Throws(AudioOutput.WriteException::class)
|
||||
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long): Boolean {
|
||||
val before = buffer.position()
|
||||
val handled = try {
|
||||
delegate.write(buffer, size, presentationTimeUs)
|
||||
} catch (e: AudioOutput.WriteException) {
|
||||
failed = true
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
log?.invoke("warn", "audio-output", "Write failed; AudioTrack will not be reused: ${e.message}")
|
||||
throw e
|
||||
}
|
||||
|
||||
override fun play() = delegate.play()
|
||||
override fun pause() = delegate.pause()
|
||||
|
||||
@Throws(AudioOutput.WriteException::class)
|
||||
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long) =
|
||||
delegate.write(buffer, size, presentationTimeUs)
|
||||
|
||||
override fun flush() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
delegate.flush()
|
||||
val written = buffer.position() - before
|
||||
if (written > 0) {
|
||||
writeCount++
|
||||
writtenBytes += written.toLong()
|
||||
if (!loggedFirstWrite) {
|
||||
loggedFirstWrite = true
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"audio-output",
|
||||
"First write: wrote=${written}B, handled=$handled, pts=${presentationTimeUs}us, writes=$writeCount, total=${writtenBytes}B"
|
||||
)
|
||||
}
|
||||
}
|
||||
return handled
|
||||
}
|
||||
|
||||
override fun stop() = delegate.stop()
|
||||
override fun flush() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
loggedFirstWrite = false
|
||||
writeCount = 0
|
||||
writtenBytes = 0
|
||||
delegate.flush()
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
if (Build.VERSION.SDK_INT >= 25) {
|
||||
delegate.stop()
|
||||
delegate.flush()
|
||||
provider.returnToCache(this)
|
||||
} else {
|
||||
delegate.release()
|
||||
}
|
||||
override fun stop() = delegate.stop()
|
||||
|
||||
override fun release() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
if (failed) {
|
||||
delegate.release()
|
||||
return
|
||||
}
|
||||
|
||||
fun forceRelease() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
delegate.release()
|
||||
if (Build.VERSION.SDK_INT >= 25) {
|
||||
delegate.stop()
|
||||
delegate.flush()
|
||||
provider.returnToCache(this)
|
||||
} else {
|
||||
delegate.release()
|
||||
}
|
||||
}
|
||||
|
||||
override fun setVolume(volume: Float) = delegate.setVolume(volume)
|
||||
override fun isOffloadedPlayback() = delegate.isOffloadedPlayback()
|
||||
override fun getAudioSessionId() = delegate.getAudioSessionId()
|
||||
override fun getSampleRate() = delegate.getSampleRate()
|
||||
override fun getBufferSizeInFrames() = delegate.getBufferSizeInFrames()
|
||||
override fun getPlaybackParameters() = delegate.getPlaybackParameters()
|
||||
override fun isStalled() = delegate.isStalled()
|
||||
override fun addListener(listener: AudioOutput.Listener) = delegate.addListener(listener)
|
||||
override fun removeListener(listener: AudioOutput.Listener) = delegate.removeListener(listener)
|
||||
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) =
|
||||
delegate.setPlaybackParameters(playbackParameters)
|
||||
override fun setOffloadDelayPadding(delayInFrames: Int, paddingInFrames: Int) =
|
||||
delegate.setOffloadDelayPadding(delayInFrames, paddingInFrames)
|
||||
override fun setOffloadEndOfStream() = delegate.setOffloadEndOfStream()
|
||||
override fun setPlayerId(playerId: PlayerId) = delegate.setPlayerId(playerId)
|
||||
override fun attachAuxEffect(effectId: Int) = delegate.attachAuxEffect(effectId)
|
||||
override fun setAuxEffectSendLevel(level: Float) = delegate.setAuxEffectSendLevel(level)
|
||||
override fun setPreferredDevice(preferredDevice: AudioDeviceInfo?) =
|
||||
delegate.setPreferredDevice(preferredDevice)
|
||||
fun forceRelease() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
delegate.release()
|
||||
}
|
||||
|
||||
override fun setVolume(volume: Float) = delegate.setVolume(volume)
|
||||
override fun isOffloadedPlayback() = delegate.isOffloadedPlayback()
|
||||
override fun getAudioSessionId() = delegate.getAudioSessionId()
|
||||
override fun getSampleRate() = delegate.getSampleRate()
|
||||
override fun getBufferSizeInFrames() = delegate.getBufferSizeInFrames()
|
||||
override fun getPlaybackParameters() = delegate.getPlaybackParameters()
|
||||
override fun isStalled() = delegate.isStalled()
|
||||
override fun addListener(listener: AudioOutput.Listener) = delegate.addListener(listener)
|
||||
override fun removeListener(listener: AudioOutput.Listener) = delegate.removeListener(listener)
|
||||
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) = delegate.setPlaybackParameters(playbackParameters)
|
||||
override fun setOffloadDelayPadding(delayInFrames: Int, paddingInFrames: Int) = delegate.setOffloadDelayPadding(delayInFrames, paddingInFrames)
|
||||
override fun setOffloadEndOfStream() = delegate.setOffloadEndOfStream()
|
||||
override fun setPlayerId(playerId: PlayerId) = delegate.setPlayerId(playerId)
|
||||
override fun attachAuxEffect(effectId: Int) = delegate.attachAuxEffect(effectId)
|
||||
override fun setAuxEffectSendLevel(level: Float) = delegate.setAuxEffectSendLevel(level)
|
||||
override fun setPreferredDevice(preferredDevice: AudioDeviceInfo?) = delegate.setPreferredDevice(preferredDevice)
|
||||
}
|
||||
|
||||
@@ -16,108 +16,115 @@ import java.util.zip.Inflater
|
||||
* All buffers are reused across samples to minimize GC pressure on the hot path.
|
||||
*/
|
||||
class ZlibInflatingTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val delegate: TrackOutput
|
||||
) : TrackOutput {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ZlibTrackOutput"
|
||||
private const val INITIAL_BUFFER_SIZE = 256 * 1024
|
||||
private const val INFLATE_CHUNK = 64 * 1024
|
||||
companion object {
|
||||
private const val TAG = "ZlibTrackOutput"
|
||||
private const val INITIAL_BUFFER_SIZE = 256 * 1024
|
||||
private const val INFLATE_CHUNK = 64 * 1024
|
||||
}
|
||||
|
||||
var active = false
|
||||
|
||||
private val inflater = Inflater()
|
||||
|
||||
// Reusable buffers — grown as needed, never shrunk
|
||||
private var compressedBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var compressedLen = 0
|
||||
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var readBuf = ByteArray(INFLATE_CHUNK)
|
||||
private val outputParsable = ParsableByteArray()
|
||||
private var buffering = false
|
||||
|
||||
override fun format(format: Format) = delegate.format(format)
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (!active) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
|
||||
buffering = true
|
||||
if (readBuf.size < length) readBuf = ByteArray(length)
|
||||
val bytesRead = input.read(readBuf, 0, length)
|
||||
if (bytesRead > 0) appendCompressed(readBuf, 0, bytesRead)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (!active) {
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
return
|
||||
}
|
||||
|
||||
var active = false
|
||||
buffering = true
|
||||
ensureCompressedCapacity(compressedLen + length)
|
||||
data.readBytes(compressedBuf, compressedLen, length)
|
||||
compressedLen += length
|
||||
}
|
||||
|
||||
private val inflater = Inflater()
|
||||
|
||||
// Reusable buffers — grown as needed, never shrunk
|
||||
private var compressedBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var compressedLen = 0
|
||||
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var readBuf = ByteArray(INFLATE_CHUNK)
|
||||
private val outputParsable = ParsableByteArray()
|
||||
private var buffering = false
|
||||
|
||||
override fun format(format: Format) = delegate.format(format)
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int
|
||||
): Int {
|
||||
if (!active) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
|
||||
buffering = true
|
||||
if (readBuf.size < length) readBuf = ByteArray(length)
|
||||
val bytesRead = input.read(readBuf, 0, length)
|
||||
if (bytesRead > 0) appendCompressed(readBuf, 0, bytesRead)
|
||||
return bytesRead
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (!active || !buffering) {
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
return
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (!active) {
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
return
|
||||
}
|
||||
buffering = false
|
||||
val srcLen = compressedLen
|
||||
compressedLen = 0
|
||||
|
||||
buffering = true
|
||||
ensureCompressedCapacity(compressedLen + length)
|
||||
data.readBytes(compressedBuf, compressedLen, length)
|
||||
compressedLen += length
|
||||
val inflatedLen = try {
|
||||
inflater.reset()
|
||||
inflater.setInput(compressedBuf, 0, srcLen)
|
||||
var written = 0
|
||||
while (!inflater.finished()) {
|
||||
if (written == inflateBuf.size) growInflateBuf()
|
||||
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
|
||||
if (count == 0 && !inflater.finished()) break
|
||||
written += count
|
||||
}
|
||||
written
|
||||
} catch (e: DataFormatException) {
|
||||
Log.e(TAG, "Zlib inflate failed (${srcLen}B), passing raw", e)
|
||||
// Fall back to raw compressed data
|
||||
ensureInflateCapacity(srcLen)
|
||||
System.arraycopy(compressedBuf, 0, inflateBuf, 0, srcLen)
|
||||
srcLen
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (!active || !buffering) {
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
return
|
||||
}
|
||||
outputParsable.reset(inflateBuf, inflatedLen)
|
||||
delegate.sampleData(outputParsable, inflatedLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
delegate.sampleMetadata(timeUs, flags, inflatedLen, 0, cryptoData)
|
||||
}
|
||||
|
||||
buffering = false
|
||||
val srcLen = compressedLen
|
||||
compressedLen = 0
|
||||
private fun appendCompressed(src: ByteArray, offset: Int, length: Int) {
|
||||
ensureCompressedCapacity(compressedLen + length)
|
||||
System.arraycopy(src, offset, compressedBuf, compressedLen, length)
|
||||
compressedLen += length
|
||||
}
|
||||
|
||||
val inflatedLen = try {
|
||||
inflater.reset()
|
||||
inflater.setInput(compressedBuf, 0, srcLen)
|
||||
var written = 0
|
||||
while (!inflater.finished()) {
|
||||
if (written == inflateBuf.size) growInflateBuf()
|
||||
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
|
||||
if (count == 0 && !inflater.finished()) break
|
||||
written += count
|
||||
}
|
||||
written
|
||||
} catch (e: DataFormatException) {
|
||||
Log.e(TAG, "Zlib inflate failed (${srcLen}B), passing raw", e)
|
||||
// Fall back to raw compressed data
|
||||
ensureInflateCapacity(srcLen)
|
||||
System.arraycopy(compressedBuf, 0, inflateBuf, 0, srcLen)
|
||||
srcLen
|
||||
}
|
||||
|
||||
outputParsable.reset(inflateBuf, inflatedLen)
|
||||
delegate.sampleData(outputParsable, inflatedLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
delegate.sampleMetadata(timeUs, flags, inflatedLen, 0, cryptoData)
|
||||
private fun ensureCompressedCapacity(needed: Int) {
|
||||
if (compressedBuf.size < needed) {
|
||||
compressedBuf = compressedBuf.copyOf(maxOf(needed, compressedBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendCompressed(src: ByteArray, offset: Int, length: Int) {
|
||||
ensureCompressedCapacity(compressedLen + length)
|
||||
System.arraycopy(src, offset, compressedBuf, compressedLen, length)
|
||||
compressedLen += length
|
||||
private fun ensureInflateCapacity(needed: Int) {
|
||||
if (inflateBuf.size < needed) {
|
||||
inflateBuf = ByteArray(maxOf(needed, inflateBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureCompressedCapacity(needed: Int) {
|
||||
if (compressedBuf.size < needed) {
|
||||
compressedBuf = compressedBuf.copyOf(maxOf(needed, compressedBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureInflateCapacity(needed: Int) {
|
||||
if (inflateBuf.size < needed) {
|
||||
inflateBuf = ByteArray(maxOf(needed, inflateBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun growInflateBuf() {
|
||||
inflateBuf = inflateBuf.copyOf(inflateBuf.size * 2)
|
||||
}
|
||||
private fun growInflateBuf() {
|
||||
inflateBuf = inflateBuf.copyOf(inflateBuf.size * 2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@ import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
import io.github.peerless2012.ass.media.AssHandler
|
||||
import io.github.peerless2012.ass.media.extractor.AssMatroskaExtractor
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
|
||||
/**
|
||||
* Extends AssMatroskaExtractor to add support for MKV ContentCompAlgo 0 (zlib).
|
||||
@@ -20,97 +20,97 @@ import androidx.media3.extractor.text.SubtitleParser
|
||||
* - Skips ContentCompSettings for zlib tracks (not applicable)
|
||||
*/
|
||||
class ZlibMatroskaExtractor(
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
assHandler: AssHandler,
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
assHandler: AssHandler
|
||||
) : AssMatroskaExtractor(subtitleParserFactory, assHandler) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ZlibMkvExtractor"
|
||||
companion object {
|
||||
private const val TAG = "ZlibMkvExtractor"
|
||||
|
||||
// Matroska EBML element IDs
|
||||
private const val ID_SEGMENT = 0x18538067
|
||||
private const val ID_TRACK_ENTRY = 0xAE
|
||||
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
|
||||
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
|
||||
// Matroska EBML element IDs
|
||||
private const val ID_SEGMENT = 0x18538067
|
||||
private const val ID_TRACK_ENTRY = 0xAE
|
||||
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
|
||||
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
|
||||
|
||||
private val extractorOutputField by lazy {
|
||||
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
private val extractorOutputField by lazy {
|
||||
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var zlibOutput: ZlibExtractorOutputWrapper? = null
|
||||
private var currentTrackUsesZlib = false
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
|
||||
// After super installs AssSubtitleExtractorOutput, wrap it with our zlib layer
|
||||
if (id == ID_SEGMENT && zlibOutput == null) {
|
||||
val currentOutput = extractorOutputField.get(this) as ExtractorOutput
|
||||
val wrapper = ZlibExtractorOutputWrapper(currentOutput)
|
||||
zlibOutput = wrapper
|
||||
extractorOutputField.set(this, wrapper)
|
||||
Log.d(TAG, "Installed zlib ExtractorOutput wrapper")
|
||||
}
|
||||
}
|
||||
|
||||
override fun integerElement(id: Int, value: Long) {
|
||||
if (id == ID_CONTENT_COMPRESSION_ALGORITHM && value == 0L) {
|
||||
currentTrackUsesZlib = true
|
||||
Log.i(TAG, "Track uses ContentCompAlgo 0 (zlib), will inflate samples")
|
||||
// Tell parent it's header stripping (algo 3) to avoid ParserException
|
||||
super.integerElement(id, 3)
|
||||
return
|
||||
}
|
||||
super.integerElement(id, value)
|
||||
}
|
||||
|
||||
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
|
||||
if (id == ID_CONTENT_COMPRESSION_SETTINGS && currentTrackUsesZlib) {
|
||||
// Skip ContentCompSettings for zlib tracks — parent would store these as
|
||||
// sampleStrippedBytes and prepend them to every sample, corrupting output.
|
||||
input.skipFully(contentSize)
|
||||
return
|
||||
}
|
||||
super.binaryElement(id, contentSize, input)
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
val wasZlib = currentTrackUsesZlib
|
||||
super.endMasterElement(id)
|
||||
|
||||
if (id == ID_TRACK_ENTRY && wasZlib) {
|
||||
zlibOutput?.activateLast()
|
||||
currentTrackUsesZlib = false
|
||||
Log.i(TAG, "Activated zlib inflation for track")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
|
||||
* Tracks are created inactive; activateLast() enables inflation for the most recently
|
||||
* created track (called when we know a track uses zlib compression).
|
||||
*/
|
||||
private class ZlibExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
private var lastCreatedWrapper: ZlibInflatingTrackOutput? = null
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
val wrapper = ZlibInflatingTrackOutput(original)
|
||||
lastCreatedWrapper = wrapper
|
||||
return wrapper
|
||||
}
|
||||
|
||||
private var zlibOutput: ZlibExtractorOutputWrapper? = null
|
||||
private var currentTrackUsesZlib = false
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
|
||||
// After super installs AssSubtitleExtractorOutput, wrap it with our zlib layer
|
||||
if (id == ID_SEGMENT && zlibOutput == null) {
|
||||
val currentOutput = extractorOutputField.get(this) as ExtractorOutput
|
||||
val wrapper = ZlibExtractorOutputWrapper(currentOutput)
|
||||
zlibOutput = wrapper
|
||||
extractorOutputField.set(this, wrapper)
|
||||
Log.d(TAG, "Installed zlib ExtractorOutput wrapper")
|
||||
}
|
||||
fun activateLast() {
|
||||
lastCreatedWrapper?.active = true
|
||||
}
|
||||
|
||||
override fun integerElement(id: Int, value: Long) {
|
||||
if (id == ID_CONTENT_COMPRESSION_ALGORITHM && value == 0L) {
|
||||
currentTrackUsesZlib = true
|
||||
Log.i(TAG, "Track uses ContentCompAlgo 0 (zlib), will inflate samples")
|
||||
// Tell parent it's header stripping (algo 3) to avoid ParserException
|
||||
super.integerElement(id, 3)
|
||||
return
|
||||
}
|
||||
super.integerElement(id, value)
|
||||
}
|
||||
|
||||
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
|
||||
if (id == ID_CONTENT_COMPRESSION_SETTINGS && currentTrackUsesZlib) {
|
||||
// Skip ContentCompSettings for zlib tracks — parent would store these as
|
||||
// sampleStrippedBytes and prepend them to every sample, corrupting output.
|
||||
input.skipFully(contentSize)
|
||||
return
|
||||
}
|
||||
super.binaryElement(id, contentSize, input)
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
val wasZlib = currentTrackUsesZlib
|
||||
super.endMasterElement(id)
|
||||
|
||||
if (id == ID_TRACK_ENTRY && wasZlib) {
|
||||
zlibOutput?.activateLast()
|
||||
currentTrackUsesZlib = false
|
||||
Log.i(TAG, "Activated zlib inflation for track")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
|
||||
* Tracks are created inactive; activateLast() enables inflation for the most recently
|
||||
* created track (called when we know a track uses zlib compression).
|
||||
*/
|
||||
private class ZlibExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput,
|
||||
) : ExtractorOutput {
|
||||
|
||||
private var lastCreatedWrapper: ZlibInflatingTrackOutput? = null
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
val wrapper = ZlibInflatingTrackOutput(original)
|
||||
lastCreatedWrapper = wrapper
|
||||
return wrapper
|
||||
}
|
||||
|
||||
fun activateLast() {
|
||||
lastCreatedWrapper?.active = true
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,365 +10,376 @@ import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
|
||||
EventChannel.StreamHandler, ActivityAware, com.edde746.plezy.shared.PlayerDelegate {
|
||||
class MpvPlayerPlugin :
|
||||
FlutterPlugin,
|
||||
MethodChannel.MethodCallHandler,
|
||||
EventChannel.StreamHandler,
|
||||
ActivityAware,
|
||||
com.edde746.plezy.shared.PlayerDelegate {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/mpv_player"
|
||||
private const val EVENT_CHANNEL = "com.plezy/mpv_player/events"
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/mpv_player"
|
||||
private const val EVENT_CHANNEL = "com.plezy/mpv_player/events"
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
private var playerCore: MpvPlayerCore? = null
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
private var sessionGeneration = 0
|
||||
|
||||
// Pending `MethodChannel.Result`s for an init that is currently in flight.
|
||||
// Concurrent `invoke('initialize')` calls share the same outcome instead
|
||||
// of each tearing down the in-flight core and starting their own — which
|
||||
// was the root cause of #930.
|
||||
private val pendingInitResults = mutableListOf<MethodChannel.Result>()
|
||||
|
||||
@Volatile private var isInitializing = false
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
|
||||
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
|
||||
eventChannel.setStreamHandler(this)
|
||||
|
||||
Log.d(TAG, "Attached to engine")
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
eventChannel.setStreamHandler(null)
|
||||
Log.d(TAG, "Detached from engine")
|
||||
}
|
||||
|
||||
// ActivityAware
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(TAG, "Attached to activity")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {
|
||||
++sessionGeneration
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
// Any in-flight init callback would never fire (its scope is cancelled
|
||||
// by dispose), so close out queued callers explicitly.
|
||||
completePendingInits(success = false)
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(TAG, "Reattached to activity for config changes")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity for config changes")
|
||||
}
|
||||
|
||||
// EventChannel.StreamHandler
|
||||
|
||||
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
|
||||
eventSink = events
|
||||
Log.d(TAG, "Event stream connected")
|
||||
}
|
||||
|
||||
override fun onCancel(arguments: Any?) {
|
||||
eventSink = null
|
||||
Log.d(TAG, "Event stream disconnected")
|
||||
}
|
||||
|
||||
// MethodChannel.MethodCallHandler
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"initialize" -> handleInitialize(result)
|
||||
"dispose" -> handleDispose(result)
|
||||
"setProperty" -> handleSetProperty(call, result)
|
||||
"getProperty" -> handleGetProperty(call, result)
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"command" -> handleCommand(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
"updateFrame" -> handleUpdateFrame(result)
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"openContentFd" -> handleOpenContentFd(call, result)
|
||||
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
|
||||
"setLogLevel" -> result.success(null)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleInitialize(result: MethodChannel.Result) {
|
||||
val currentActivity = activity
|
||||
if (currentActivity == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
return
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
private var playerCore: MpvPlayerCore? = null
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
private var sessionGeneration = 0
|
||||
|
||||
// Pending `MethodChannel.Result`s for an init that is currently in flight.
|
||||
// Concurrent `invoke('initialize')` calls share the same outcome instead
|
||||
// of each tearing down the in-flight core and starting their own — which
|
||||
// was the root cause of #930.
|
||||
private val pendingInitResults = mutableListOf<MethodChannel.Result>()
|
||||
@Volatile private var isInitializing = false
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
|
||||
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
|
||||
eventChannel.setStreamHandler(this)
|
||||
|
||||
Log.d(TAG, "Attached to engine")
|
||||
if (playerCore?.isInitialized == true) {
|
||||
Log.d(TAG, "Already initialized")
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
eventChannel.setStreamHandler(null)
|
||||
Log.d(TAG, "Detached from engine")
|
||||
// Coalesce concurrent inits: the second caller waits for the first
|
||||
// call's outcome instead of disposing the in-flight core. The Dart
|
||||
// side memoizes too, but this is defense in depth for any direct
|
||||
// `invoke('initialize')` that bypasses _ensureInitialized.
|
||||
synchronized(pendingInitResults) {
|
||||
pendingInitResults += result
|
||||
if (isInitializing) {
|
||||
Log.d(TAG, "Init already in flight, queuing caller")
|
||||
return
|
||||
}
|
||||
isInitializing = true
|
||||
}
|
||||
|
||||
// ActivityAware
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(TAG, "Attached to activity")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {
|
||||
++sessionGeneration
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
// Any in-flight init callback would never fire (its scope is cancelled
|
||||
// by dispose), so close out queued callers explicitly.
|
||||
completePendingInits(success = false)
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(TAG, "Reattached to activity for config changes")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity for config changes")
|
||||
}
|
||||
|
||||
// EventChannel.StreamHandler
|
||||
|
||||
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
|
||||
eventSink = events
|
||||
Log.d(TAG, "Event stream connected")
|
||||
}
|
||||
|
||||
override fun onCancel(arguments: Any?) {
|
||||
eventSink = null
|
||||
Log.d(TAG, "Event stream disconnected")
|
||||
}
|
||||
|
||||
// MethodChannel.MethodCallHandler
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"initialize" -> handleInitialize(result)
|
||||
"dispose" -> handleDispose(result)
|
||||
"setProperty" -> handleSetProperty(call, result)
|
||||
"getProperty" -> handleGetProperty(call, result)
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"command" -> handleCommand(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
"updateFrame" -> handleUpdateFrame(result)
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"openContentFd" -> handleOpenContentFd(call, result)
|
||||
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
|
||||
"setLogLevel" -> result.success(null)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleInitialize(result: MethodChannel.Result) {
|
||||
val currentActivity = activity
|
||||
if (currentActivity == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
return
|
||||
currentActivity.runOnUiThread {
|
||||
val gen: Int
|
||||
val core: MpvPlayerCore
|
||||
try {
|
||||
// Caller invariant: dispose() was already called explicitly,
|
||||
// OR `playerCore?.isInitialized == true` and we early-exited
|
||||
// above. We never tear down a core that's mid-initialization.
|
||||
if (playerCore != null && playerCore?.isInitialized != true) {
|
||||
Log.w(TAG, "Discarding stale uninitialized core before re-init")
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
}
|
||||
|
||||
if (playerCore?.isInitialized == true) {
|
||||
Log.d(TAG, "Already initialized")
|
||||
result.success(true)
|
||||
return
|
||||
gen = ++sessionGeneration
|
||||
core = MpvPlayerCore(currentActivity).apply {
|
||||
delegate = this@MpvPlayerPlugin
|
||||
}
|
||||
playerCore = core
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to initialize: ${e.message}", e)
|
||||
completePendingInits(success = false, errorMessage = e.message)
|
||||
return@runOnUiThread
|
||||
}
|
||||
|
||||
// Coalesce concurrent inits: the second caller waits for the first
|
||||
// call's outcome instead of disposing the in-flight core. The Dart
|
||||
// side memoizes too, but this is defense in depth for any direct
|
||||
// `invoke('initialize')` that bypasses _ensureInitialized.
|
||||
synchronized(pendingInitResults) {
|
||||
pendingInitResults += result
|
||||
if (isInitializing) {
|
||||
Log.d(TAG, "Init already in flight, queuing caller")
|
||||
return
|
||||
}
|
||||
isInitializing = true
|
||||
}
|
||||
|
||||
currentActivity.runOnUiThread {
|
||||
val gen: Int
|
||||
val core: MpvPlayerCore
|
||||
try {
|
||||
// Caller invariant: dispose() was already called explicitly,
|
||||
// OR `playerCore?.isInitialized == true` and we early-exited
|
||||
// above. We never tear down a core that's mid-initialization.
|
||||
if (playerCore != null && playerCore?.isInitialized != true) {
|
||||
Log.w(TAG, "Discarding stale uninitialized core before re-init")
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
}
|
||||
|
||||
gen = ++sessionGeneration
|
||||
core = MpvPlayerCore(currentActivity).apply {
|
||||
delegate = this@MpvPlayerPlugin
|
||||
}
|
||||
playerCore = core
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to initialize: ${e.message}", e)
|
||||
completePendingInits(success = false, errorMessage = e.message)
|
||||
return@runOnUiThread
|
||||
}
|
||||
|
||||
core.initialize { success ->
|
||||
val stale = gen != sessionGeneration || playerCore !== core
|
||||
if (stale) {
|
||||
Log.d(TAG, "Stale init callback (gen=$gen, current=$sessionGeneration)")
|
||||
} else {
|
||||
// Start hidden - now safe because setVisible operates on the container,
|
||||
// not the SurfaceView directly (matching ExoPlayer's approach)
|
||||
core.setVisible(false)
|
||||
Log.d(TAG, "Initialized: $success")
|
||||
}
|
||||
completePendingInits(success = !stale && success)
|
||||
}
|
||||
core.initialize { success ->
|
||||
val stale = gen != sessionGeneration || playerCore !== core
|
||||
if (stale) {
|
||||
Log.d(TAG, "Stale init callback (gen=$gen, current=$sessionGeneration)")
|
||||
} else {
|
||||
// Start hidden - now safe because setVisible operates on the container,
|
||||
// not the SurfaceView directly (matching ExoPlayer's approach)
|
||||
core.setVisible(false)
|
||||
Log.d(TAG, "Initialized: $success")
|
||||
}
|
||||
completePendingInits(success = !stale && success)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun completePendingInits(success: Boolean, errorMessage: String? = null) {
|
||||
val pending = synchronized(pendingInitResults) {
|
||||
isInitializing = false
|
||||
val copy = pendingInitResults.toList()
|
||||
pendingInitResults.clear()
|
||||
copy
|
||||
}
|
||||
for (r in pending) {
|
||||
if (errorMessage != null) {
|
||||
r.error("INIT_FAILED", errorMessage, null)
|
||||
} else {
|
||||
r.success(success)
|
||||
}
|
||||
}
|
||||
private fun completePendingInits(success: Boolean, errorMessage: String? = null) {
|
||||
val pending = synchronized(pendingInitResults) {
|
||||
isInitializing = false
|
||||
val copy = pendingInitResults.toList()
|
||||
pendingInitResults.clear()
|
||||
copy
|
||||
}
|
||||
|
||||
private fun handleDispose(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
val core = playerCore
|
||||
++sessionGeneration
|
||||
playerCore = null
|
||||
|
||||
// Any in-flight init callback is cancelled with the scope, so
|
||||
// close out queued callers here instead of leaking them.
|
||||
completePendingInits(success = false)
|
||||
|
||||
core?.dispose {
|
||||
Log.d(TAG, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
} ?: result.success(null)
|
||||
for (r in pending) {
|
||||
if (errorMessage != null) {
|
||||
r.error("INIT_FAILED", errorMessage, null)
|
||||
} else {
|
||||
r.success(success)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val value = call.argument<String>("value")
|
||||
private fun handleDispose(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
val core = playerCore
|
||||
++sessionGeneration
|
||||
playerCore = null
|
||||
|
||||
if (name == null || value == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
|
||||
return
|
||||
}
|
||||
// Any in-flight init callback is cancelled with the scope, so
|
||||
// close out queued callers here instead of leaking them.
|
||||
completePendingInits(success = false)
|
||||
|
||||
playerCore?.setProperty(name, value)
|
||||
core?.dispose {
|
||||
Log.d(TAG, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val value = call.argument<String>("value")
|
||||
|
||||
if (name == null || value == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
|
||||
return
|
||||
}
|
||||
|
||||
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
playerCore?.setProperty(name, value)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
if (name == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name'", null)
|
||||
return
|
||||
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
|
||||
if (name == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val value = playerCore?.getProperty(name)
|
||||
result.success(value)
|
||||
}
|
||||
|
||||
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val format = call.argument<String>("format")
|
||||
val id = call.argument<Int>("id")
|
||||
|
||||
if (name == null || format == null || id == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name', 'format', or 'id'", null)
|
||||
return
|
||||
}
|
||||
|
||||
nameToId[name] = id
|
||||
playerCore?.observeProperty(name, format)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
|
||||
val args = call.argument<List<String>>("args")
|
||||
|
||||
if (args == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'args'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
core.command(args.toTypedArray()) {
|
||||
result.success(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
|
||||
val visible = call.argument<Boolean>("visible")
|
||||
|
||||
if (visible == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'visible'", null)
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.setVisible(visible)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleUpdateFrame(result: MethodChannel.Result) {
|
||||
playerCore?.updateFrame()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs) { switched ->
|
||||
result.success(switched)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
playerCore?.clearVideoFrameRate()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "requestAudioFocus")
|
||||
val granted = playerCore?.requestAudioFocus() ?: false
|
||||
result.success(granted)
|
||||
}
|
||||
|
||||
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "abandonAudioFocus")
|
||||
playerCore?.abandonAudioFocus()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleOpenContentFd(call: MethodCall, result: MethodChannel.Result) {
|
||||
val uriString = call.argument<String>("uri")
|
||||
if (uriString == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val contentResolver = activity?.contentResolver
|
||||
if (contentResolver == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
return
|
||||
}
|
||||
|
||||
// Open file descriptor off UI thread to prevent ANR on slow storage
|
||||
Thread {
|
||||
try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val pfd = contentResolver.openFileDescriptor(uri, "r")
|
||||
if (pfd == null) {
|
||||
activity?.runOnUiThread {
|
||||
result.error("OPEN_FAILED", "Failed to open file descriptor for $uriString", null)
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
|
||||
val value = playerCore?.getProperty(name)
|
||||
result.success(value)
|
||||
}
|
||||
val fd = pfd.detachFd()
|
||||
Log.d(TAG, "Opened content FD $fd for $uriString")
|
||||
activity?.runOnUiThread { result.success(fd) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
|
||||
activity?.runOnUiThread { result.error("OPEN_FAILED", e.message, null) }
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val format = call.argument<String>("format")
|
||||
val id = call.argument<Int>("id")
|
||||
// PlayerDelegate
|
||||
|
||||
if (name == null || format == null || id == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name', 'format', or 'id'", null)
|
||||
return
|
||||
}
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = nameToId[name] ?: return
|
||||
eventSink?.success(listOf(propId, value))
|
||||
}
|
||||
|
||||
nameToId[name] = id
|
||||
playerCore?.observeProperty(name, format)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
|
||||
val args = call.argument<List<String>>("args")
|
||||
|
||||
if (args == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'args'", null)
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.command(args.toTypedArray())
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
|
||||
val visible = call.argument<Boolean>("visible")
|
||||
|
||||
if (visible == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'visible'", null)
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.setVisible(visible)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleUpdateFrame(result: MethodChannel.Result) {
|
||||
playerCore?.updateFrame()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs) { switched ->
|
||||
result.success(switched)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
playerCore?.clearVideoFrameRate()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "requestAudioFocus")
|
||||
val granted = playerCore?.requestAudioFocus() ?: false
|
||||
result.success(granted)
|
||||
}
|
||||
|
||||
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "abandonAudioFocus")
|
||||
playerCore?.abandonAudioFocus()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleOpenContentFd(call: MethodCall, result: MethodChannel.Result) {
|
||||
val uriString = call.argument<String>("uri")
|
||||
if (uriString == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val contentResolver = activity?.contentResolver
|
||||
if (contentResolver == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
return
|
||||
}
|
||||
|
||||
// Open file descriptor off UI thread to prevent ANR on slow storage
|
||||
Thread {
|
||||
try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val pfd = contentResolver.openFileDescriptor(uri, "r")
|
||||
if (pfd == null) {
|
||||
activity?.runOnUiThread {
|
||||
result.error("OPEN_FAILED", "Failed to open file descriptor for $uriString", null)
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
|
||||
val fd = pfd.detachFd()
|
||||
Log.d(TAG, "Opened content FD $fd for $uriString")
|
||||
activity?.runOnUiThread { result.success(fd) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
|
||||
activity?.runOnUiThread { result.error("OPEN_FAILED", e.message, null) }
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
// PlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = nameToId[name] ?: return
|
||||
eventSink?.success(listOf(propId, value))
|
||||
}
|
||||
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
eventSink?.success(event)
|
||||
}
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
eventSink?.success(event)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,97 +9,97 @@ import android.os.Handler
|
||||
import android.util.Log
|
||||
|
||||
class AudioFocusManager(
|
||||
context: Context,
|
||||
private val handler: Handler,
|
||||
private val onPause: () -> Unit,
|
||||
private val onResume: () -> Unit,
|
||||
private val isPaused: () -> Boolean,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) }
|
||||
context: Context,
|
||||
private val handler: Handler,
|
||||
private val onPause: () -> Unit,
|
||||
private val onResume: () -> Unit,
|
||||
private val isPaused: () -> Boolean,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) }
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "AudioFocusManager"
|
||||
}
|
||||
companion object {
|
||||
private const val TAG = "AudioFocusManager"
|
||||
}
|
||||
|
||||
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private var audioFocusRequest: AudioFocusRequest? = null
|
||||
private var hasAudioFocus: Boolean = false
|
||||
var wasPlayingBeforeFocusLoss: Boolean = false
|
||||
private set
|
||||
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private var audioFocusRequest: AudioFocusRequest? = null
|
||||
private var hasAudioFocus: Boolean = false
|
||||
var wasPlayingBeforeFocusLoss: Boolean = false
|
||||
private set
|
||||
|
||||
private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
|
||||
when (focusChange) {
|
||||
AudioManager.AUDIOFOCUS_GAIN -> {
|
||||
log("Focus gained")
|
||||
hasAudioFocus = true
|
||||
if (wasPlayingBeforeFocusLoss) {
|
||||
onResume()
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
}
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS -> {
|
||||
log("Focus lost permanently")
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = !isPaused()
|
||||
onPause()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
||||
log("Focus lost transiently")
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = !isPaused()
|
||||
onPause()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
|
||||
log("Focus lost transiently (can duck)")
|
||||
}
|
||||
private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
|
||||
when (focusChange) {
|
||||
AudioManager.AUDIOFOCUS_GAIN -> {
|
||||
log("Focus gained")
|
||||
hasAudioFocus = true
|
||||
if (wasPlayingBeforeFocusLoss) {
|
||||
onResume()
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
}
|
||||
}
|
||||
|
||||
fun requestAudioFocus(): Boolean {
|
||||
Log.d(TAG, "Requesting audio focus")
|
||||
|
||||
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||
.build()
|
||||
)
|
||||
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
|
||||
.build()
|
||||
|
||||
audioFocusRequest = focusRequest
|
||||
audioManager.requestAudioFocus(focusRequest)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.requestAudioFocus(
|
||||
audioFocusChangeListener,
|
||||
AudioManager.STREAM_MUSIC,
|
||||
AudioManager.AUDIOFOCUS_GAIN
|
||||
)
|
||||
}
|
||||
|
||||
hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
|
||||
Log.d(TAG, "Audio focus request result: $result, granted: $hasAudioFocus")
|
||||
return hasAudioFocus
|
||||
}
|
||||
|
||||
fun abandonAudioFocus() {
|
||||
Log.d(TAG, "Abandoning audio focus")
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
|
||||
audioFocusRequest = null
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.abandonAudioFocus(audioFocusChangeListener)
|
||||
}
|
||||
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS -> {
|
||||
log("Focus lost permanently")
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
wasPlayingBeforeFocusLoss = !isPaused()
|
||||
onPause()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
||||
log("Focus lost transiently")
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = !isPaused()
|
||||
onPause()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
|
||||
log("Focus lost transiently (can duck)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun requestAudioFocus(): Boolean {
|
||||
Log.d(TAG, "Requesting audio focus")
|
||||
|
||||
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||
.build()
|
||||
)
|
||||
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
|
||||
.build()
|
||||
|
||||
audioFocusRequest = focusRequest
|
||||
audioManager.requestAudioFocus(focusRequest)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.requestAudioFocus(
|
||||
audioFocusChangeListener,
|
||||
AudioManager.STREAM_MUSIC,
|
||||
AudioManager.AUDIOFOCUS_GAIN
|
||||
)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
abandonAudioFocus()
|
||||
hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
|
||||
Log.d(TAG, "Audio focus request result: $result, granted: $hasAudioFocus")
|
||||
return hasAudioFocus
|
||||
}
|
||||
|
||||
fun abandonAudioFocus() {
|
||||
Log.d(TAG, "Abandoning audio focus")
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
|
||||
audioFocusRequest = null
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.abandonAudioFocus(audioFocusChangeListener)
|
||||
}
|
||||
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
}
|
||||
|
||||
fun release() {
|
||||
abandonAudioFocus()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.os.Build
|
||||
|
||||
object DeviceQuirks {
|
||||
val isEWaste: Boolean
|
||||
get() = isGooglePixelDevice || isGoogleTensorDevice
|
||||
|
||||
private val isGooglePixelDevice: Boolean
|
||||
get() = (
|
||||
Build.MANUFACTURER.equals("Google", ignoreCase = true) ||
|
||||
Build.BRAND.equals("google", ignoreCase = true)
|
||||
) &&
|
||||
Build.MODEL.contains("Pixel", ignoreCase = true)
|
||||
|
||||
private val isGoogleTensorDevice: Boolean
|
||||
get() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
|
||||
val soc = Build.SOC_MODEL
|
||||
return soc.startsWith("Tensor", ignoreCase = true) ||
|
||||
soc.startsWith("GS", ignoreCase = true)
|
||||
}
|
||||
}
|
||||
@@ -9,84 +9,84 @@ import android.view.ViewGroup
|
||||
|
||||
object FlutterOverlayHelper {
|
||||
|
||||
/**
|
||||
* Find the top-level container holding the Flutter render surface. Returns the
|
||||
* direct child of [contentView] that contains a FlutterSurfaceView/FlutterTextureView
|
||||
* at any depth — `bringChildToFront` only works for direct children, so this is the
|
||||
* node to pass to [configureFlutterZOrder].
|
||||
*
|
||||
* Searches any depth because an app may wrap Flutter (e.g. for key-event dispatch)
|
||||
* and push it below the direct-child level.
|
||||
*/
|
||||
fun findFlutterContainer(contentView: ViewGroup, excludeView: View? = null): ViewGroup? {
|
||||
for (i in contentView.childCount - 1 downTo 0) {
|
||||
val child = contentView.getChildAt(i)
|
||||
if (child === excludeView || child !is ViewGroup) continue
|
||||
if (findRenderSurface(child) != null) return child
|
||||
}
|
||||
return null
|
||||
/**
|
||||
* Find the top-level container holding the Flutter render surface. Returns the
|
||||
* direct child of [contentView] that contains a FlutterSurfaceView/FlutterTextureView
|
||||
* at any depth — `bringChildToFront` only works for direct children, so this is the
|
||||
* node to pass to [configureFlutterZOrder].
|
||||
*
|
||||
* Searches any depth because an app may wrap Flutter (e.g. for key-event dispatch)
|
||||
* and push it below the direct-child level.
|
||||
*/
|
||||
fun findFlutterContainer(contentView: ViewGroup, excludeView: View? = null): ViewGroup? {
|
||||
for (i in contentView.childCount - 1 downTo 0) {
|
||||
val child = contentView.getChildAt(i)
|
||||
if (child === excludeView || child !is ViewGroup) continue
|
||||
if (findRenderSurface(child) != null) return child
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findRenderSurface(root: ViewGroup): View? {
|
||||
for (i in 0 until root.childCount) {
|
||||
val child = root.getChildAt(i)
|
||||
if (child is SurfaceView || child is TextureView) return child
|
||||
if (child is ViewGroup) findRenderSurface(child)?.let { return it }
|
||||
}
|
||||
return null
|
||||
private fun findRenderSurface(root: ViewGroup): View? {
|
||||
for (i in 0 until root.childCount) {
|
||||
val child = root.getChildAt(i)
|
||||
if (child is SurfaceView || child is TextureView) return child
|
||||
if (child is ViewGroup) findRenderSurface(child)?.let { return it }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply [SurfaceView.setCompositionOrder] on API 36+; no-op on older APIs where
|
||||
* the legacy [SurfaceView.setZOrderOnTop]/[SurfaceView.setZOrderMediaOverlay]
|
||||
* bucket settings govern Z-order instead.
|
||||
*
|
||||
* The value maps directly to the SurfaceView's `mSubLayer`. Per AOSP semantics:
|
||||
* `mSubLayer >= 0` (non-negative `order`) is composited above the parent window
|
||||
* and skips the hole-punch in `draw()`; `mSubLayer < 0` (negative `order`) is
|
||||
* behind the parent window and the SurfaceView is made visible by punching a
|
||||
* transparent hole in the parent canvas. Valid range is `[-2, 2]`. Picking the
|
||||
* right sign matters: any view that draws on the parent canvas (e.g. Media3's
|
||||
* `CanvasSubtitleOutput` for SRT/VTT/SDH) is hidden by SurfaceViews with
|
||||
* non-negative orders that sit on top of the same area.
|
||||
*/
|
||||
fun applyCompositionOrder(view: SurfaceView, order: Int) {
|
||||
if (Build.VERSION.SDK_INT >= 36) view.compositionOrder = order
|
||||
}
|
||||
/**
|
||||
* Apply [SurfaceView.setCompositionOrder] on API 36+; no-op on older APIs where
|
||||
* the legacy [SurfaceView.setZOrderOnTop]/[SurfaceView.setZOrderMediaOverlay]
|
||||
* bucket settings govern Z-order instead.
|
||||
*
|
||||
* The value maps directly to the SurfaceView's `mSubLayer`. Per AOSP semantics:
|
||||
* `mSubLayer >= 0` (non-negative `order`) is composited above the parent window
|
||||
* and skips the hole-punch in `draw()`; `mSubLayer < 0` (negative `order`) is
|
||||
* behind the parent window and the SurfaceView is made visible by punching a
|
||||
* transparent hole in the parent canvas. Valid range is `[-2, 2]`. Picking the
|
||||
* right sign matters: any view that draws on the parent canvas (e.g. Media3's
|
||||
* `CanvasSubtitleOutput` for SRT/VTT/SDH) is hidden by SurfaceViews with
|
||||
* non-negative orders that sit on top of the same area.
|
||||
*/
|
||||
fun applyCompositionOrder(view: SurfaceView, order: Int) {
|
||||
if (Build.VERSION.SDK_INT >= 36) view.compositionOrder = order
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure z-ordering so the Flutter UI renders above the video/subtitle surfaces.
|
||||
*
|
||||
* On API 36+ the value is applied via [SurfaceView.setCompositionOrder] and maps
|
||||
* directly to `mSubLayer` (see [applyCompositionOrder] for the sign semantics).
|
||||
* On pre-36 SurfaceView builds the value is mapped to the legacy on-top bucket
|
||||
* when positive. On TextureView builds the value is unused (view hierarchy order
|
||||
* handles it).
|
||||
*
|
||||
* Pass a non-negative value (e.g. `1`) so Flutter renders above the parent canvas
|
||||
* and lets the legacy transparent-mode `setZOrderOnTop(true)` semantics carry over.
|
||||
*/
|
||||
fun configureFlutterZOrder(contentView: ViewGroup, container: ViewGroup, compositionOrder: Int) {
|
||||
contentView.bringChildToFront(container)
|
||||
when (val surface = findRenderSurface(container)) {
|
||||
is SurfaceView -> {
|
||||
if (Build.VERSION.SDK_INT >= 36) {
|
||||
// Clear legacy bucket hints so compositionOrder is authoritative.
|
||||
// Flutter's FlutterSurfaceView sets setZOrderOnTop(true) in its
|
||||
// transparent-mode constructor, which otherwise pins it to z=1.
|
||||
surface.setZOrderOnTop(false)
|
||||
surface.setZOrderMediaOverlay(false)
|
||||
surface.compositionOrder = compositionOrder
|
||||
} else {
|
||||
// Pre-36 has 3 coarse sublayer buckets. Put Flutter in the on-top
|
||||
// bucket so it renders above the video (default) and libass subtitle
|
||||
// (media overlay) SurfaceViews. NB: setZOrderMediaOverlay overwrites
|
||||
// mSubLayer internally, so don't call it here or it cancels setZOrderOnTop.
|
||||
surface.setZOrderOnTop(compositionOrder > 0)
|
||||
}
|
||||
surface.holder.setFormat(PixelFormat.TRANSLUCENT)
|
||||
}
|
||||
is TextureView -> surface.isOpaque = false
|
||||
/**
|
||||
* Configure z-ordering so the Flutter UI renders above the video/subtitle surfaces.
|
||||
*
|
||||
* On API 36+ the value is applied via [SurfaceView.setCompositionOrder] and maps
|
||||
* directly to `mSubLayer` (see [applyCompositionOrder] for the sign semantics).
|
||||
* On pre-36 SurfaceView builds the value is mapped to the legacy on-top bucket
|
||||
* when positive. On TextureView builds the value is unused (view hierarchy order
|
||||
* handles it).
|
||||
*
|
||||
* Pass a non-negative value (e.g. `1`) so Flutter renders above the parent canvas
|
||||
* and lets the legacy transparent-mode `setZOrderOnTop(true)` semantics carry over.
|
||||
*/
|
||||
fun configureFlutterZOrder(contentView: ViewGroup, container: ViewGroup, compositionOrder: Int) {
|
||||
contentView.bringChildToFront(container)
|
||||
when (val surface = findRenderSurface(container)) {
|
||||
is SurfaceView -> {
|
||||
if (Build.VERSION.SDK_INT >= 36) {
|
||||
// Clear legacy bucket hints so compositionOrder is authoritative.
|
||||
// Flutter's FlutterSurfaceView sets setZOrderOnTop(true) in its
|
||||
// transparent-mode constructor, which otherwise pins it to z=1.
|
||||
surface.setZOrderOnTop(false)
|
||||
surface.setZOrderMediaOverlay(false)
|
||||
surface.compositionOrder = compositionOrder
|
||||
} else {
|
||||
// Pre-36 has 3 coarse sublayer buckets. Put Flutter in the on-top
|
||||
// bucket so it renders above the video (default) and libass subtitle
|
||||
// (media overlay) SurfaceViews. NB: setZOrderMediaOverlay overwrites
|
||||
// mSubLayer internally, so don't call it here or it cancels setZOrderOnTop.
|
||||
surface.setZOrderOnTop(compositionOrder > 0)
|
||||
}
|
||||
surface.holder.setFormat(PixelFormat.TRANSLUCENT)
|
||||
}
|
||||
is TextureView -> surface.isOpaque = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,274 +6,264 @@ import android.hardware.display.DisplayManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import androidx.annotation.RequiresApi
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class FrameRateManager(
|
||||
private val activity: Activity,
|
||||
private val handler: Handler,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) }
|
||||
private val activity: Activity,
|
||||
private val handler: Handler,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) }
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "FrameRateManager"
|
||||
private const val SHORT_VIDEO_LENGTH_MS = 300000L // 5 minutes
|
||||
private const val DISPLAY_SETTLE_MS = 2000L
|
||||
private const val WATCHDOG_MARGIN_MS = 3000L
|
||||
companion object {
|
||||
private const val TAG = "FrameRateManager"
|
||||
private const val DISPLAY_SETTLE_MS = 2000L
|
||||
private const val WATCHDOG_MARGIN_MS = 3000L
|
||||
private const val RATE_TOLERANCE = 0.1f
|
||||
}
|
||||
|
||||
private data class RefreshRateMatch(
|
||||
val reason: String,
|
||||
val priority: Int,
|
||||
val error: Float
|
||||
)
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private data class DisplayModeCandidate(
|
||||
val mode: Display.Mode,
|
||||
val match: RefreshRateMatch
|
||||
)
|
||||
|
||||
private var currentVideoFps: Float = 0f
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private var pendingSettleRunnable: Runnable? = null
|
||||
private var watchdogRunnable: Runnable? = null
|
||||
private var pendingCompletion: ((switched: Boolean) -> Unit)? = null
|
||||
|
||||
private fun getDisplayManager(): DisplayManager = activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
|
||||
|
||||
// Request a display frame-rate switch. Invokes [onComplete] once, either:
|
||||
// - immediately with `switched=false` when no switch is needed (invalid fps,
|
||||
// no matching mode, or already matching); or
|
||||
// - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the caller's
|
||||
// [extraDelayMs], with `switched=true`; or
|
||||
// - via a watchdog if the real event never arrives, so the caller doesn't hang.
|
||||
//
|
||||
// The caller is responsible for pausing playback before calling and resuming
|
||||
// it after [onComplete] fires.
|
||||
fun setVideoFrameRate(
|
||||
fps: Float,
|
||||
videoDurationMs: Long,
|
||||
extraDelayMs: Long,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
currentVideoFps = fps
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
private var currentVideoFps: Float = 0f
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private var pendingSettleRunnable: Runnable? = null
|
||||
private var watchdogRunnable: Runnable? = null
|
||||
private var pendingCompletion: ((switched: Boolean) -> Unit)? = null
|
||||
log(
|
||||
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
|
||||
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
)
|
||||
|
||||
private fun getDisplayManager(): DisplayManager {
|
||||
return activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
setDisplayMode(fps, extraDelayMs, onComplete)
|
||||
} else {
|
||||
onComplete(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearVideoFrameRate() {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
currentVideoFps = 0f
|
||||
// Resolve any pending setVideoFrameRate future as "not switched" so
|
||||
// the Dart caller's await doesn't hang on player dispose.
|
||||
firePendingCompletion("clear", switched = false)
|
||||
// Restore default display mode on API M (preferredDisplayModeId persists)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = 0
|
||||
activity.window?.attributes = attrs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Release pending callbacks/listener without restoring the display mode.
|
||||
// Used by player-core dispose paths so a backend handoff (e.g. ExoPlayer→MPV
|
||||
// audio fallback) doesn't clobber the just-applied refresh-rate switch —
|
||||
// window-scoped preferredDisplayModeId persists across the SurfaceView swap,
|
||||
// letting MPV inherit the rate without a second HDMI renegotiation.
|
||||
fun releasePending() {
|
||||
Log.d(TAG, "releasePending")
|
||||
currentVideoFps = 0f
|
||||
firePendingCompletion("release", switched = false)
|
||||
}
|
||||
|
||||
private fun cancelPendingCallbacks() {
|
||||
pendingSettleRunnable?.let { handler.removeCallbacks(it) }
|
||||
watchdogRunnable?.let { handler.removeCallbacks(it) }
|
||||
pendingSettleRunnable = null
|
||||
watchdogRunnable = null
|
||||
}
|
||||
|
||||
private fun firePendingCompletion(reason: String, switched: Boolean) {
|
||||
cancelPendingCallbacks()
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
displayListener = null
|
||||
}
|
||||
val cb = pendingCompletion ?: return
|
||||
pendingCompletion = null
|
||||
log("complete reason=$reason, switched=$switched, currentMode=${currentModeDescription()}")
|
||||
cb(switched)
|
||||
}
|
||||
|
||||
private fun registerDisplayListener(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
// Resolve any previous pending op before starting a new one.
|
||||
firePendingCompletion("superseded", switched = false)
|
||||
pendingCompletion = onComplete
|
||||
|
||||
displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = Unit
|
||||
override fun onDisplayRemoved(displayId: Int) = Unit
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
// Unregister immediately so a chatty display (e.g. several
|
||||
// onDisplayChanged events during HDMI renegotiation) doesn't
|
||||
// queue multiple settle callbacks.
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
|
||||
val settle = Runnable { firePendingCompletion("display settled", switched = currentRateMatch(fps) != null) }
|
||||
pendingSettleRunnable = settle
|
||||
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
|
||||
}
|
||||
}
|
||||
getDisplayManager().registerDisplayListener(displayListener, handler)
|
||||
|
||||
// Watchdog: if the TV never signals a display change (silently ignoring
|
||||
// the mode request), still complete after a bounded wait so the caller
|
||||
// doesn't hang.
|
||||
val watchdog = Runnable { firePendingCompletion("watchdog", switched = currentRateMatch(fps) != null) }
|
||||
watchdogRunnable = watchdog
|
||||
handler.postDelayed(watchdog, DISPLAY_SETTLE_MS + extraDelayMs + WATCHDOG_MARGIN_MS)
|
||||
}
|
||||
|
||||
private fun matchRefreshRate(refreshRate: Float, fps: Float): RefreshRateMatch? {
|
||||
if (refreshRate <= 0f || fps <= 0f) return null
|
||||
|
||||
val exactError = abs(refreshRate - fps)
|
||||
if (exactError < RATE_TOLERANCE) {
|
||||
return RefreshRateMatch(reason = "exact", priority = 0, error = exactError)
|
||||
}
|
||||
|
||||
/// Request a display frame-rate switch. Invokes [onComplete] once, either:
|
||||
/// - immediately with `switched=false` when no switch is needed (invalid
|
||||
/// fps, no matching mode, seamless fallback); or
|
||||
/// - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the
|
||||
/// caller's [extraDelayMs], with `switched=true`; or
|
||||
/// - via a watchdog with `switched=true` if the real event never arrives,
|
||||
/// so the caller doesn't hang.
|
||||
///
|
||||
/// The caller is responsible for pausing playback before calling and
|
||||
/// resuming it after [onComplete] fires.
|
||||
fun setVideoFrameRate(
|
||||
fps: Float,
|
||||
videoDurationMs: Long,
|
||||
surface: Surface?,
|
||||
extraDelayMs: Long,
|
||||
onComplete: (switched: Boolean) -> Unit,
|
||||
) {
|
||||
currentVideoFps = fps
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
log("fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=${extraDelayMs}, API=${Build.VERSION.SDK_INT}")
|
||||
|
||||
when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
if (surface == null) {
|
||||
Log.d(TAG, "setVideoFrameRate: Surface not available")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
setFrameRateS(fps, surface, videoDurationMs, extraDelayMs, onComplete)
|
||||
}
|
||||
// API R's Surface.setFrameRate() only supports seamless switching (no
|
||||
// CHANGE_FRAME_RATE_ALWAYS), so 60→24Hz won't switch. Fall through to
|
||||
// preferredDisplayModeId which directly sets the display mode.
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> setFrameRateM(fps, extraDelayMs, onComplete)
|
||||
else -> onComplete(false)
|
||||
}
|
||||
val multiple = (refreshRate / fps).roundToInt()
|
||||
if (multiple > 1) {
|
||||
val multipleError = abs(refreshRate - (fps * multiple))
|
||||
if (multipleError < RATE_TOLERANCE) {
|
||||
return RefreshRateMatch(reason = "${multiple}x", priority = 1, error = multipleError)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearVideoFrameRate() {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
currentVideoFps = 0f
|
||||
// Resolve any pending setVideoFrameRate future as "not switched" so
|
||||
// the Dart caller's await doesn't hang on player dispose.
|
||||
firePendingCompletion("clear", switched = false)
|
||||
// Restore default display mode on API M (preferredDisplayModeId persists)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = 0
|
||||
activity.window?.attributes = attrs
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun currentRateMatch(fps: Float): RefreshRateMatch? {
|
||||
val current = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
currentDisplayMode()?.refreshRate
|
||||
} else {
|
||||
null
|
||||
} ?: return null
|
||||
return matchRefreshRate(current, fps)
|
||||
}
|
||||
|
||||
private fun currentModeDescription(): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
describeMode(currentDisplayMode())
|
||||
} else {
|
||||
"unavailable"
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun currentDisplay(): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
activity.display
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
(activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun currentDisplayMode(): Display.Mode? = currentDisplay()?.mode
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun describeMode(mode: Display.Mode?): String {
|
||||
if (mode == null) return "unknown"
|
||||
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz"
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun findBestModeMatch(fps: Float, currentMode: Display.Mode, supportedModes: Array<Display.Mode>): DisplayModeCandidate? = supportedModes.asSequence()
|
||||
.filter { mode ->
|
||||
mode.physicalHeight == currentMode.physicalHeight &&
|
||||
mode.physicalWidth == currentMode.physicalWidth
|
||||
}
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<DisplayModeCandidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
log("setDisplayMode fps=$fps")
|
||||
val display = currentDisplay()
|
||||
if (display == null) {
|
||||
log("display unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
private fun cancelPendingCallbacks() {
|
||||
pendingSettleRunnable?.let { handler.removeCallbacks(it) }
|
||||
watchdogRunnable?.let { handler.removeCallbacks(it) }
|
||||
pendingSettleRunnable = null
|
||||
watchdogRunnable = null
|
||||
val supportedModes = display.supportedModes
|
||||
if (supportedModes == null) {
|
||||
log("supported display modes unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
val currentMode = display.mode
|
||||
log("supported modes=${describeSupportedModes(supportedModes)}")
|
||||
|
||||
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes)
|
||||
if (modeMatch == null) {
|
||||
log("no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight}")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
private fun firePendingCompletion(reason: String, switched: Boolean) {
|
||||
cancelPendingCallbacks()
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
displayListener = null
|
||||
}
|
||||
val cb = pendingCompletion ?: return
|
||||
pendingCompletion = null
|
||||
Log.d(TAG, "FrameRateManager complete ($reason, switched=$switched)")
|
||||
cb(switched)
|
||||
val modeToUse = modeMatch.mode
|
||||
if (modeToUse.modeId == currentMode.modeId) {
|
||||
log("current mode already matches ${fps}fps (${modeMatch.match.reason}), no switch needed")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
private fun registerDisplayListener(extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
// Resolve any previous pending op before starting a new one.
|
||||
firePendingCompletion("superseded", switched = false)
|
||||
pendingCompletion = onComplete
|
||||
|
||||
displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = Unit
|
||||
override fun onDisplayRemoved(displayId: Int) = Unit
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
// Unregister immediately so a chatty display (e.g. several
|
||||
// onDisplayChanged events during HDMI renegotiation) doesn't
|
||||
// queue multiple settle callbacks.
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
|
||||
val settle = Runnable { firePendingCompletion("display settled", switched = true) }
|
||||
pendingSettleRunnable = settle
|
||||
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
|
||||
}
|
||||
}
|
||||
getDisplayManager().registerDisplayListener(displayListener, handler)
|
||||
|
||||
// Watchdog: if the TV never signals a display change (silently ignoring
|
||||
// the mode request), still complete after a bounded wait so the caller
|
||||
// doesn't hang.
|
||||
val watchdog = Runnable { firePendingCompletion("watchdog", switched = true) }
|
||||
watchdogRunnable = watchdog
|
||||
handler.postDelayed(watchdog, DISPLAY_SETTLE_MS + extraDelayMs + WATCHDOG_MARGIN_MS)
|
||||
}
|
||||
|
||||
private fun currentRateMatchesFps(fps: Float): Boolean {
|
||||
val current = activity.display?.mode?.refreshRate ?: return false
|
||||
if (current <= 0f) return false
|
||||
// Treat "equal within a frame" and "clean multiple" as a match —
|
||||
// same tolerance the API M matcher uses below.
|
||||
if (kotlin.math.abs(current - fps) < 0.1f) return true
|
||||
val mod = current % fps
|
||||
return mod < 0.1f || (fps - mod) < 0.1f
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.S)
|
||||
private fun setFrameRateS(
|
||||
fps: Float,
|
||||
surface: Surface,
|
||||
videoDurationMs: Long,
|
||||
extraDelayMs: Long,
|
||||
onComplete: (switched: Boolean) -> Unit,
|
||||
) {
|
||||
Log.d(TAG, "setFrameRateS: fps=$fps, duration=${videoDurationMs}ms")
|
||||
|
||||
// If the current display rate already satisfies the video fps, issue
|
||||
// the hint for book-keeping but skip the listener — otherwise we'd
|
||||
// wait for an onDisplayChanged event that never fires and end up
|
||||
// burning the watchdog timeout for no reason.
|
||||
if (currentRateMatchesFps(fps)) {
|
||||
Log.d(TAG, "Current display rate already matches ${fps}fps, no switch needed")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (videoDurationMs < SHORT_VIDEO_LENGTH_MS) {
|
||||
Log.d(TAG, "Short video, using seamless-only switching")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
var seamless = false
|
||||
activity.display?.mode?.alternativeRefreshRates?.let { refreshRates ->
|
||||
for (rate in refreshRates) {
|
||||
if (fps.toString().startsWith(rate.toString()) ||
|
||||
rate.toString().startsWith(fps.toString()) ||
|
||||
rate % fps == 0f) {
|
||||
seamless = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seamless) {
|
||||
log("Seamless switch available for ${fps}fps")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener(extraDelayMs, onComplete)
|
||||
} else {
|
||||
val userPreference = getDisplayManager().matchContentFrameRateUserPreference
|
||||
if (userPreference == DisplayManager.MATCH_CONTENT_FRAMERATE_ALWAYS) {
|
||||
Log.d(TAG, "User preference allows non-seamless switch")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener(extraDelayMs, onComplete)
|
||||
} else {
|
||||
Log.d(TAG, "Non-seamless switch not allowed, using seamless-only")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
onComplete(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setFrameRateM(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
Log.d(TAG, "setFrameRateM: fps=$fps")
|
||||
val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
@Suppress("DEPRECATION")
|
||||
val display = wm.defaultDisplay
|
||||
if (display == null) {
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
val supportedModes = display.supportedModes
|
||||
if (supportedModes == null) {
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
val currentMode = display.mode
|
||||
var modeToUse = currentMode
|
||||
|
||||
for (mode in supportedModes) {
|
||||
if (mode.physicalHeight != currentMode.physicalHeight ||
|
||||
mode.physicalWidth != currentMode.physicalWidth) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (BigDecimal(fps.toString()).setScale(1, RoundingMode.FLOOR) ==
|
||||
BigDecimal(mode.refreshRate.toString()).setScale(1, RoundingMode.FLOOR)) {
|
||||
modeToUse = mode
|
||||
break
|
||||
} else if ((mode.refreshRate % fps).let { it < 0.1f || (fps - it) < 0.1f }) {
|
||||
modeToUse = mode
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (modeToUse == currentMode) {
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "Switching to mode ${modeToUse.modeId} (${modeToUse.refreshRate}Hz)")
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = modeToUse.modeId
|
||||
activity.window?.attributes = attrs
|
||||
}
|
||||
registerDisplayListener(extraDelayMs, onComplete)
|
||||
log(
|
||||
"switching to ${describeMode(modeToUse)} for ${fps}fps " +
|
||||
"(${modeMatch.match.reason}, error=${modeMatch.match.error})"
|
||||
)
|
||||
val window = activity.window
|
||||
if (window == null) {
|
||||
log("window unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
registerDisplayListener(fps, extraDelayMs, onComplete)
|
||||
window.attributes = window.attributes.apply { preferredDisplayModeId = modeToUse.modeId }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
interface PlayerDelegate {
|
||||
fun onPropertyChange(name: String, value: Any?)
|
||||
fun onEvent(name: String, data: Map<String, Any>?)
|
||||
fun onPropertyChange(name: String, value: Any?)
|
||||
fun onEvent(name: String, data: Map<String, Any>?)
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ package com.edde746.plezy.shared
|
||||
import android.graphics.Color
|
||||
|
||||
object ThemeHelper {
|
||||
fun themeColor(mode: String?): Int? = when (mode) {
|
||||
"oled" -> Color.BLACK
|
||||
"dark" -> Color.parseColor("#0E0F12")
|
||||
"light" -> Color.parseColor("#F7F7F8")
|
||||
else -> null
|
||||
}
|
||||
fun themeColor(mode: String?): Int? = when (mode) {
|
||||
"oled" -> Color.BLACK
|
||||
"dark" -> Color.parseColor("#0E0F12")
|
||||
"light" -> Color.parseColor("#F7F7F8")
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,167 +16,169 @@ import java.util.concurrent.Executors
|
||||
* Flutter plugin for Android TV Watch Next integration.
|
||||
* Syncs Plex "On Deck" content to the Android TV launcher's Watch Next row.
|
||||
*/
|
||||
class WatchNextPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
|
||||
class WatchNextPlugin :
|
||||
FlutterPlugin,
|
||||
MethodChannel.MethodCallHandler {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WatchNextPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/watch_next"
|
||||
companion object {
|
||||
private const val TAG = "WatchNextPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/watch_next"
|
||||
|
||||
private var pendingDeepLink: String? = null
|
||||
|
||||
/**
|
||||
* Parse a Watch Next deep link intent.
|
||||
* Returns the content ID if this was a Watch Next intent, null otherwise.
|
||||
*/
|
||||
fun handleIntent(intent: Intent?): String? {
|
||||
val data = intent?.data ?: return null
|
||||
if (data.scheme == "plezy" && data.authority == "play") {
|
||||
return data.getQueryParameter("content_id")
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private var applicationContext: Context? = null
|
||||
private var watchNextProvider: WatchNextProvider? = null
|
||||
private val ioExecutor by lazy { Executors.newSingleThreadExecutor() }
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
applicationContext = binding.applicationContext
|
||||
watchNextProvider = WatchNextProvider(binding.applicationContext)
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
applicationContext = null
|
||||
watchNextProvider = null
|
||||
ioExecutor.shutdown()
|
||||
}
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"isSupported" -> handleIsSupported(result)
|
||||
"sync" -> handleSync(call, result)
|
||||
"clear" -> handleClear(result)
|
||||
"remove" -> handleRemove(call, result)
|
||||
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleIsSupported(result: MethodChannel.Result) {
|
||||
val context = applicationContext
|
||||
if (context == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
result.success(context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK))
|
||||
}
|
||||
|
||||
private fun handleSync(call: MethodCall, result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
|
||||
val itemsData = call.argument<List<Map<String, Any?>>>("items")
|
||||
if (itemsData == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'items' argument", null)
|
||||
return
|
||||
}
|
||||
|
||||
val items = itemsData.mapNotNull { parseWatchNextItem(it) }
|
||||
executeOnIo(result) { provider.syncWatchNextPrograms(items) }
|
||||
}
|
||||
|
||||
private fun handleClear(result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
executeOnIo(result) { provider.clearAll() }
|
||||
}
|
||||
|
||||
private fun handleRemove(call: MethodCall, result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
|
||||
val contentId = call.argument<String>("contentId")
|
||||
if (contentId == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'contentId' argument", null)
|
||||
return
|
||||
}
|
||||
executeOnIo(result) { provider.removeItem(contentId) }
|
||||
}
|
||||
|
||||
private fun executeOnIo(result: MethodChannel.Result, block: () -> Any?) {
|
||||
try {
|
||||
ioExecutor.execute {
|
||||
try {
|
||||
val value = block()
|
||||
mainHandler.post { result.success(value) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "IO operation failed: ${e.message}", e)
|
||||
mainHandler.post { result.error("IO_ERROR", e.message, null) }
|
||||
}
|
||||
}
|
||||
} catch (e: java.util.concurrent.RejectedExecutionException) {
|
||||
result.error("SHUTDOWN", "Plugin is shutting down", null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetInitialDeepLink(result: MethodChannel.Result) {
|
||||
val contentId = pendingDeepLink
|
||||
pendingDeepLink = null
|
||||
result.success(contentId)
|
||||
}
|
||||
|
||||
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
|
||||
val contentId = data["contentId"] as? String ?: return null
|
||||
val title = data["title"] as? String ?: return null
|
||||
|
||||
val typeString = data["type"] as? String ?: "movie"
|
||||
val type = when (typeString.lowercase()) {
|
||||
"episode" -> TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE
|
||||
"movie" -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
|
||||
else -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
|
||||
}
|
||||
|
||||
return WatchNextProvider.WatchNextItem(
|
||||
contentId = contentId,
|
||||
title = title,
|
||||
episodeTitle = data["episodeTitle"] as? String,
|
||||
description = data["description"] as? String,
|
||||
posterUri = data["posterUri"] as? String,
|
||||
type = type,
|
||||
duration = (data["duration"] as? Number)?.toLong() ?: 0L,
|
||||
lastPlaybackPosition = (data["lastPlaybackPosition"] as? Number)?.toLong() ?: 0L,
|
||||
lastEngagementTime = (data["lastEngagementTime"] as? Number)?.toLong() ?: System.currentTimeMillis(),
|
||||
seriesTitle = data["seriesTitle"] as? String,
|
||||
seasonNumber = (data["seasonNumber"] as? Number)?.toInt(),
|
||||
episodeNumber = (data["episodeNumber"] as? Number)?.toInt()
|
||||
)
|
||||
}
|
||||
private var pendingDeepLink: String? = null
|
||||
|
||||
/**
|
||||
* Store a deep link content ID for delivery to Flutter.
|
||||
* Called from MainActivity on intent receipt.
|
||||
* Parse a Watch Next deep link intent.
|
||||
* Returns the content ID if this was a Watch Next intent, null otherwise.
|
||||
*/
|
||||
fun notifyDeepLink(contentId: String) {
|
||||
pendingDeepLink = contentId
|
||||
try {
|
||||
methodChannel.invokeMethod("onWatchNextTap", mapOf("contentId" to contentId))
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Method channel not ready, stored as pending deep link")
|
||||
}
|
||||
fun handleIntent(intent: Intent?): String? {
|
||||
val data = intent?.data ?: return null
|
||||
if (data.scheme == "plezy" && data.authority == "play") {
|
||||
return data.getQueryParameter("content_id")
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private var applicationContext: Context? = null
|
||||
private var watchNextProvider: WatchNextProvider? = null
|
||||
private val ioExecutor by lazy { Executors.newSingleThreadExecutor() }
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
applicationContext = binding.applicationContext
|
||||
watchNextProvider = WatchNextProvider(binding.applicationContext)
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
applicationContext = null
|
||||
watchNextProvider = null
|
||||
ioExecutor.shutdown()
|
||||
}
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"isSupported" -> handleIsSupported(result)
|
||||
"sync" -> handleSync(call, result)
|
||||
"clear" -> handleClear(result)
|
||||
"remove" -> handleRemove(call, result)
|
||||
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleIsSupported(result: MethodChannel.Result) {
|
||||
val context = applicationContext
|
||||
if (context == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
result.success(context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK))
|
||||
}
|
||||
|
||||
private fun handleSync(call: MethodCall, result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
|
||||
val itemsData = call.argument<List<Map<String, Any?>>>("items")
|
||||
if (itemsData == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'items' argument", null)
|
||||
return
|
||||
}
|
||||
|
||||
val items = itemsData.mapNotNull { parseWatchNextItem(it) }
|
||||
executeOnIo(result) { provider.syncWatchNextPrograms(items) }
|
||||
}
|
||||
|
||||
private fun handleClear(result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
executeOnIo(result) { provider.clearAll() }
|
||||
}
|
||||
|
||||
private fun handleRemove(call: MethodCall, result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
|
||||
val contentId = call.argument<String>("contentId")
|
||||
if (contentId == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'contentId' argument", null)
|
||||
return
|
||||
}
|
||||
executeOnIo(result) { provider.removeItem(contentId) }
|
||||
}
|
||||
|
||||
private fun executeOnIo(result: MethodChannel.Result, block: () -> Any?) {
|
||||
try {
|
||||
ioExecutor.execute {
|
||||
try {
|
||||
val value = block()
|
||||
mainHandler.post { result.success(value) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "IO operation failed: ${e.message}", e)
|
||||
mainHandler.post { result.error("IO_ERROR", e.message, null) }
|
||||
}
|
||||
}
|
||||
} catch (e: java.util.concurrent.RejectedExecutionException) {
|
||||
result.error("SHUTDOWN", "Plugin is shutting down", null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetInitialDeepLink(result: MethodChannel.Result) {
|
||||
val contentId = pendingDeepLink
|
||||
pendingDeepLink = null
|
||||
result.success(contentId)
|
||||
}
|
||||
|
||||
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
|
||||
val contentId = data["contentId"] as? String ?: return null
|
||||
val title = data["title"] as? String ?: return null
|
||||
|
||||
val typeString = data["type"] as? String ?: "movie"
|
||||
val type = when (typeString.lowercase()) {
|
||||
"episode" -> TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE
|
||||
"movie" -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
|
||||
else -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
|
||||
}
|
||||
|
||||
return WatchNextProvider.WatchNextItem(
|
||||
contentId = contentId,
|
||||
title = title,
|
||||
episodeTitle = data["episodeTitle"] as? String,
|
||||
description = data["description"] as? String,
|
||||
posterUri = data["posterUri"] as? String,
|
||||
type = type,
|
||||
duration = (data["duration"] as? Number)?.toLong() ?: 0L,
|
||||
lastPlaybackPosition = (data["lastPlaybackPosition"] as? Number)?.toLong() ?: 0L,
|
||||
lastEngagementTime = (data["lastEngagementTime"] as? Number)?.toLong() ?: System.currentTimeMillis(),
|
||||
seriesTitle = data["seriesTitle"] as? String,
|
||||
seasonNumber = (data["seasonNumber"] as? Number)?.toInt(),
|
||||
episodeNumber = (data["episodeNumber"] as? Number)?.toInt()
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a deep link content ID for delivery to Flutter.
|
||||
* Called from MainActivity on intent receipt.
|
||||
*/
|
||||
fun notifyDeepLink(contentId: String) {
|
||||
pendingDeepLink = contentId
|
||||
try {
|
||||
methodChannel.invokeMethod("onWatchNextTap", mapOf("contentId" to contentId))
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Method channel not ready, stored as pending deep link")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,154 +14,151 @@ import androidx.tvprovider.media.tv.WatchNextProgram
|
||||
*/
|
||||
class WatchNextProvider(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WatchNextProvider"
|
||||
}
|
||||
companion object {
|
||||
private const val TAG = "WatchNextProvider"
|
||||
}
|
||||
|
||||
data class WatchNextItem(
|
||||
val contentId: String,
|
||||
val title: String,
|
||||
val episodeTitle: String?,
|
||||
val description: String?,
|
||||
val posterUri: String?,
|
||||
val type: Int,
|
||||
val duration: Long,
|
||||
val lastPlaybackPosition: Long,
|
||||
val lastEngagementTime: Long,
|
||||
val seriesTitle: String?,
|
||||
val seasonNumber: Int?,
|
||||
val episodeNumber: Int?
|
||||
data class WatchNextItem(
|
||||
val contentId: String,
|
||||
val title: String,
|
||||
val episodeTitle: String?,
|
||||
val description: String?,
|
||||
val posterUri: String?,
|
||||
val type: Int,
|
||||
val duration: Long,
|
||||
val lastPlaybackPosition: Long,
|
||||
val lastEngagementTime: Long,
|
||||
val seriesTitle: String?,
|
||||
val seasonNumber: Int?,
|
||||
val episodeNumber: Int?
|
||||
)
|
||||
|
||||
/**
|
||||
* Sync items to Watch Next row.
|
||||
* Uses applyBatch to delete + insert in a single transaction so the
|
||||
* launcher receives one content-change notification with the full set.
|
||||
*/
|
||||
fun syncWatchNextPrograms(items: List<WatchNextItem>): Boolean = try {
|
||||
val ops = ArrayList<ContentProviderOperation>()
|
||||
|
||||
ops.add(
|
||||
ContentProviderOperation.newDelete(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI
|
||||
).build()
|
||||
)
|
||||
|
||||
/**
|
||||
* Sync items to Watch Next row.
|
||||
* Uses applyBatch to delete + insert in a single transaction so the
|
||||
* launcher receives one content-change notification with the full set.
|
||||
*/
|
||||
fun syncWatchNextPrograms(items: List<WatchNextItem>): Boolean {
|
||||
return try {
|
||||
val ops = ArrayList<ContentProviderOperation>()
|
||||
for (item in items) {
|
||||
val program = buildProgram(item)
|
||||
ops.add(
|
||||
ContentProviderOperation.newInsert(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI
|
||||
).withValues(program.toContentValues()).build()
|
||||
)
|
||||
}
|
||||
|
||||
ops.add(
|
||||
ContentProviderOperation.newDelete(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI
|
||||
).build()
|
||||
context.contentResolver.applyBatch(TvContractCompat.AUTHORITY, ops)
|
||||
Log.d(TAG, "Synced ${items.size} Watch Next entries")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to sync Watch Next programs", e)
|
||||
false
|
||||
}
|
||||
|
||||
fun clearAll(): Boolean = try {
|
||||
context.contentResolver.delete(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
null,
|
||||
null
|
||||
)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to clear Watch Next entries", e)
|
||||
false
|
||||
}
|
||||
|
||||
fun removeItem(contentId: String): Boolean {
|
||||
return try {
|
||||
val cursor = context.contentResolver.query(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
arrayOf(
|
||||
TvContractCompat.WatchNextPrograms._ID,
|
||||
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID
|
||||
),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
val idIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms._ID)
|
||||
val providerIdIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID)
|
||||
|
||||
if (idIndex < 0 || providerIdIndex < 0) return false
|
||||
|
||||
while (it.moveToNext()) {
|
||||
if (it.getString(providerIdIndex) == contentId) {
|
||||
val id = it.getLong(idIndex)
|
||||
val deleteUri = ContentUris.withAppendedId(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
id
|
||||
)
|
||||
|
||||
for (item in items) {
|
||||
val program = buildProgram(item)
|
||||
ops.add(
|
||||
ContentProviderOperation.newInsert(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI
|
||||
).withValues(program.toContentValues()).build()
|
||||
)
|
||||
}
|
||||
|
||||
context.contentResolver.applyBatch(TvContractCompat.AUTHORITY, ops)
|
||||
Log.d(TAG, "Synced ${items.size} Watch Next entries")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to sync Watch Next programs", e)
|
||||
false
|
||||
context.contentResolver.delete(deleteUri, null, null)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to remove Watch Next item: $contentId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildProgram(item: WatchNextItem): WatchNextProgram {
|
||||
val watchNextType = if (item.lastPlaybackPosition > 0) {
|
||||
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE
|
||||
} else {
|
||||
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT
|
||||
}
|
||||
|
||||
fun clearAll(): Boolean {
|
||||
return try {
|
||||
context.contentResolver.delete(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
null,
|
||||
null
|
||||
)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to clear Watch Next entries", e)
|
||||
false
|
||||
}
|
||||
val builder = WatchNextProgram.Builder()
|
||||
.setType(item.type)
|
||||
.setWatchNextType(watchNextType)
|
||||
.setTitle(item.title)
|
||||
.setInternalProviderId(item.contentId)
|
||||
.setLastEngagementTimeUtcMillis(item.lastEngagementTime)
|
||||
|
||||
item.description?.let { builder.setDescription(it) }
|
||||
|
||||
item.posterUri?.let { uri ->
|
||||
try {
|
||||
builder.setPosterArtUri(Uri.parse(uri))
|
||||
builder.setPosterArtAspectRatio(TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to parse poster URI: $uri", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun removeItem(contentId: String): Boolean {
|
||||
return try {
|
||||
val cursor = context.contentResolver.query(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
arrayOf(
|
||||
TvContractCompat.WatchNextPrograms._ID,
|
||||
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID
|
||||
),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
val idIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms._ID)
|
||||
val providerIdIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID)
|
||||
|
||||
if (idIndex < 0 || providerIdIndex < 0) return false
|
||||
|
||||
while (it.moveToNext()) {
|
||||
if (it.getString(providerIdIndex) == contentId) {
|
||||
val id = it.getLong(idIndex)
|
||||
val deleteUri = ContentUris.withAppendedId(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
id
|
||||
)
|
||||
context.contentResolver.delete(deleteUri, null, null)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to remove Watch Next item: $contentId", e)
|
||||
false
|
||||
}
|
||||
if (item.duration > 0) {
|
||||
builder.setDurationMillis(item.duration.toInt())
|
||||
if (item.lastPlaybackPosition > 0) {
|
||||
builder.setLastPlaybackPositionMillis(item.lastPlaybackPosition.toInt())
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildProgram(item: WatchNextItem): WatchNextProgram {
|
||||
val watchNextType = if (item.lastPlaybackPosition > 0)
|
||||
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE
|
||||
else
|
||||
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT
|
||||
|
||||
val builder = WatchNextProgram.Builder()
|
||||
.setType(item.type)
|
||||
.setWatchNextType(watchNextType)
|
||||
.setTitle(item.title)
|
||||
.setInternalProviderId(item.contentId)
|
||||
.setLastEngagementTimeUtcMillis(item.lastEngagementTime)
|
||||
|
||||
item.description?.let { builder.setDescription(it) }
|
||||
|
||||
item.posterUri?.let { uri ->
|
||||
try {
|
||||
builder.setPosterArtUri(Uri.parse(uri))
|
||||
builder.setPosterArtAspectRatio(TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to parse poster URI: $uri", e)
|
||||
}
|
||||
}
|
||||
|
||||
if (item.duration > 0) {
|
||||
builder.setDurationMillis(item.duration.toInt())
|
||||
if (item.lastPlaybackPosition > 0) {
|
||||
builder.setLastPlaybackPositionMillis(item.lastPlaybackPosition.toInt())
|
||||
}
|
||||
}
|
||||
|
||||
if (item.type == TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE) {
|
||||
item.episodeTitle?.let { builder.setEpisodeTitle(it) }
|
||||
item.seasonNumber?.let { builder.setSeasonNumber(it) }
|
||||
item.episodeNumber?.let { builder.setEpisodeNumber(it) }
|
||||
}
|
||||
|
||||
val intentUri = Uri.Builder()
|
||||
.scheme("plezy")
|
||||
.authority("play")
|
||||
.appendQueryParameter("content_id", item.contentId)
|
||||
.build()
|
||||
builder.setIntentUri(intentUri)
|
||||
|
||||
return builder.build()
|
||||
if (item.type == TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE) {
|
||||
item.episodeTitle?.let { builder.setEpisodeTitle(it) }
|
||||
item.seasonNumber?.let { builder.setSeasonNumber(it) }
|
||||
item.episodeNumber?.let { builder.setEpisodeNumber(it) }
|
||||
}
|
||||
|
||||
val intentUri = Uri.Builder()
|
||||
.scheme("plezy")
|
||||
.authority("play")
|
||||
.appendQueryParameter("content_id", item.contentId)
|
||||
.build()
|
||||
builder.setIntentUri(intentUri)
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@android:color/white" />
|
||||
<item android:drawable="@color/splash_background" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- TV (Android TV / Google TV / Fire TV) launch + window background.
|
||||
The television UI-mode qualifier outranks night/notnight, so this wins
|
||||
even on TVs that report notnight (most do) where values/ would resolve
|
||||
the near-white #F7F7F8. Black matches the OLED default theme on TV. -->
|
||||
<color name="splash_background">#000000</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,313 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DvBitstreamSanitizerTest {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
// --- HDR10+ SEI stripping (native DV codec path) ---
|
||||
|
||||
@Test
|
||||
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
|
||||
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
|
||||
val originalLimit = buffer.limit()
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
assertTrue(buffer.limit() < originalLimit)
|
||||
assertEquals(0, buffer.position())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsSuffixSei() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
|
||||
val buffer = bufferOf(vcl, suffixSei)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(vcl, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handles3ByteStartCodes() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02), startCodeLen = 3)
|
||||
val sei = annexBNal(39, hdr10PlusSeiPayload(), startCodeLen = 3)
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03), startCodeLen = 3)
|
||||
val buffer = bufferOf(vcl1, sei, vcl2)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesNonHdr10PlusT35Sei() {
|
||||
// Same T.35 layout but wrong country code (0x00 instead of 0xB5).
|
||||
val sei = annexBNal(
|
||||
39,
|
||||
byteArrayOf(0x04, 0x07, 0x00, 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00)
|
||||
)
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), sei, annexBNal(1, byteArrayOf(0x02)))
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noOpWithoutSeiNals() {
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01, 0x02)), annexBNal(1, byteArrayOf(0x03)))
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsTruncatedSei() {
|
||||
// Declares payload size 7 but the identifier bytes are cut short.
|
||||
val truncated = annexBNal(39, byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C))
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), truncated)
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsHdr10PlusSeiWhenFlagOff() {
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), hdr10PlusSei())
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- DV RPU/EL stripping (HEVC fallback path) ---
|
||||
|
||||
@Test
|
||||
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
|
||||
val el = annexBNal(63, byteArrayOf(0x42))
|
||||
val sei = hdr10PlusSei()
|
||||
val buffer = bufferOf(vcl, rpu, sei, el)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
|
||||
|
||||
assertArrayEquals(concat(vcl, sei), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bothFlagsStripBothMetadataKinds() {
|
||||
val vcl1 = annexBNal(19, byteArrayOf(0x00)) // IDR_W_RADL
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x05))
|
||||
val buffer = bufferOf(vcl1, annexBNal(62, byteArrayOf(0x19)), hdr10PlusSei(), vcl2)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- Buffer handling ---
|
||||
|
||||
@Test
|
||||
fun respectsPositionAndRestoresIt() {
|
||||
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
val content = concat(prefix, vcl, hdr10PlusSei())
|
||||
val buffer = ByteBuffer.wrap(content.copyOf())
|
||||
buffer.position(prefix.size)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(prefix.size, buffer.position())
|
||||
assertArrayEquals(vcl, remainingBytes(buffer))
|
||||
// Bytes before the position are untouched.
|
||||
assertEquals(0xAA.toByte(), buffer.get(0))
|
||||
assertEquals(0xBB.toByte(), buffer.get(1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun worksOnDirectBuffers() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val buffer = directBufferOf(vcl, hdr10PlusSei())
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(vcl, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyBufferIsNoOp() {
|
||||
val buffer = ByteBuffer.allocate(0)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertEquals(0, buffer.position())
|
||||
assertEquals(0, buffer.limit())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsOnDirectBufferWithNonZeroPosition() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val buffer = directBufferOf(byteArrayOf(0xAA.toByte(), 0xBB.toByte()), vcl1, hdr10PlusSei(), vcl2)
|
||||
buffer.position(2)
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(1, stripped)
|
||||
assertEquals(2, buffer.position())
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
// Bytes before the position are untouched.
|
||||
assertEquals(0xAA.toByte(), buffer.get(0))
|
||||
assertEquals(0xBB.toByte(), buffer.get(1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noStripLeavesDirectBufferStateUntouched() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val buffer = directBufferOf(vcl1, vcl2)
|
||||
val originalLimit = buffer.limit()
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertEquals(0, stripped)
|
||||
assertEquals(0, buffer.position())
|
||||
assertEquals(originalLimit, buffer.limit())
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsTrailingRpuWithZeroByteTailWriteBack() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
|
||||
val buffer = directBufferOf(vcl1, vcl2, rpu)
|
||||
val originalLimit = buffer.limit()
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
|
||||
|
||||
assertEquals(1, stripped)
|
||||
assertEquals(originalLimit - rpu.size, buffer.limit())
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun growsScratchForLargeSamples() {
|
||||
// Exceeds the initial 256KB scratch and one doubling; non-zero filler so no
|
||||
// accidental start codes appear in the payloads.
|
||||
val vcl1 = annexBNal(1, ByteArray(800_000) { 0xAB.toByte() })
|
||||
val vcl2 = annexBNal(1, ByteArray(700_000) { 0xCD.toByte() })
|
||||
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(1, stripped)
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reusesSanitizerAcrossSequentialBuffers() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
|
||||
|
||||
val first = bufferOf(vcl1, hdr10PlusSei(), vcl2)
|
||||
assertEquals(1, sanitizer.sanitize(first, stripHdr10PlusSei = true, stripDvRpu = false))
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(first))
|
||||
|
||||
val second = bufferOf(vcl1, vcl2)
|
||||
assertEquals(0, sanitizer.sanitize(second, stripHdr10PlusSei = true, stripDvRpu = false))
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(second))
|
||||
|
||||
val third = bufferOf(hdr10PlusSei(), vcl1, annexBNal(62, byteArrayOf(0x19)), vcl2, hdr10PlusSei())
|
||||
assertEquals(3, sanitizer.sanitize(third, stripHdr10PlusSei = true, stripDvRpu = true))
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(third))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsBufferWithoutStartCodes() {
|
||||
val content = byteArrayOf(0x12, 0x34, 0x56, 0x78)
|
||||
val buffer = ByteBuffer.wrap(content.copyOf())
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertEquals(0, stripped)
|
||||
assertEquals(0, buffer.position())
|
||||
assertEquals(content.size, buffer.limit())
|
||||
assertArrayEquals(content, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsMultipleSeisInOneAccessUnit() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
|
||||
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2, suffixSei)
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(2, stripped)
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
/** Builds an HEVC NAL unit: start code + 2-byte NAL header encoding [nalUnitType] + payload. */
|
||||
private fun annexBNal(nalUnitType: Int, payload: ByteArray, startCodeLen: Int = 4): ByteArray {
|
||||
val startCode = if (startCodeLen == 3) byteArrayOf(0, 0, 1) else byteArrayOf(0, 0, 0, 1)
|
||||
val header = byteArrayOf(((nalUnitType shl 1) and 0x7E).toByte(), 0x01)
|
||||
return concat(startCode, header, payload)
|
||||
}
|
||||
|
||||
/**
|
||||
* SEI payload: type 4 (user_data_registered_itu_t_t35), size 7, then the HDR10+
|
||||
* identifiers — country 0xB5, provider 0x003C, oriented code 0x0001, app id 4, version 0 —
|
||||
* closed by the rbsp_trailing_bits stop byte real SEI NALs always end with (a trailing 0x00
|
||||
* would otherwise be ambiguous against a following 3-byte start code).
|
||||
*/
|
||||
private fun hdr10PlusSeiPayload(): ByteArray = byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00, 0x80.toByte())
|
||||
|
||||
private fun hdr10PlusSei(): ByteArray = annexBNal(39, hdr10PlusSeiPayload())
|
||||
|
||||
private fun concat(vararg parts: ByteArray): ByteArray {
|
||||
val result = ByteArray(parts.sumOf { it.size })
|
||||
var offset = 0
|
||||
for (part in parts) {
|
||||
part.copyInto(result, offset)
|
||||
offset += part.size
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun bufferOf(vararg parts: ByteArray): ByteBuffer = ByteBuffer.wrap(concat(*parts))
|
||||
|
||||
private fun directBufferOf(vararg parts: ByteArray): ByteBuffer {
|
||||
val content = concat(*parts)
|
||||
val buffer = ByteBuffer.allocateDirect(content.size)
|
||||
buffer.put(content)
|
||||
buffer.flip()
|
||||
return buffer
|
||||
}
|
||||
|
||||
private fun remainingBytes(buffer: ByteBuffer): ByteArray {
|
||||
val copy = ByteArray(buffer.remaining())
|
||||
buffer.duplicate().get(copy)
|
||||
return copy
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,28 @@ allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
if (providers.gradleProperty("localAssCore").isPresent) {
|
||||
// Opt-in A/B of a locally built libass native core: build it in the
|
||||
// libass-android fork with `./gradlew :lib_ass:publishToMavenLocal
|
||||
// -PVERSION_NAME=0.4.0-local`, then build this app with -PlocalAssCore.
|
||||
mavenLocal()
|
||||
} else {
|
||||
// Production libass native core: the -O3/NEON/asm AAR published on
|
||||
// the edde746/libass-android fork's releases (the upstream Maven
|
||||
// artifact io.github.peerless2012:ass ships un-optimized natives —
|
||||
// see the fork's pinned libass-cmake fix). Resolved as
|
||||
// <tag>/ass-<tag>.aar with no metadata probing.
|
||||
exclusiveContent {
|
||||
forRepository {
|
||||
ivy {
|
||||
url = uri("https://github.com/edde746/libass-android/releases/download")
|
||||
patternLayout { artifact("[revision]/[artifact]-[revision].[ext]") }
|
||||
metadataSources { artifact() }
|
||||
}
|
||||
}
|
||||
filter { includeModule("io.github.peerless2012", "ass") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
require 'dotenv/load'
|
||||
Dotenv.load("../../.env")
|
||||
require 'shellwords'
|
||||
|
||||
PROJECT_ROOT = File.expand_path("../..", __dir__)
|
||||
PROJECT_ROOT_ARG = Shellwords.escape(PROJECT_ROOT)
|
||||
|
||||
Dotenv.load(File.join(PROJECT_ROOT, ".env"))
|
||||
|
||||
default_platform(:android)
|
||||
|
||||
@@ -7,7 +12,7 @@ platform :android do
|
||||
desc "Build and deploy to Google Play Store"
|
||||
lane :release do
|
||||
# Get version from pubspec.yaml
|
||||
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
|
||||
pubspec_path = File.join(PROJECT_ROOT, "pubspec.yaml")
|
||||
pubspec_content = File.read(pubspec_path)
|
||||
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
|
||||
|
||||
@@ -19,11 +24,11 @@ platform :android do
|
||||
UI.user_error!("Could not extract version from pubspec.yaml")
|
||||
end
|
||||
|
||||
git_commit = `git rev-parse --short HEAD`.strip
|
||||
git_commit = `git -C #{PROJECT_ROOT_ARG} rev-parse --short HEAD`.strip
|
||||
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=play-store --obfuscate --split-debug-info=debug-info/android-aab")
|
||||
sh("cd #{ENV['PWD']}/.. && ./scripts/upload-symbols.sh android-aab")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && flutter build appbundle --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=play-store --dart-define=SENTRY_DIST=play-store --obfuscate --split-debug-info=debug-info/android-aab --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-aab/obfuscation.map.json")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=play-store ./scripts/upload-symbols.sh android-aab")
|
||||
|
||||
upload_to_play_store(
|
||||
track: "production",
|
||||
@@ -33,8 +38,8 @@ platform :android do
|
||||
)
|
||||
|
||||
# Build universal APK for Amazon Appstore (doesn't accept AABs, excludes x86 via env var)
|
||||
sh("cd #{ENV['PWD']}/.. && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=amazon --obfuscate --split-debug-info=debug-info/android-apk")
|
||||
sh("cd #{ENV['PWD']}/.. && ./scripts/upload-symbols.sh android-apk")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=amazon --dart-define=SENTRY_DIST=amazon --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=amazon ./scripts/upload-symbols.sh android-apk")
|
||||
|
||||
upload_to_amazon_appstore(
|
||||
apk_paths: [
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
# This builtInKotlin flag was added automatically by Flutter migrator
|
||||
android.builtInKotlin=false
|
||||
# This newDsl flag was added automatically by Flutter migrator
|
||||
android.newDsl=false
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// libass ASS subtitle rendering: Kotlin/JNI bindings + Media3 integration
|
||||
// (extractor, parsers, AssHandler, GL atlas overlay). The native libass core
|
||||
// (libass.so + prefab headers) comes from the Maven artifact
|
||||
// io.github.peerless2012:ass; this module compiles its JNI against it.
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.edde746.plezy.libass"
|
||||
compileSdk = 36
|
||||
// Matches flutter.ndkVersion so only one NDK is provisioned. This module's
|
||||
// CMake build (-DANDROID_STL=c++_shared) contributes NDK 28.2's
|
||||
// libc++_shared.so to packaging, but that copy is NOT what ships: the app
|
||||
// packages the libmpv AAR's newer copy with top merge priority (see
|
||||
// app/build.gradle.kts packaging { jniLibs } + sourceSets).
|
||||
ndkVersion = "28.2.13676358"
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 21
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
if (project.hasProperty("localAssCore")) {
|
||||
// The locally published A/B core only ships device ABIs (x86 would need
|
||||
// nasm on the host); match it so prefab resolution doesn't fail.
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
|
||||
}
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
// libass.so in the prefab AAR is built against c++_shared (abi.json: stl=c++_shared);
|
||||
// prefab validates consumer STL compatibility.
|
||||
arguments += listOf("-DANDROID_STL=c++_shared")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
prefab = true
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// libass.so is a prefab IMPORTED target (linked, not owned) — the app packages
|
||||
// it from the io.github.peerless2012:ass AAR; don't duplicate it here.
|
||||
excludes.add("**/libass.so")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
version = "3.22.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// compileOnly: prefab headers + link-time libass.so come from the AAR; runtime
|
||||
// packaging of libass.so is the app's implementation dependency.
|
||||
// -PlocalAssCore swaps in a mavenLocal()-published core for A/B tests (must
|
||||
// match the app module's version so one libass.so is linked and packaged).
|
||||
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
|
||||
compileOnly("io.github.peerless2012:ass:$assCoreVersion@aar")
|
||||
|
||||
implementation("androidx.annotation:annotation:1.9.1")
|
||||
implementation("androidx.annotation:annotation-experimental:1.5.1")
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
implementation("androidx.media3:media3-ui:1.9.2")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# Constructed from JNI via FindClass/NewObject (AssKt.c).
|
||||
-keep class com.edde746.plezy.libass.AssAtlasFrame { *; }
|
||||
# JNI exports bind by name (Java_com_edde746_plezy_libass_*); keep the names stable.
|
||||
-keepclasseswithmembernames class com.edde746.plezy.libass.* {
|
||||
native <methods>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,436 @@
|
||||
// JNI bindings for libass. Exports use standard Java_<package>_<Class>_<method>
|
||||
// naming so no RegisterNatives/JNI_OnLoad registration is needed.
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
static inline long long nowMs(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
#include "ass/ass.h"
|
||||
|
||||
#define LOG_TAG "SubtitleRenderer"
|
||||
|
||||
static void assMessageCallback(int level, const char* fmt, va_list args, void* data) {
|
||||
if (level > 4) return;
|
||||
|
||||
if (level >= 2) {
|
||||
__android_log_vprint(ANDROID_LOG_WARN, LOG_TAG, fmt, args);
|
||||
} else {
|
||||
__android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, fmt, args);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Ass (library) ---
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssInit(JNIEnv* env, jclass clazz) {
|
||||
ASS_Library* assLibrary = ass_library_init();
|
||||
ass_set_message_cb(assLibrary, assMessageCallback, NULL);
|
||||
ass_set_extract_fonts(assLibrary, 1);
|
||||
return (jlong)assLibrary;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssAddFont(
|
||||
JNIEnv* env, jclass clazz, jlong ass, jstring name, jbyteArray byteArray) {
|
||||
jsize length = (*env)->GetArrayLength(env, byteArray);
|
||||
jbyte* bytePtr = (*env)->GetByteArrayElements(env, byteArray, NULL);
|
||||
if (bytePtr == NULL) {
|
||||
return;
|
||||
}
|
||||
const char* cName = (*env)->GetStringUTFChars(env, name, NULL);
|
||||
ass_add_font(((ASS_Library*)ass), cName, (char*)bytePtr, length);
|
||||
(*env)->ReleaseByteArrayElements(env, byteArray, bytePtr, 0);
|
||||
if (cName != NULL) {
|
||||
(*env)->ReleaseStringUTFChars(env, name, cName);
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssDeinit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
if (ass) {
|
||||
ass_library_done((ASS_Library*)ass);
|
||||
}
|
||||
}
|
||||
|
||||
// --- AssTrack ---
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackInit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
return (jlong)ass_new_track((ASS_Library*)ass);
|
||||
}
|
||||
|
||||
// Shared body of readBuffer/readChunk: pins the byte array and feeds libass.
|
||||
// chunked != 0 routes to ass_process_chunk (timed dialogue), else ass_process_data.
|
||||
static void processTrackBytes(
|
||||
JNIEnv* env, jlong track, jbyteArray buffer, jint offset, jint length, jlong start, jlong duration, int chunked) {
|
||||
if (!track) return;
|
||||
jbyte* elements = (*env)->GetByteArrayElements(env, buffer, NULL);
|
||||
if (elements == NULL) {
|
||||
return;
|
||||
}
|
||||
if (chunked) {
|
||||
ass_process_chunk((ASS_Track*)track, (char*)(elements + offset), length, start, duration);
|
||||
} else {
|
||||
ass_process_data((ASS_Track*)track, (char*)(elements + offset), length);
|
||||
}
|
||||
(*env)->ReleaseByteArrayElements(env, buffer, elements, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackReadBuffer(
|
||||
JNIEnv* env, jclass clazz, jlong track, jbyteArray buffer, jint offset, jint length) {
|
||||
processTrackBytes(env, track, buffer, offset, length, 0, 0, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackReadChunk(
|
||||
JNIEnv* env, jclass clazz, jlong track, jlong start, jlong duration, jbyteArray buffer, jint offset, jint length) {
|
||||
processTrackBytes(env, track, buffer, offset, length, start, duration, 1);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackDeinit(JNIEnv* env, jclass clazz, jlong track) {
|
||||
if (!track) return;
|
||||
ass_free_track((ASS_Track*)track);
|
||||
}
|
||||
|
||||
// Earliest event Start strictly after afterMs, or -1. Lets the render pipeline
|
||||
// pre-render (cache-warm) the next upcoming event during idle stretches so
|
||||
// heavy typesetting doesn't pay its cache-cold rasterization at appearance.
|
||||
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNextEventStart(
|
||||
JNIEnv* env, jclass clazz, jlong track, jlong afterMs) {
|
||||
if (!track) return -1;
|
||||
ASS_Track* t = (ASS_Track*)track;
|
||||
long long best = -1;
|
||||
for (int i = 0; i < t->n_events; i++) {
|
||||
const long long start = t->events[i].Start;
|
||||
if (start > afterMs && (best < 0 || start < best)) best = start;
|
||||
}
|
||||
return (jlong)best;
|
||||
}
|
||||
|
||||
// Earliest visible-content boundary (event Start OR End) strictly after afterMs,
|
||||
// or -1. A cache-warming prefetch is only invisible while no boundary passes:
|
||||
// the render pipeline uses this to ensure nothing on screen is due to change
|
||||
// before the event it is about to warm.
|
||||
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNextEventChange(
|
||||
JNIEnv* env, jclass clazz, jlong track, jlong afterMs) {
|
||||
if (!track) return -1;
|
||||
ASS_Track* t = (ASS_Track*)track;
|
||||
long long best = -1;
|
||||
for (int i = 0; i < t->n_events; i++) {
|
||||
const long long start = t->events[i].Start;
|
||||
const long long end = start + t->events[i].Duration;
|
||||
if (start > afterMs && (best < 0 || start < best)) best = start;
|
||||
if (end > afterMs && (best < 0 || end < best)) best = end;
|
||||
}
|
||||
return (jlong)best;
|
||||
}
|
||||
|
||||
// --- AssRender ---
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderInit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
ASS_Renderer* assRenderer = ass_renderer_init((ASS_Library*)ass);
|
||||
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, NULL, 1);
|
||||
return (jlong)assRenderer;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetFontScale(
|
||||
JNIEnv* env, jclass clazz, jlong render, jfloat scale) {
|
||||
if (!render) return;
|
||||
ass_set_font_scale((ASS_Renderer*)render, scale);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetCacheLimit(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint glyphMax, jint bitmapMaxSize) {
|
||||
if (!render) return;
|
||||
ass_set_cache_limits((ASS_Renderer*)render, glyphMax, bitmapMaxSize);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetFrameSize(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint width, jint height) {
|
||||
if (!render) return;
|
||||
ass_set_frame_size((ASS_Renderer*)render, width, height);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetStorageSize(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint width, jint height) {
|
||||
if (!render) return;
|
||||
ass_set_storage_size((ASS_Renderer*)render, width, height);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetMargins(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint top, jint bottom, jint left, jint right) {
|
||||
if (!render) return;
|
||||
ass_set_margins((ASS_Renderer*)render, top, bottom, left, right);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetUseMargins(
|
||||
JNIEnv* env, jclass clazz, jlong render, jboolean use) {
|
||||
if (!render) return;
|
||||
ass_set_use_margins((ASS_Renderer*)render, use ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderDeinit(JNIEnv* env, jclass clazz, jlong render) {
|
||||
if (render) {
|
||||
ass_renderer_done((ASS_Renderer*)render);
|
||||
}
|
||||
}
|
||||
|
||||
// (image, original-list index) pair so packing can run in height-sorted order
|
||||
// while slots stay keyed by list position (= blend order) for pass 2.
|
||||
typedef struct {
|
||||
ASS_Image* img;
|
||||
int idx;
|
||||
} PackItem;
|
||||
|
||||
static int comparePackItemsByHeightDesc(const void* a, const void* b) {
|
||||
const PackItem* ia = (const PackItem*)a;
|
||||
const PackItem* ib = (const PackItem*)b;
|
||||
return ib->img->h - ia->img->h;
|
||||
}
|
||||
|
||||
// Throttle for truncation warnings (shared across renderers; logging only).
|
||||
static int truncationLogCounter = 0;
|
||||
|
||||
// Renders a frame into the provided atlas + vertex direct ByteBuffers.
|
||||
//
|
||||
// - atlasBuf holds packed ALPHA_8 pixels with row stride atlasMaxW. Only the first
|
||||
// atlasHeight rows are written; the caller uploads that region to a texture
|
||||
// allocated once at atlasMaxW × atlasMaxH.
|
||||
// - vertexBuf holds a per-quad vertex stream (6 vertices × (2 pos + 2 uv + 4 color)
|
||||
// floats = 48 floats = 192 bytes per quad). Must match BYTES_PER_QUAD/VERTEX in
|
||||
// AssSubtitleAtlasPipeline.kt. Ready for a single glDrawArrays(GL_TRIANGLES, 0, N * 6).
|
||||
// - UVs are normalized against atlasMaxW × atlasMaxH (the allocated texture dims),
|
||||
// not the packed region, so the texture never needs reallocation.
|
||||
// - Images are packed in height-sorted rows (minimizes packed height) but vertices
|
||||
// are emitted in original list order — the list order is libass's painter order.
|
||||
//
|
||||
// Never fails on content size: images that don't fit the remaining atlas/vertex
|
||||
// capacity are dropped and counted in AssAtlasFrame.truncated, so a heavy frame
|
||||
// degrades instead of going stale. Returns NULL only for missing buffers/handles.
|
||||
// On changed == 0, returns (0, 0, 0, changed, 0) without touching the buffers —
|
||||
// caller reuses the atlas texture already on the GPU.
|
||||
JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFrameAtlas(
|
||||
JNIEnv* env, jclass clazz, jlong render, jlong track, jlong time, jobject atlasBuf, jint atlasMaxW, jint atlasMaxH,
|
||||
jobject vertexBuf) {
|
||||
if (!render || !track || !atlasBuf || !vertexBuf || atlasMaxW <= 0 || atlasMaxH <= 0) return NULL;
|
||||
|
||||
jclass atlasFrameClass = (*env)->FindClass(env, "com/edde746/plezy/libass/AssAtlasFrame");
|
||||
if (!atlasFrameClass) return NULL;
|
||||
jmethodID ctor = (*env)->GetMethodID(env, atlasFrameClass, "<init>", "(IIIII)V");
|
||||
if (!ctor) return NULL;
|
||||
|
||||
const long long t0 = nowMs();
|
||||
int changed;
|
||||
ASS_Image* image = ass_render_frame((ASS_Renderer*)render, (ASS_Track*)track, time, &changed);
|
||||
const long long tAss = nowMs();
|
||||
|
||||
if (changed == 0 || image == NULL) {
|
||||
if (tAss - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, no output)", (long long)time,
|
||||
tAss - t0, changed);
|
||||
}
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
|
||||
}
|
||||
|
||||
uint8_t* atlasPixels = (uint8_t*)(*env)->GetDirectBufferAddress(env, atlasBuf);
|
||||
jlong atlasCap = (*env)->GetDirectBufferCapacity(env, atlasBuf);
|
||||
float* vertices = (float*)(*env)->GetDirectBufferAddress(env, vertexBuf);
|
||||
jlong vertexCap = (*env)->GetDirectBufferCapacity(env, vertexBuf);
|
||||
if (!atlasPixels || !vertices) return NULL;
|
||||
if ((jlong)atlasMaxW * atlasMaxH > atlasCap) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR, LOG_TAG, "atlas buffer smaller than %dx%d (capacity %lld bytes)", atlasMaxW, atlasMaxH,
|
||||
(long long)atlasCap);
|
||||
return NULL;
|
||||
}
|
||||
// 48 floats per quad × 4 bytes = 192 bytes/quad
|
||||
const int maxQuads = (int)(vertexCap / 192);
|
||||
|
||||
int total = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) total++;
|
||||
}
|
||||
if (total == 0) {
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
|
||||
}
|
||||
|
||||
// Pass 1: assign packing slots in height-sorted order so mixed-size frames pack
|
||||
// tight rows. slotX/slotY are keyed by the image's position in the original
|
||||
// list; -1 marks images dropped for capacity.
|
||||
PackItem* items = (PackItem*)malloc(sizeof(PackItem) * (size_t)total);
|
||||
int* slotX = (int*)malloc(sizeof(int) * (size_t)total);
|
||||
int* slotY = (int*)malloc(sizeof(int) * (size_t)total);
|
||||
if (!items || !slotX || !slotY) {
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
return NULL;
|
||||
}
|
||||
int n = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) {
|
||||
items[n].img = img;
|
||||
items[n].idx = n;
|
||||
n++;
|
||||
}
|
||||
}
|
||||
qsort(items, (size_t)n, sizeof(PackItem), comparePackItemsByHeightDesc);
|
||||
|
||||
int cursorX = 0, cursorY = 0, rowH = 0;
|
||||
int truncated = 0;
|
||||
int packedH = 0;
|
||||
int accepted = 0;
|
||||
long long srcPixels = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
ASS_Image* img = items[i].img;
|
||||
srcPixels += (long long)img->w * img->h;
|
||||
int sx = -1, sy = -1;
|
||||
if (img->w <= atlasMaxW && accepted < maxQuads) {
|
||||
int cx = cursorX, cy = cursorY, rh = rowH;
|
||||
if (cx + img->w > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + img->h <= atlasMaxH) {
|
||||
sx = cx;
|
||||
sy = cy;
|
||||
cursorX = cx + img->w;
|
||||
cursorY = cy;
|
||||
rowH = (img->h > rh) ? img->h : rh;
|
||||
if (cy + img->h > packedH) packedH = cy + img->h;
|
||||
accepted++;
|
||||
}
|
||||
}
|
||||
if (sx < 0) truncated++;
|
||||
slotX[items[i].idx] = sx;
|
||||
slotY[items[i].idx] = sy;
|
||||
}
|
||||
|
||||
if (truncated > 0 && (truncationLogCounter++ & 63) == 0) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d images dropped (atlas %dx%d, %d quads max)", truncated,
|
||||
n, atlasMaxW, atlasMaxH, maxQuads);
|
||||
}
|
||||
if (accepted == 0) {
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated);
|
||||
}
|
||||
|
||||
memset(atlasPixels, 0, (size_t)atlasMaxW * packedH);
|
||||
|
||||
// Pass 2: walk the original list (= libass's painter/blend order), copying each
|
||||
// accepted image into its assigned slot and emitting its quad.
|
||||
int qi = 0;
|
||||
int k = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
const int px = slotX[k];
|
||||
const int py = slotY[k];
|
||||
k++;
|
||||
if (px < 0) continue;
|
||||
|
||||
for (int y = 0; y < img->h; y++) {
|
||||
uint8_t* dst = atlasPixels + (size_t)(py + y) * atlasMaxW + px;
|
||||
const uint8_t* src = img->bitmap + (size_t)y * img->stride;
|
||||
memcpy(dst, src, (size_t)img->w);
|
||||
}
|
||||
|
||||
const float x0 = (float)img->dst_x;
|
||||
const float y0 = (float)img->dst_y;
|
||||
const float x1 = x0 + (float)img->w;
|
||||
const float y1 = y0 + (float)img->h;
|
||||
const float u0 = (float)px / (float)atlasMaxW;
|
||||
const float v0 = (float)py / (float)atlasMaxH;
|
||||
const float u1 = (float)(px + img->w) / (float)atlasMaxW;
|
||||
const float v1 = (float)(py + img->h) / (float)atlasMaxH;
|
||||
const unsigned int c = img->color;
|
||||
const float r = (float)((c >> 24) & 0xFFu) / 255.0f;
|
||||
const float g = (float)((c >> 16) & 0xFFu) / 255.0f;
|
||||
const float b = (float)((c >> 8) & 0xFFu) / 255.0f;
|
||||
const float a = (float)(0xFFu - (c & 0xFFu)) / 255.0f;
|
||||
|
||||
float* vx = vertices + (size_t)qi * 48;
|
||||
// 8 floats per vertex: x, y, u, v, r, g, b, a.
|
||||
// Triangle 1: (x0,y0) (x1,y0) (x0,y1)
|
||||
vx[0] = x0;
|
||||
vx[1] = y0;
|
||||
vx[2] = u0;
|
||||
vx[3] = v0;
|
||||
vx[4] = r;
|
||||
vx[5] = g;
|
||||
vx[6] = b;
|
||||
vx[7] = a;
|
||||
vx[8] = x1;
|
||||
vx[9] = y0;
|
||||
vx[10] = u1;
|
||||
vx[11] = v0;
|
||||
vx[12] = r;
|
||||
vx[13] = g;
|
||||
vx[14] = b;
|
||||
vx[15] = a;
|
||||
vx[16] = x0;
|
||||
vx[17] = y1;
|
||||
vx[18] = u0;
|
||||
vx[19] = v1;
|
||||
vx[20] = r;
|
||||
vx[21] = g;
|
||||
vx[22] = b;
|
||||
vx[23] = a;
|
||||
// Triangle 2: (x1,y0) (x1,y1) (x0,y1)
|
||||
vx[24] = x1;
|
||||
vx[25] = y0;
|
||||
vx[26] = u1;
|
||||
vx[27] = v0;
|
||||
vx[28] = r;
|
||||
vx[29] = g;
|
||||
vx[30] = b;
|
||||
vx[31] = a;
|
||||
vx[32] = x1;
|
||||
vx[33] = y1;
|
||||
vx[34] = u1;
|
||||
vx[35] = v1;
|
||||
vx[36] = r;
|
||||
vx[37] = g;
|
||||
vx[38] = b;
|
||||
vx[39] = a;
|
||||
vx[40] = x0;
|
||||
vx[41] = y1;
|
||||
vx[42] = u0;
|
||||
vx[43] = v1;
|
||||
vx[44] = r;
|
||||
vx[45] = g;
|
||||
vx[46] = b;
|
||||
vx[47] = a;
|
||||
|
||||
qi++;
|
||||
}
|
||||
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
|
||||
// Slow-render breakdown: separates libass's own cost (rasterize/blur/shape)
|
||||
// from this function's packing + memcpy, so device logs attribute the time.
|
||||
const long long tEnd = nowMs();
|
||||
if (tEnd - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG,
|
||||
"slow render t=%lldms: total=%lldms ass=%lldms pack+copy=%lldms images=%d srcPx=%lldk atlas=%dx%d quads=%d",
|
||||
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, packedH, qi);
|
||||
}
|
||||
|
||||
// atlasWidth is the full row stride (GLES2 can't upload with stride ≠ width);
|
||||
// atlasHeight is the packed height — the only rows worth uploading.
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, atlasMaxW, packedH, qi, changed, truncated);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
project("asskt")
|
||||
|
||||
# libass headers + libass.so come from the io.github.peerless2012:ass AAR via prefab.
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c)
|
||||
find_package(lib_ass REQUIRED CONFIG)
|
||||
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE
|
||||
lib_ass::ass
|
||||
log)
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class Ass {
|
||||
|
||||
companion object {
|
||||
|
||||
init {
|
||||
System.loadLibrary("asskt")
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssInit(): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssAddFont(ptr: Long, name: String, buffer: ByteArray)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssDeinit(ptr: Long)
|
||||
}
|
||||
|
||||
/** Single lock for all libass calls on this library instance. */
|
||||
val lock = ReentrantLock()
|
||||
|
||||
private var nativeAss: Long = nativeAssInit()
|
||||
|
||||
@Volatile
|
||||
var released = false
|
||||
private set
|
||||
|
||||
private fun <T> create(block: (Long) -> T): T = lock.withLock {
|
||||
check(!released && nativeAss != 0L) { "Ass already released" }
|
||||
block(nativeAss)
|
||||
}
|
||||
|
||||
fun createTrack(): AssTrack = create { AssTrack(it, lock) }
|
||||
|
||||
fun createRender(): AssRender = create { AssRender(it, lock) }
|
||||
|
||||
fun addFont(name: String, buffer: ByteArray) {
|
||||
lock.withLock {
|
||||
if (!released && nativeAss != 0L) nativeAssAddFont(nativeAss, name, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
lock.withLock {
|
||||
if (released) return
|
||||
released = true
|
||||
if (nativeAss != 0L) {
|
||||
nativeAssDeinit(nativeAss)
|
||||
nativeAss = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected fun finalize() {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
/**
|
||||
* Result of a packed-atlas render. The atlas pixel data is stored in the direct ByteBuffer
|
||||
* that was passed into [AssRender.renderFrameAtlas]; the vertex stream is in the other.
|
||||
*
|
||||
* @param atlasWidth atlas row stride in pixels (= the allocated width; 0 when [changed] == 0)
|
||||
* @param atlasHeight packed atlas height in pixels — the rows worth uploading
|
||||
* @param quadCount number of quads; the vertex buffer holds [quadCount] * 6 vertices
|
||||
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
|
||||
* @param truncated images dropped because they exceeded the atlas/vertex capacity;
|
||||
* the frame is incomplete but never stale (> 0 should be rare —
|
||||
* it means even the GL-max-sized atlas couldn't fit the frame)
|
||||
*/
|
||||
class AssAtlasFrame(
|
||||
val atlasWidth: Int,
|
||||
val atlasHeight: Int,
|
||||
val quadCount: Int,
|
||||
val changed: Int,
|
||||
val truncated: Int
|
||||
)
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
|
||||
companion object {
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderInit(ass: Long): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetFontScale(render: Long, scale: Float)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetCacheLimit(render: Long, glyphMax: Int, bitmapMaxSize: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetStorageSize(render: Long, width: Int, height: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetFrameSize(render: Long, width: Int, height: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetMargins(render: Long, top: Int, bottom: Int, left: Int, right: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetUseMargins(render: Long, use: Boolean)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderFrameAtlas(
|
||||
render: Long,
|
||||
track: Long,
|
||||
time: Long,
|
||||
atlasBuf: ByteBuffer,
|
||||
atlasMaxWidth: Int,
|
||||
atlasMaxHeight: Int,
|
||||
vertexBuf: ByteBuffer
|
||||
): AssAtlasFrame?
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderDeinit(render: Long)
|
||||
}
|
||||
|
||||
private var nativeRender: Long = nativeAssRenderInit(nativeAss)
|
||||
|
||||
@Volatile
|
||||
var released = false
|
||||
private set
|
||||
|
||||
private var track: AssTrack? = null
|
||||
|
||||
/**
|
||||
* Bumped on every renderer-state mutation (track, sizes, margins, font scale).
|
||||
* Lets the render-ahead pipeline detect that a speculatively rendered frame was
|
||||
* produced against stale state and must not be presented.
|
||||
*/
|
||||
private val generation = java.util.concurrent.atomic.AtomicInteger(0)
|
||||
|
||||
/** Current renderer-state generation; see [generation]. */
|
||||
val stateGeneration: Int get() = generation.get()
|
||||
|
||||
/** Runs [block] with the native handle under the shared libass lock; no-op once released. */
|
||||
private inline fun withNative(block: (Long) -> Unit) {
|
||||
lock.withLock {
|
||||
if (!released && nativeRender != 0L) block(nativeRender)
|
||||
}
|
||||
}
|
||||
|
||||
fun setTrack(track: AssTrack?) {
|
||||
generation.incrementAndGet()
|
||||
lock.withLock { this.track = track }
|
||||
}
|
||||
|
||||
fun setFontScale(scale: Float) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetFontScale(it, scale) }
|
||||
}
|
||||
|
||||
fun setCacheLimit(glyphMax: Int, bitmapMaxSize: Int) = withNative { nativeAssRenderSetCacheLimit(it, glyphMax, bitmapMaxSize) }
|
||||
|
||||
fun setStorageSize(width: Int, height: Int) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetStorageSize(it, width, height) }
|
||||
}
|
||||
|
||||
fun setFrameSize(width: Int, height: Int) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetFrameSize(it, width, height) }
|
||||
}
|
||||
|
||||
/**
|
||||
* mpv-style frame margins: offsets of the video dst rect within the frame set by
|
||||
* [setFrameSize]. Negative when the video extends beyond the frame (zoomed in / cover).
|
||||
*/
|
||||
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetMargins(it, top, bottom, left, right) }
|
||||
}
|
||||
|
||||
/**
|
||||
* mpv's sub-ass-force-margins: lay out non-positioned events against the full frame
|
||||
* (kept on the visible screen) instead of the video rect between the margins.
|
||||
*/
|
||||
fun setUseMargins(use: Boolean) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetUseMargins(it, use) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a frame into a packed ALPHA_8 texture atlas plus a single vertex stream
|
||||
* ready for `glDrawArrays(GL_TRIANGLES, 0, quadCount * 6)`.
|
||||
*
|
||||
* UVs are normalized against ([atlasMaxW], [atlasMaxH]) — the allocated texture
|
||||
* dims — so the caller can allocate the texture once and `glTexSubImage2D` only
|
||||
* the packed rows. Images that exceed the capacity are dropped and counted in
|
||||
* [AssAtlasFrame.truncated]; the render never fails on content size.
|
||||
*
|
||||
* @param atlasBuf direct ByteBuffer receiving the packed pixels (≥ atlasMaxW × atlasMaxH)
|
||||
* @param atlasMaxW atlas row stride in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param atlasMaxH atlas height in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param vertexBuf direct ByteBuffer receiving the vertex stream (192 bytes per quad)
|
||||
*/
|
||||
/** How long the most recent [renderFrameAtlas] waited to acquire the shared
|
||||
* libass lock (contended by track dialogue/font feeding), in milliseconds. */
|
||||
@Volatile
|
||||
var lastLockWaitMs: Long = 0
|
||||
private set
|
||||
|
||||
fun renderFrameAtlas(
|
||||
time: Long,
|
||||
atlasBuf: ByteBuffer,
|
||||
atlasMaxW: Int,
|
||||
atlasMaxH: Int,
|
||||
vertexBuf: ByteBuffer
|
||||
): AssAtlasFrame? {
|
||||
val tQueue = System.nanoTime()
|
||||
lock.withLock {
|
||||
lastLockWaitMs = (System.nanoTime() - tQueue) / 1_000_000
|
||||
if (released || nativeRender == 0L) return null
|
||||
val t = track ?: return null
|
||||
if (t.released || t.nativeAssTrack == 0L) return null
|
||||
return nativeAssRenderFrameAtlas(nativeRender, t.nativeAssTrack, time, atlasBuf, atlasMaxW, atlasMaxH, vertexBuf)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
lock.withLock {
|
||||
if (released) return
|
||||
released = true
|
||||
track = null
|
||||
if (nativeRender != 0L) {
|
||||
nativeAssRenderDeinit(nativeRender)
|
||||
nativeRender = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected fun finalize() {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class AssTrack(private val ass: Long, private val lock: ReentrantLock) {
|
||||
|
||||
companion object {
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackInit(track: Long): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackReadBuffer(track: Long, byteArray: ByteArray, offset: Int, length: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackReadChunk(track: Long, start: Long, duration: Long, byteArray: ByteArray, offset: Int, length: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackDeinit(track: Long)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackNextEventStart(track: Long, afterMs: Long): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackNextEventChange(track: Long, afterMs: Long): Long
|
||||
}
|
||||
|
||||
var nativeAssTrack = nativeAssTrackInit(ass)
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var released = false
|
||||
private set
|
||||
|
||||
/** Runs [block] with the native handle under the shared libass lock; no-op once released. */
|
||||
private inline fun withNative(block: (Long) -> Unit) {
|
||||
lock.withLock {
|
||||
if (!released && nativeAssTrack != 0L) block(nativeAssTrack)
|
||||
}
|
||||
}
|
||||
|
||||
fun readBuffer(array: ByteArray, offset: Int = 0, length: Int = array.size) = withNative { nativeAssTrackReadBuffer(it, array, offset, length) }
|
||||
|
||||
fun readChunk(start: Long, duration: Long, array: ByteArray, offset: Int = 0, length: Int = array.size) = withNative { nativeAssTrackReadChunk(it, start, duration, array, offset, length) }
|
||||
|
||||
/** Earliest event start strictly after [afterMs], or -1 if none (yet). */
|
||||
fun nextEventStartMs(afterMs: Long): Long {
|
||||
lock.withLock {
|
||||
if (released || nativeAssTrack == 0L) return -1
|
||||
return nativeAssTrackNextEventStart(nativeAssTrack, afterMs)
|
||||
}
|
||||
}
|
||||
|
||||
/** Earliest event start OR end strictly after [afterMs], or -1 if none (yet). */
|
||||
fun nextEventChangeMs(afterMs: Long): Long {
|
||||
lock.withLock {
|
||||
if (released || nativeAssTrack == 0L) return -1
|
||||
return nativeAssTrackNextEventChange(nativeAssTrack, afterMs)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
lock.withLock {
|
||||
if (released) return
|
||||
released = true
|
||||
if (nativeAssTrack != 0L) {
|
||||
nativeAssTrackDeinit(nativeAssTrack)
|
||||
nativeAssTrack = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected fun finalize() {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package com.edde746.plezy.libass.media
|
||||
|
||||
import android.util.Log
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.MimeTypes.TEXT_SSA
|
||||
import androidx.media3.common.Player.Listener
|
||||
import androidx.media3.common.Tracks
|
||||
import androidx.media3.common.VideoSize
|
||||
import androidx.media3.common.util.Size
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.video.VideoFrameMetadataListener
|
||||
import com.edde746.plezy.libass.Ass
|
||||
import com.edde746.plezy.libass.AssRender
|
||||
import com.edde746.plezy.libass.AssTrack
|
||||
import com.edde746.plezy.libass.media.parser.AssHeaderParser
|
||||
|
||||
/**
|
||||
* Handles ASS subtitle rendering and integration with ExoPlayer.
|
||||
*
|
||||
* This class listens to ExoPlayer events and manages the creation, selection, and rendering of ASS
|
||||
* subtitle tracks. Rendering always happens on a GL overlay surface (atlas pipeline) — the
|
||||
* libass frame is the overlay surface, not the video.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class AssHandler(
|
||||
val config: AssHandlerConfig = AssHandlerConfig()
|
||||
) : Listener {
|
||||
|
||||
/** The ASS instance used for creating tracks and renderers. This is lazy to avoid loading
|
||||
* libass if the played media does not have ASS tracks. */
|
||||
private val assDelegate = lazy { Ass() }
|
||||
val ass by assDelegate
|
||||
|
||||
/** The current ASS renderer. It's created as soon as a ASS track is detected. */
|
||||
var render: AssRender? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* AssRender changed callback
|
||||
*/
|
||||
var renderCallback: ((AssRender?) -> Unit)? = null
|
||||
|
||||
/** The currently selected ASS track. */
|
||||
var track: AssTrack? = null
|
||||
private set
|
||||
|
||||
/** The available ASS tracks in the current media. */
|
||||
private val availableTracks = mutableMapOf<String, AssTrack>()
|
||||
|
||||
/** Fonts encountered before any ASS track was created. Flushed in [createTrack]. */
|
||||
private val pendingFonts = mutableListOf<Pair<String, ByteArray>>()
|
||||
|
||||
/** The size of the video track. */
|
||||
var videoSize = Size.ZERO
|
||||
private set
|
||||
|
||||
/** The size of the surface on which subtitles are rendered. */
|
||||
var surfaceSize = Size.ZERO
|
||||
private set
|
||||
|
||||
/**
|
||||
* True once an overlay widget reported its surface size via [setOverlaySurfaceSize].
|
||||
* From then on the Player.Listener surface size (= the video output surface, which
|
||||
* may differ from the subtitle overlay once the overlay is parented elsewhere) is
|
||||
* ignored as a frame-size source.
|
||||
*/
|
||||
private var overlaySizeFromWidget = false
|
||||
|
||||
/** mpv-style margins of the video rect within the frame: top, bottom, left, right. */
|
||||
private var margins: IntArray? = null
|
||||
|
||||
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
|
||||
private var useMargins = false
|
||||
|
||||
/**
|
||||
* Per-video-frame callback. Fired by ExoPlayer just before MediaCodec releases the frame
|
||||
* to the output surface. Carries the exact PTS of the frame and the System.nanoTime()
|
||||
* domain target release time, so subtitle renderers can align composition to the same
|
||||
* display vsync as the video.
|
||||
*
|
||||
* - [presentationTimeUs] is track-relative microseconds matching the subtitle track's PTS.
|
||||
* - [releaseTimeNs] may be [androidx.media3.common.C.TIME_UNSET] in rare paths.
|
||||
*
|
||||
* Invoked on the playback thread.
|
||||
*/
|
||||
var videoFrameCallback: ((presentationTimeUs: Long, releaseTimeNs: Long) -> Unit)? = null
|
||||
|
||||
private val videoFrameMetadataListener = VideoFrameMetadataListener { pts, releaseNs, _, _ ->
|
||||
videoFrameCallback?.invoke(pts, releaseNs)
|
||||
}
|
||||
|
||||
private var player: ExoPlayer? = null
|
||||
|
||||
/** The current selected ass format. */
|
||||
private var format: Format? = null
|
||||
|
||||
/**
|
||||
* Initializes the handler with the provided ExoPlayer instance.
|
||||
* @param player The ExoPlayer instance to attach to.
|
||||
*/
|
||||
fun init(player: ExoPlayer) {
|
||||
this.player = player
|
||||
player.addListener(this)
|
||||
player.setVideoFrameMetadataListener(videoFrameMetadataListener)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles transitions between media items in the player and resets everything to the initial
|
||||
* state.
|
||||
*/
|
||||
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
||||
super.onMediaItemTransition(mediaItem, reason)
|
||||
Log.i("AssHandler", "onMediaItemTransition: item = $mediaItem, reason = $reason")
|
||||
resetMediaState(releaseNative = true)
|
||||
}
|
||||
|
||||
private fun resetMediaState(releaseNative: Boolean) {
|
||||
val oldRender = render
|
||||
val oldTracks = availableTracks.values.toList()
|
||||
|
||||
render = null
|
||||
track = null
|
||||
format = null
|
||||
availableTracks.clear()
|
||||
pendingFonts.clear()
|
||||
videoSize = Size.ZERO
|
||||
renderCallback?.invoke(null)
|
||||
|
||||
if (releaseNative) {
|
||||
oldRender?.release()
|
||||
oldTracks.forEach { it.release() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles changes to the tracks available in the current media.
|
||||
* Configures the selected ASS track if available.
|
||||
* @param tracks The selected tracks.
|
||||
*/
|
||||
override fun onTracksChanged(tracks: Tracks) {
|
||||
Log.i("AssHandler", "onTracksChanged $tracks")
|
||||
|
||||
val selectedVideoTrack = getSelectedVideoTrack(tracks)
|
||||
if (selectedVideoTrack != null) {
|
||||
setVideoSize(selectedVideoTrack.width, selectedVideoTrack.height)
|
||||
}
|
||||
|
||||
format = getSelectedAssTrack(tracks)
|
||||
if (format == null) {
|
||||
Log.i("AssHandler", "subtitle track disabled")
|
||||
track = null
|
||||
render?.setTrack(null)
|
||||
return
|
||||
}
|
||||
|
||||
updateTrack()
|
||||
}
|
||||
|
||||
private fun updateTrack() {
|
||||
val track = availableTracks.firstNotNullOfOrNull {
|
||||
// When media without external subtitles, format id will not change.
|
||||
// When media with external subtitles, format will become like 1:1 .
|
||||
// So to compat both situation, we extract the actual id after the colon.
|
||||
if (format?.id?.substringAfter(":") == it.key) {
|
||||
it.value
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
if (track == null || this.track == track) return
|
||||
|
||||
Log.i("AssHandler", "subtitle track changed to $format")
|
||||
this.track = track
|
||||
val render = requireNotNull(render)
|
||||
applyRenderState(render)
|
||||
render.setTrack(track)
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)applies sizing and margin state to [render]. Called whenever a render is
|
||||
* (re)created or the selected track changes, so renderer state survives both.
|
||||
*/
|
||||
private fun applyRenderState(render: AssRender) {
|
||||
if (videoSize.isValid) render.setStorageSize(videoSize.width, videoSize.height)
|
||||
when {
|
||||
surfaceSize.isValid -> render.setFrameSize(surfaceSize.width, surfaceSize.height)
|
||||
// Fallback frame until the overlay surface reports its size.
|
||||
videoSize.isValid -> render.setFrameSize(videoSize.width, videoSize.height)
|
||||
}
|
||||
margins?.let { m -> render.setMargins(m[0], m[1], m[2], m[3]) }
|
||||
render.setUseMargins(useMargins)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles changes to the surface size for video playback.
|
||||
* Notifies the callback if the size has changed.
|
||||
* @param width The new width of the surface.
|
||||
* @param height The new height of the surface.
|
||||
*/
|
||||
override fun onSurfaceSizeChanged(width: Int, height: Int) {
|
||||
super.onSurfaceSizeChanged(width, height)
|
||||
Log.i("AssHandler", "onSurfaceSizeChanged: width = $width, height = $height")
|
||||
// The video output surface is only a frame-size proxy until an overlay widget
|
||||
// reports its own size — they diverge when the overlay isn't video-rect-sized.
|
||||
if (overlaySizeFromWidget) return
|
||||
if (surfaceSize.width == width && surfaceSize.height == height) return
|
||||
surfaceSize = Size(width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports the subtitle overlay widget's actual surface size — the authoritative
|
||||
* libass frame size for OVERLAY render types.
|
||||
*/
|
||||
fun setOverlaySurfaceSize(width: Int, height: Int) {
|
||||
overlaySizeFromWidget = true
|
||||
if (surfaceSize.width == width && surfaceSize.height == height) return
|
||||
Log.i("AssHandler", "setOverlaySurfaceSize: width = $width, height = $height")
|
||||
surfaceSize = Size(width, height)
|
||||
render?.setFrameSize(width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets mpv-style frame margins: the offsets of the video dst rect within the libass
|
||||
* frame ([setOverlaySurfaceSize]); negative when the video extends beyond the frame.
|
||||
* Applied to the current render and re-applied whenever a render is (re)created.
|
||||
*/
|
||||
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
|
||||
margins = intArrayOf(top, bottom, left, right)
|
||||
render?.setMargins(top, bottom, left, right)
|
||||
}
|
||||
|
||||
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
|
||||
fun setUseMargins(use: Boolean) {
|
||||
useMargins = use
|
||||
render?.setUseMargins(use)
|
||||
}
|
||||
|
||||
override fun onVideoSizeChanged(videoSize: VideoSize) {
|
||||
super.onVideoSizeChanged(videoSize)
|
||||
this.videoSize = Size(videoSize.width, videoSize.height)
|
||||
Log.i("AssHandler", "onVideoSizeChanged: width = ${videoSize.width}, height = ${videoSize.height}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the video size for the ASS renderer. Called as soon as the video size is known in
|
||||
* order to properly render subtitles.
|
||||
* @param width The width of the video.
|
||||
* @param height The height of the video.
|
||||
*/
|
||||
fun setVideoSize(width: Int, height: Int) {
|
||||
Log.i("AssHandler", "setVideoSize: width = $width, height = $height")
|
||||
videoSize = Size(width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the current media has ASS tracks, false otherwise.
|
||||
*/
|
||||
fun hasTracks(): Boolean = availableTracks.isNotEmpty()
|
||||
|
||||
/**
|
||||
* Adds a font to the ASS library. If no tracks have been created yet, the font is buffered
|
||||
* and will be added when the first track is created via [createTrack].
|
||||
*/
|
||||
@Synchronized
|
||||
fun addFont(name: String, data: ByteArray) {
|
||||
if (hasTracks()) {
|
||||
ass.addFont(name, data)
|
||||
} else {
|
||||
pendingFonts.add(name to data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ASS track from the given format and saves it in the [availableTracks].
|
||||
* The renderer and libass are also created if needed.
|
||||
* @param format The format of the ASS track.
|
||||
* @return The created ASS track.
|
||||
*/
|
||||
@Synchronized
|
||||
fun createTrack(format: Format): AssTrack {
|
||||
Log.i("AssHandler", "createTrack: format = $format")
|
||||
// Ensure the renderer is created before creating tracks.
|
||||
createRenderIfNeeded()
|
||||
|
||||
// Flush any fonts that were buffered before the first track was created.
|
||||
if (pendingFonts.isNotEmpty()) {
|
||||
for ((name, data) in pendingFonts) {
|
||||
ass.addFont(name, data)
|
||||
}
|
||||
pendingFonts.clear()
|
||||
}
|
||||
|
||||
val track = ass.createTrack()
|
||||
if (format.initializationData.size > 0) {
|
||||
val header = AssHeaderParser.parse(format)
|
||||
track.readBuffer(header)
|
||||
}
|
||||
availableTracks[format.id!!] = track
|
||||
|
||||
updateTrack()
|
||||
|
||||
return track
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the ASS renderer is created if it does not already exist.
|
||||
*/
|
||||
private fun createRenderIfNeeded() {
|
||||
if (render != null) return
|
||||
Log.i("AssHandler", "createRender (cacheSize: ${config.cacheSize}MB, glyphSize: ${config.glyphSize})")
|
||||
render = ass.createRender().also { render ->
|
||||
render.setCacheLimit(config.glyphSize, config.cacheSize)
|
||||
applyRenderState(render)
|
||||
}
|
||||
renderCallback?.invoke(render)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a dialogue into the track of the given [trackId].
|
||||
* Thread-safe: AssTrack.readChunk internally acquires the shared libass lock.
|
||||
*/
|
||||
fun readTrackDialogue(
|
||||
trackId: String?,
|
||||
start: Long,
|
||||
duration: Long,
|
||||
data: ByteArray,
|
||||
offset: Int = 0,
|
||||
length: Int = data.size
|
||||
) {
|
||||
val t = availableTracks[trackId] ?: return
|
||||
t.readChunk(start, duration, data, offset, length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the selected video track, if any.
|
||||
*/
|
||||
private fun getSelectedVideoTrack(tracks: Tracks): Format? = tracks.groups.find { group ->
|
||||
if (group.isSelected) {
|
||||
(0 until group.length).any { index ->
|
||||
val track = group.getTrackFormat(index)
|
||||
MimeTypes.isVideo(track.sampleMimeType)
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}?.getTrackFormat(0)
|
||||
|
||||
/**
|
||||
* Retrieves the ID of the selected ASS track, if any.
|
||||
* @param tracks The selected tracks.
|
||||
* @return The ID of the selected ASS track, or null if none.
|
||||
*/
|
||||
private fun getSelectedAssTrack(tracks: Tracks): Format? = tracks.groups.find { group ->
|
||||
if (group.isSelected) {
|
||||
(0 until group.length).any { index ->
|
||||
val track = group.getTrackFormat(index)
|
||||
track.sampleMimeType == TEXT_SSA || track.codecs == TEXT_SSA
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}?.getTrackFormat(0)
|
||||
|
||||
/**
|
||||
* Releases all native resources held by this handler.
|
||||
*/
|
||||
fun release() {
|
||||
videoFrameCallback = null
|
||||
player?.clearVideoFrameMetadataListener(videoFrameMetadataListener)
|
||||
player = null
|
||||
resetMediaState(releaseNative = true)
|
||||
if (assDelegate.isInitialized()) {
|
||||
ass.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the size is valid (both width and height are greater than 0).
|
||||
*/
|
||||
private val Size.isValid
|
||||
get() = width > 0 && height > 0
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.edde746.plezy.libass.media
|
||||
|
||||
data class AssHandlerConfig(
|
||||
val glyphSize: Int = 10000,
|
||||
val cacheSize: Int = 128
|
||||
)
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.edde746.plezy.libass.media.extractor
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.mkv.EbmlProcessor
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.text.AssSubtitleExtractorOutput
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
open class AssMatroskaExtractor(
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
private val assHandler: AssHandler,
|
||||
flags: Int = 0
|
||||
) : MatroskaExtractor(subtitleParserFactory, flags) {
|
||||
|
||||
private var currentAttachmentName: String? = null
|
||||
private var currentAttachmentMime: String? = null
|
||||
|
||||
internal val subtitleSample = subtitleSampleField.get(this) as ParsableByteArray
|
||||
|
||||
override fun getElementType(id: Int): Int = when (id) {
|
||||
ID_ATTACHMENTS -> EbmlProcessor.ELEMENT_TYPE_MASTER
|
||||
ID_ATTACHED_FILE -> EbmlProcessor.ELEMENT_TYPE_MASTER
|
||||
ID_FILE_NAME -> EbmlProcessor.ELEMENT_TYPE_STRING
|
||||
ID_FILE_MIME_TYPE -> EbmlProcessor.ELEMENT_TYPE_STRING
|
||||
ID_FILE_DATA -> EbmlProcessor.ELEMENT_TYPE_BINARY
|
||||
else -> super.getElementType(id)
|
||||
}
|
||||
|
||||
override fun isLevel1Element(id: Int): Boolean = super.isLevel1Element(id) || id == ID_ATTACHMENTS
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
when (id) {
|
||||
ID_EBML -> {
|
||||
val currentExtractor = extractorOutput.get(this) as ExtractorOutput
|
||||
if (currentExtractor !is AssSubtitleExtractorOutput) {
|
||||
extractorOutput.set(
|
||||
this,
|
||||
AssSubtitleExtractorOutput(currentExtractor, assHandler, this)
|
||||
)
|
||||
}
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
}
|
||||
ID_ATTACHED_FILE -> clearAttachment()
|
||||
else -> super.startMasterElement(id, contentPosition, contentSize)
|
||||
}
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
when (id) {
|
||||
ID_VIDEO -> {
|
||||
// We need to get the video dimensions very early
|
||||
val track = getCurrentTrack(id)
|
||||
assHandler.setVideoSize(track.width, track.height)
|
||||
super.endMasterElement(id)
|
||||
}
|
||||
ID_ATTACHED_FILE -> clearAttachment()
|
||||
else -> super.endMasterElement(id)
|
||||
}
|
||||
}
|
||||
|
||||
override fun stringElement(id: Int, value: String) {
|
||||
when (id) {
|
||||
ID_FILE_NAME -> currentAttachmentName = value
|
||||
ID_FILE_MIME_TYPE -> currentAttachmentMime = value
|
||||
else -> super.stringElement(id, value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
|
||||
when (id) {
|
||||
ID_FILE_DATA -> {
|
||||
val attachmentName = requireNotNull(currentAttachmentName)
|
||||
val attachmentMime = requireNotNull(currentAttachmentMime)
|
||||
|
||||
if (attachmentMime in fontMimeTypes) {
|
||||
val data = ByteArray(contentSize)
|
||||
input.readFully(data, 0, contentSize)
|
||||
assHandler.addFont(attachmentName, data)
|
||||
} else {
|
||||
input.skipFully(contentSize)
|
||||
}
|
||||
}
|
||||
else -> super.binaryElement(id, contentSize, input)
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearAttachment() {
|
||||
currentAttachmentName = null
|
||||
currentAttachmentMime = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ID_EBML = 0x1A45DFA3
|
||||
const val ID_VIDEO = 0xE0
|
||||
const val ID_ATTACHMENTS = 0x1941A469
|
||||
const val ID_ATTACHED_FILE = 0x61A7
|
||||
const val ID_FILE_NAME = 0x466E
|
||||
const val ID_FILE_MIME_TYPE = 0x4660
|
||||
const val ID_FILE_DATA = 0x465C
|
||||
|
||||
val fontMimeTypes = listOf(
|
||||
"font/ttf",
|
||||
"font/otf",
|
||||
"font/sfnt",
|
||||
"font/woff",
|
||||
"font/woff2",
|
||||
"application/font-sfnt",
|
||||
"application/font-woff",
|
||||
"application/x-truetype-font",
|
||||
"application/vnd.ms-opentype",
|
||||
"application/x-font-ttf"
|
||||
)
|
||||
|
||||
val extractorOutput = MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
val subtitleSampleField = MatroskaExtractor::class.java.getDeclaredField("subtitleSample").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.Consumer
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.text.CuesWithTiming
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.AssTrack
|
||||
|
||||
/**
|
||||
* Parser for full (non-embedded) ASS documents, e.g. external sidecar files.
|
||||
* Feeds the whole document into the libass track; rendering happens on the
|
||||
* overlay surface, so no Media3 cues are emitted.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssFullSubtitleParser(private val track: AssTrack) : SubtitleParser {
|
||||
|
||||
override fun parse(
|
||||
data: ByteArray,
|
||||
offset: Int,
|
||||
length: Int,
|
||||
outputOptions: SubtitleParser.OutputOptions,
|
||||
output: Consumer<CuesWithTiming>
|
||||
) {
|
||||
track.readBuffer(data, offset, length)
|
||||
}
|
||||
|
||||
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
object AssHeaderParser {
|
||||
|
||||
private const val ASS_EVENTS = "[Events]\n" +
|
||||
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
|
||||
|
||||
/**
|
||||
* Fix some ass header with error end.
|
||||
* https://github.com/jellyfin/jellyfin-ffmpeg/issues/506
|
||||
*/
|
||||
private fun fixAssHeaderIfNeed(buffer: ByteArray): ByteArray = if (buffer[buffer.size - 1] != 0.toByte()) {
|
||||
// validate ass header
|
||||
buffer
|
||||
} else {
|
||||
// remote the last null character and append the events tag
|
||||
(String(buffer, 0, buffer.size - 1) + "\n" + ASS_EVENTS).toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the headers from the initialization data of the given [format]. The original
|
||||
* headers are preserved (duplication checks are handled by libass).
|
||||
*/
|
||||
fun parse(format: Format): ByteArray = fixAssHeaderIfNeed(format.initializationData[1])
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.Consumer
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.text.CuesWithTiming
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
|
||||
/**
|
||||
* No operation subtitle parser.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssNoOpSubtitleParser : SubtitleParser {
|
||||
override fun parse(
|
||||
p0: ByteArray,
|
||||
p1: Int,
|
||||
p2: Int,
|
||||
p3: SubtitleParser.OutputOptions,
|
||||
p4: Consumer<CuesWithTiming>
|
||||
) {
|
||||
}
|
||||
|
||||
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
|
||||
@UnstableApi
|
||||
class AssSubtitleParserFactory(private val assHandler: AssHandler) : SubtitleParser.Factory {
|
||||
|
||||
private val defaultSubtitleParserFactory = DefaultSubtitleParserFactory()
|
||||
|
||||
override fun supportsFormat(format: Format): Boolean = defaultSubtitleParserFactory.supportsFormat(format)
|
||||
|
||||
override fun getCueReplacementBehavior(format: Format): Int = defaultSubtitleParserFactory.getCueReplacementBehavior(format)
|
||||
|
||||
override fun create(format: Format): SubtitleParser = if (format.sampleMimeType == MimeTypes.TEXT_SSA) {
|
||||
val embeddedSubtitles = MimeTypes.VIDEO_MATROSKA
|
||||
.contentEquals(format.containerMimeType)
|
||||
val track = assHandler.createTrack(format)
|
||||
if (embeddedSubtitles) {
|
||||
// Embedded dialogue lines reach libass via AssTrackOutput; nothing to parse here.
|
||||
AssNoOpSubtitleParser()
|
||||
} else {
|
||||
AssFullSubtitleParser(track)
|
||||
}
|
||||
} else {
|
||||
defaultSubtitleParserFactory.create(format)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.edde746.plezy.libass.media.text
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
|
||||
/**
|
||||
* This class is only used by the overlay renderer. It's needed to get the start time of the subtitles.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssSubtitleExtractorOutput(
|
||||
private val delegate: ExtractorOutput,
|
||||
private val assHandler: AssHandler,
|
||||
private val extractor: AssMatroskaExtractor
|
||||
) : ExtractorOutput by delegate {
|
||||
override fun track(id: Int, type: Int): TrackOutput = if (type == C.TRACK_TYPE_TEXT) {
|
||||
// We can't know at this time if the subtitle track is ASS or other format, so we wrap
|
||||
// every subtitle track
|
||||
AssTrackOutput(delegate.track(id, type), assHandler, extractor)
|
||||
} else {
|
||||
delegate.track(id, type)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.edde746.plezy.libass.media.text
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.common.util.Util
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
import java.util.regex.Pattern
|
||||
|
||||
/**
|
||||
* This class is only used by the overlay renderer. It's needed to get the start time of the subtitles.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val assHandler: AssHandler,
|
||||
private val extractor: AssMatroskaExtractor
|
||||
) : TrackOutput by delegate {
|
||||
|
||||
private var isAss = false
|
||||
|
||||
private var trackId: String? = null
|
||||
|
||||
override fun format(format: Format) {
|
||||
if (format.sampleMimeType == MimeTypes.TEXT_SSA || format.codecs == MimeTypes.TEXT_SSA) {
|
||||
isAss = true
|
||||
trackId = format.id
|
||||
}
|
||||
delegate.format(format)
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (isAss && timeUs.isValidTs) {
|
||||
val sample = extractor.subtitleSample
|
||||
val endIndex = findTokenIndex(sample.data, 1)
|
||||
val lineIndex = findTokenIndex(sample.data, 2)
|
||||
|
||||
val rawDuration = sample.data.decodeToString(endIndex, lineIndex - 1)
|
||||
val durationUs = parseTimecodeUs(rawDuration)
|
||||
|
||||
assHandler.readTrackDialogue(
|
||||
trackId = trackId,
|
||||
start = timeUs / 1000,
|
||||
duration = durationUs / 1000,
|
||||
data = sample.data,
|
||||
offset = lineIndex,
|
||||
length = sample.limit() - lineIndex
|
||||
)
|
||||
}
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
}
|
||||
|
||||
private fun parseTimecodeUs(timeString: String): Long {
|
||||
val matcher = SSA_TIMECODE_PATTERN.matcher(timeString.trim { it <= ' ' })
|
||||
if (!matcher.matches()) {
|
||||
return C.TIME_UNSET
|
||||
}
|
||||
var timestampUs =
|
||||
Util.castNonNull(matcher.group(1)).toLong() * 60 * 60 * C.MICROS_PER_SECOND
|
||||
timestampUs += Util.castNonNull(matcher.group(2)).toLong() * 60 * C.MICROS_PER_SECOND
|
||||
timestampUs += Util.castNonNull(matcher.group(3)).toLong() * C.MICROS_PER_SECOND
|
||||
timestampUs += Util.castNonNull(matcher.group(4)).toLong() * 10000
|
||||
return timestampUs
|
||||
}
|
||||
|
||||
private fun findTokenIndex(array: ByteArray, tokenNumber: Int): Int {
|
||||
if (tokenNumber == 0) return 0
|
||||
var tokensFound = 0
|
||||
array.forEachIndexed { index, byte ->
|
||||
if (byte == COMMA && ++tokensFound == tokenNumber) {
|
||||
return index + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
private val Long.isValidTs
|
||||
get() = this != C.TIME_UNSET
|
||||
|
||||
private companion object {
|
||||
val SSA_TIMECODE_PATTERN: Pattern =
|
||||
Pattern.compile("""(?:(\d+):)?(\d+):(\d+)[:.](\d+)""")
|
||||
|
||||
const val COMMA = ','.code.toByte()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,991 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import android.opengl.EGL14
|
||||
import android.opengl.EGLContext
|
||||
import android.opengl.EGLDisplay
|
||||
import android.opengl.EGLExt
|
||||
import android.opengl.EGLSurface
|
||||
import android.opengl.GLES20
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.util.GlProgram
|
||||
import androidx.media3.common.util.GlUtil
|
||||
import androidx.media3.common.util.Size
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* Atlas-rendering pipeline behind [AssSubtitleSurfaceView].
|
||||
* Runs libass on its own [HandlerThread] into a packed
|
||||
* ALPHA_8 texture atlas plus a single vertex stream, and a GL thread that uploads
|
||||
* both and issues one `glDrawArrays` per frame. Each swap is pinned to the video's
|
||||
* target release time via [EGLExt.eglPresentationTimeANDROID]: SurfaceFlinger holds
|
||||
* the buffer and composes it on the same vsync as the corresponding video frame.
|
||||
*/
|
||||
@UnstableApi
|
||||
internal object AssAtlasPipelineConfig {
|
||||
/** Flip to `true` for `adb logcat -s AssSurfaceGlThread:D AssLibassThread:D` traces. */
|
||||
internal const val TIMING_LOGS = false
|
||||
|
||||
/** Fallback atlas row width when GL caps are unknown (EGL init failed/slow). */
|
||||
internal const val FALLBACK_ATLAS_W = 2048
|
||||
|
||||
/** Fallback atlas height; 2048 × 4096 = 8 MB matches the long-proven default. */
|
||||
internal const val FALLBACK_ATLAS_H = 4096
|
||||
|
||||
/**
|
||||
* Pixel budget per atlas slot once GL caps are known: 4096×4096 or 2048×8192
|
||||
* (16 MB ALPHA_8). Sized so heavy typesetting (full-screen gradients/blurs)
|
||||
* fits where the old fixed 2048×4096 overflowed and dropped frames.
|
||||
*/
|
||||
internal const val ATLAS_PIXEL_BUDGET = 16 * 1024 * 1024
|
||||
|
||||
/** Preallocated vertex-stream capacity (192 bytes × 16384 = 3 MB per buffer). */
|
||||
internal const val MAX_QUADS = 16384
|
||||
|
||||
/** Must match the byte layout produced by `nativeAssRenderFrameAtlas` in AssKt.c. */
|
||||
internal const val BYTES_PER_VERTEX = 32
|
||||
internal const val BYTES_PER_QUAD = BYTES_PER_VERTEX * 6
|
||||
|
||||
/**
|
||||
* Kill switch for speculative render-ahead (see [SpecRenderEngine]) and the
|
||||
* event prefetch. With it off (or on low-RAM devices, which stay at 2 slots)
|
||||
* every request renders on-demand inside the video frame's release deadline —
|
||||
* the pre-speculation behavior.
|
||||
*
|
||||
* Only pays off when typical changed renders fit the speculation coverage
|
||||
* window (~frame interval + release budget): with the un-optimized (-O0)
|
||||
* native core's 90ms+ renders it could only add overhead; with the -O3/NEON
|
||||
* core's ~35-50ms renders it converts near-misses into on-time latches.
|
||||
*/
|
||||
internal const val SPECULATION_ENABLED = true
|
||||
}
|
||||
|
||||
/** Payload handed from the libass worker to the GL thread. */
|
||||
internal class AtlasPayload(
|
||||
val slotIndex: Int,
|
||||
val atlasBuf: ByteBuffer,
|
||||
val vertexBuf: ByteBuffer,
|
||||
var frame: AssAtlasFrame,
|
||||
var presentationTimeUs: Long,
|
||||
var releaseTimeNs: Long,
|
||||
/** Bumped on every content-changing render; lets the GL thread tell "same slot,
|
||||
* new content" apart from "same slot, same content" when deciding to re-upload. */
|
||||
var contentSeq: Long = 0L
|
||||
)
|
||||
|
||||
/** Payload slots plus the atlas dims their buffers were sized for. */
|
||||
internal class AtlasSlots(
|
||||
val payloads: Array<AtlasPayload>,
|
||||
val atlasW: Int,
|
||||
val atlasH: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* Owns both the libass worker and the GL thread. The two talk via a single-slot
|
||||
* atomic — a newer payload always replaces a pending one so the GL thread never
|
||||
* falls behind.
|
||||
*/
|
||||
@UnstableApi
|
||||
internal class AssAtlasPipeline(
|
||||
surface: Surface,
|
||||
width: Int,
|
||||
height: Int,
|
||||
assHandler: AssHandler,
|
||||
lowRamDevice: Boolean = false
|
||||
) {
|
||||
private val surfaceWidth = width
|
||||
private val surfaceHeight = height
|
||||
|
||||
// 3 slots give the render-ahead engine a writable target while one slot is
|
||||
// posted and another is in GL's hands; low-RAM devices stay at 2 slots with
|
||||
// speculation off (the legacy on-demand behavior, ~19 MB less in buffers).
|
||||
private val slotCount = if (lowRamDevice) 2 else 3
|
||||
private val speculationEnabled = AssAtlasPipelineConfig.SPECULATION_ENABLED && slotCount >= 3
|
||||
|
||||
// Atlas dims, resolved exactly once (first-wins): normally by the GL thread from
|
||||
// GL_MAX_TEXTURE_SIZE right after EGL init; by the libass thread's 1 s fallback
|
||||
// if GL never comes up. Both threads then agree on the dims, which matters
|
||||
// because the C side bakes UV denominators = these dims into the vertex stream
|
||||
// and the GL side allocates the texture once at these dims.
|
||||
private val dimsResolved = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
private val dimsLatch = java.util.concurrent.CountDownLatch(1)
|
||||
|
||||
@Volatile private var atlasW = 0
|
||||
|
||||
@Volatile private var atlasH = 0
|
||||
|
||||
private fun resolveAtlasDims(maxTextureSize: Int): Pair<Int, Int> {
|
||||
if (dimsResolved.compareAndSet(false, true)) {
|
||||
if (maxTextureSize < 4096) {
|
||||
// Query failed (or an ancient GPU): keep the long-proven fixed size.
|
||||
atlasW = AssAtlasPipelineConfig.FALLBACK_ATLAS_W
|
||||
atlasH = AssAtlasPipelineConfig.FALLBACK_ATLAS_H
|
||||
} else {
|
||||
val w = if (surfaceWidth > 2048) 4096 else 2048
|
||||
atlasW = w
|
||||
atlasH = minOf(maxTextureSize, AssAtlasPipelineConfig.ATLAS_PIXEL_BUDGET / w)
|
||||
}
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d("AssAtlasPipeline", "atlas dims ${atlasW}x$atlasH (glMaxTexture=$maxTextureSize)")
|
||||
}
|
||||
dimsLatch.countDown()
|
||||
}
|
||||
return atlasW to atlasH
|
||||
}
|
||||
|
||||
// Lazily allocated on the libass thread once atlas dims are known; ~19 MB of
|
||||
// direct buffers per slot at the full budget, so don't pay it before the
|
||||
// first actual render. Confined to the libass thread after creation.
|
||||
private var slots: AtlasSlots? = null
|
||||
|
||||
private fun acquireSlots(): AtlasSlots {
|
||||
slots?.let { return it }
|
||||
if (!dimsLatch.await(1, java.util.concurrent.TimeUnit.SECONDS)) {
|
||||
resolveAtlasDims(0) // first-wins: no-op if the GL thread resolved meanwhile
|
||||
}
|
||||
val w = atlasW
|
||||
val h = atlasH
|
||||
val payloads = Array(slotCount) { index ->
|
||||
AtlasPayload(
|
||||
slotIndex = index,
|
||||
atlasBuf = ByteBuffer.allocateDirect(w * h).order(ByteOrder.nativeOrder()),
|
||||
vertexBuf = ByteBuffer.allocateDirect(
|
||||
AssAtlasPipelineConfig.MAX_QUADS * AssAtlasPipelineConfig.BYTES_PER_QUAD
|
||||
).order(ByteOrder.nativeOrder()),
|
||||
frame = AssAtlasFrame(0, 0, 0, 0, 0),
|
||||
presentationTimeUs = 0L,
|
||||
releaseTimeNs = C.TIME_UNSET
|
||||
)
|
||||
}
|
||||
return AtlasSlots(payloads, w, h).also { slots = it }
|
||||
}
|
||||
|
||||
/** Slot index the GL thread most recently took for drawing; the libass side
|
||||
* never writes it. Written only inside [takePending] on the GL thread. */
|
||||
@Volatile private var glLastTakenSlot = -1
|
||||
|
||||
private val pendingPayload = AtomicReference<AtlasPayload?>(null)
|
||||
private val glThread = AtlasGlThread(
|
||||
surface,
|
||||
width,
|
||||
height,
|
||||
assHandler,
|
||||
takePending = {
|
||||
pendingPayload.getAndSet(null)?.also { glLastTakenSlot = it.slotIndex }
|
||||
},
|
||||
resolveAtlasDims = ::resolveAtlasDims
|
||||
)
|
||||
private val libassThread = AtlasLibassThread(
|
||||
assHandler,
|
||||
acquireSlots = ::acquireSlots,
|
||||
speculationEnabled = speculationEnabled,
|
||||
glTakenSlot = { glLastTakenSlot },
|
||||
onFrameReady = { payload ->
|
||||
pendingPayload.set(payload)
|
||||
glThread.triggerDraw()
|
||||
}
|
||||
)
|
||||
|
||||
fun start() {
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
"AssAtlasPipeline",
|
||||
"start surface=${surfaceWidth}x$surfaceHeight slots=$slotCount speculation=$speculationEnabled"
|
||||
)
|
||||
}
|
||||
glThread.start()
|
||||
libassThread.start()
|
||||
}
|
||||
|
||||
fun requestRender(presentationTimeUs: Long, releaseTimeNs: Long) {
|
||||
libassThread.enqueue(presentationTimeUs, releaseTimeNs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-renders the last requested position — for renderer state changes (margins,
|
||||
* use-margins) that must become visible while playback is paused. Safe during
|
||||
* playback: the next video frame's [requestRender] supersedes it (latest-wins).
|
||||
*/
|
||||
fun invalidate() {
|
||||
libassThread.invalidate()
|
||||
}
|
||||
|
||||
fun onSurfaceSizeChanged(width: Int, height: Int) {
|
||||
glThread.onSurfaceSizeChanged(width, height)
|
||||
}
|
||||
|
||||
/** Vsync-pinned swaps performed (excludes untimed invalidate repaints). */
|
||||
val swapCount: Long get() = glThread.swapCount
|
||||
|
||||
/** Pinned swaps that finished past the swap-time budget (possible missed vsync). */
|
||||
val lateSwapCount: Long get() = glThread.lateSwapCount
|
||||
|
||||
/** Worst observed swap lateness past the target release time, in milliseconds. */
|
||||
val maxLateMs: Long get() = glThread.maxLateMs
|
||||
|
||||
/** Total libass renders performed (one per serviced request). */
|
||||
val renderCount: Long get() = libassThread.renderCount
|
||||
|
||||
/** Renders where libass reported changed content (atlas/vertex rewritten). */
|
||||
val changedRenderCount: Long get() = libassThread.changedRenderCount
|
||||
|
||||
/** Renders that overflowed the atlas/vertex capacity (frame content incomplete). */
|
||||
val overflowCount: Long get() = libassThread.overflowCount
|
||||
|
||||
/** Duration of the most recent libass render, in milliseconds. */
|
||||
val lastLibassMs: Long get() = libassThread.lastLibassMs
|
||||
|
||||
/** Worst observed libass render duration, in milliseconds. */
|
||||
val maxLibassMs: Long get() = libassThread.maxLibassMs
|
||||
|
||||
/** Changed-render duration histogram: [≤10ms, ≤25ms, ≤42ms, ≤84ms, >84ms]. */
|
||||
val libassMsHistogram: List<Long> get() = libassThread.histogramSnapshot()
|
||||
|
||||
/** Requests served from a pre-rendered (speculative) frame — GL-only hot path. */
|
||||
val specHits: Long get() = libassThread.specHits
|
||||
|
||||
/** Requests where a speculative frame existed but didn't match (seek, state change). */
|
||||
val specMisses: Long get() = libassThread.specMisses
|
||||
|
||||
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
|
||||
val specSkips: Long get() = libassThread.specSkips
|
||||
|
||||
/** Cache-warming prefetch renders of upcoming events. */
|
||||
val prefetchCount: Long get() = libassThread.prefetchCount
|
||||
|
||||
/** Worst (minimum) lead of a changed-content pinned swap vs its target release
|
||||
* time, in ms; negative = the new content was queued after the video frame's
|
||||
* vsync. Long.MAX_VALUE until a changed pinned swap happened. */
|
||||
val minLeadChangedMs: Long get() = glThread.minLeadChangedMs
|
||||
|
||||
fun releaseAndWait() {
|
||||
libassThread.releaseAndWait()
|
||||
glThread.releaseAndWait()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a [Handler] synchronously: posts [releaseWhat] with an [Ack], waits up to 1 s
|
||||
* for the handler to invoke [onReleased] (on its own looper) and signal the latch.
|
||||
*/
|
||||
private fun postShutdownAndWait(
|
||||
handler: Handler,
|
||||
releaseWhat: Int,
|
||||
onReleased: () -> Unit
|
||||
) {
|
||||
val latch = Object()
|
||||
synchronized(latch) {
|
||||
handler.obtainMessage(releaseWhat, Ack(latch, onReleased)).sendToTarget()
|
||||
try {
|
||||
latch.wait(1_000)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Transport for [postShutdownAndWait] — the handler callback calls [release] then notifies. */
|
||||
private class Ack(val latch: Any, val release: () -> Unit)
|
||||
|
||||
/**
|
||||
* Runs libass off the GL thread into a packed atlas + vertex stream. Latest-wins:
|
||||
* older pending renders are dropped when a newer one arrives. Slot choice, the
|
||||
* changed-flag bookkeeping and speculative render-ahead live in [SpecRenderEngine];
|
||||
* this thread owns the buffers, the timing/stat accounting and the GL handoff.
|
||||
*/
|
||||
@UnstableApi
|
||||
private class AtlasLibassThread(
|
||||
private val assHandler: AssHandler,
|
||||
private val acquireSlots: () -> AtlasSlots,
|
||||
private val speculationEnabled: Boolean,
|
||||
private val glTakenSlot: () -> Int,
|
||||
private val onFrameReady: (AtlasPayload) -> Unit
|
||||
) : HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY) {
|
||||
|
||||
/** Immutable (pts, release) request — handed off through a single atomic so a
|
||||
* concurrent enqueue can neither be lost by drain's consume nor torn in half.
|
||||
* [enqueueNs] timestamps the handoff so drain can report how long the request
|
||||
* sat behind an in-flight render (the queue-wait component of subtitle lag). */
|
||||
private class PendingFrame(val ptsUs: Long, val releaseNs: Long, val enqueueNs: Long = System.nanoTime())
|
||||
|
||||
private lateinit var handler: Handler
|
||||
|
||||
private val pending = AtomicReference<PendingFrame?>(null)
|
||||
|
||||
@Volatile private var lastRequestedPtsUs = UNSET
|
||||
private var contentSeqCounter = 0L
|
||||
|
||||
// Thread-confined; created on first render so non-ASS playback never allocates.
|
||||
private var engine: SpecRenderEngine? = null
|
||||
|
||||
val specHits: Long get() = engine?.specHits ?: 0L
|
||||
val specMisses: Long get() = engine?.specMisses ?: 0L
|
||||
val specSkips: Long get() = engine?.specSkips ?: 0L
|
||||
val prefetchCount: Long get() = engine?.prefetchCount ?: 0L
|
||||
|
||||
// Telemetry; single-writer (this thread), read from the stats path.
|
||||
@Volatile var renderCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var changedRenderCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var overflowCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var lastLibassMs = 0L
|
||||
private set
|
||||
|
||||
@Volatile var maxLibassMs = 0L
|
||||
private set
|
||||
|
||||
/** Changed-render durations bucketed at ≤10 / ≤25 / ≤42 / ≤84 / >84 ms. */
|
||||
private val histogram = java.util.concurrent.atomic.AtomicLongArray(5)
|
||||
|
||||
fun histogramSnapshot(): List<Long> = List(histogram.length()) { histogram.get(it) }
|
||||
|
||||
private fun recordChangedRenderMs(ms: Long) {
|
||||
val bucket = when {
|
||||
ms <= 10 -> 0
|
||||
ms <= 25 -> 1
|
||||
ms <= 42 -> 2
|
||||
ms <= 84 -> 3
|
||||
else -> 4
|
||||
}
|
||||
histogram.incrementAndGet(bucket)
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
super.start()
|
||||
handler = Handler(looper) { msg ->
|
||||
when (msg.what) {
|
||||
MSG_RENDER -> drainAndRender()
|
||||
MSG_RELEASE -> {
|
||||
val ack = msg.obj as Ack
|
||||
ack.release()
|
||||
quit()
|
||||
synchronized(ack.latch) { (ack.latch as Object).notifyAll() }
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fun enqueue(presentationTimeUs: Long, releaseTimeNs: Long) {
|
||||
if (!::handler.isInitialized) return
|
||||
val dropped = pending.getAndSet(PendingFrame(presentationTimeUs, releaseTimeNs))
|
||||
if (dropped != null && AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
// A request was coalesced away — the renderer is behind by at least one
|
||||
// frame. agedMs = how long the dropped request had been waiting.
|
||||
Log.d(
|
||||
TAG,
|
||||
"drop pts=${dropped.ptsUs / 1000}ms agedMs=${(System.nanoTime() - dropped.enqueueNs) / 1_000_000} " +
|
||||
"replacedBy=${presentationTimeUs / 1000}ms"
|
||||
)
|
||||
}
|
||||
handler.removeMessages(MSG_RENDER)
|
||||
handler.sendEmptyMessage(MSG_RENDER)
|
||||
}
|
||||
|
||||
/** Re-enqueues the last requested PTS (renderer state changed, possibly while paused). */
|
||||
fun invalidate() {
|
||||
val pts = lastRequestedPtsUs
|
||||
if (pts == UNSET) return
|
||||
// TIME_UNSET release time => the GL thread swaps immediately instead of
|
||||
// vsync-pinning to a video frame that may never come while paused.
|
||||
enqueue(pts, C.TIME_UNSET)
|
||||
}
|
||||
|
||||
private fun ensureEngine(slots: AtlasSlots): SpecRenderEngine {
|
||||
engine?.let { return it }
|
||||
return SpecRenderEngine(
|
||||
slotCount = slots.payloads.size,
|
||||
speculationEnabled = speculationEnabled,
|
||||
renderAt = { timeMs, slot -> timedRender(timeMs, slots, slot) },
|
||||
// Renderer identity in the high bits + its state generation in the low bits:
|
||||
// a recreated renderer (media item transition) can never alias a stale
|
||||
// speculation, even if the new generation counter happens to match.
|
||||
stateGeneration = {
|
||||
assHandler.render?.let {
|
||||
(System.identityHashCode(it).toLong() shl 32) or (it.stateGeneration.toLong() and 0xffffffffL)
|
||||
} ?: -1L
|
||||
},
|
||||
glTakenSlot = glTakenSlot,
|
||||
debugLog = if (AssAtlasPipelineConfig.TIMING_LOGS) ({ msg -> Log.d(TAG, msg) }) else null
|
||||
).also { engine = it }
|
||||
}
|
||||
|
||||
/** Consecutive renders that reported no content change — a static screen.
|
||||
* Reset by any changed render (dialogue flips, karaoke, animated signs). */
|
||||
private var unchangedStreak = 0
|
||||
|
||||
/** Renders into [slot]'s buffers, owning the per-render timing/stat accounting
|
||||
* for both on-demand and speculative renders. */
|
||||
private fun timedRender(timeMs: Long, slots: AtlasSlots, slot: Int): AssAtlasFrame? {
|
||||
val render = assHandler.render ?: return null
|
||||
val payload = slots.payloads[slot]
|
||||
val t0 = System.nanoTime()
|
||||
val frame = render.renderFrameAtlas(timeMs, payload.atlasBuf, slots.atlasW, slots.atlasH, payload.vertexBuf)
|
||||
?: return null
|
||||
val libassMs = (System.nanoTime() - t0) / 1_000_000
|
||||
renderCount++
|
||||
lastLibassMs = libassMs
|
||||
if (libassMs > maxLibassMs) maxLibassMs = libassMs
|
||||
if (frame.truncated > 0) overflowCount++
|
||||
if (frame.changed != 0) {
|
||||
changedRenderCount++
|
||||
recordChangedRenderMs(libassMs)
|
||||
unchangedStreak = 0
|
||||
} else {
|
||||
unchangedStreak++
|
||||
}
|
||||
return frame
|
||||
}
|
||||
|
||||
private fun drainAndRender() {
|
||||
val request = pending.getAndSet(null) ?: return
|
||||
val pts = request.ptsUs
|
||||
val releaseNs = request.releaseNs
|
||||
lastRequestedPtsUs = pts
|
||||
val tDrain = System.nanoTime()
|
||||
// How long the request sat in the handoff (behind an in-flight on-demand or
|
||||
// speculative render) — the queue-wait component of any subtitle lag.
|
||||
val waitMs = (tDrain - request.enqueueNs) / 1_000_000
|
||||
// Before any ASS render exists (SRT/VTT or no subs) do nothing — this also
|
||||
// keeps the slot buffers unallocated for non-ASS playback.
|
||||
if (assHandler.render == null) return
|
||||
val slots = acquireSlots()
|
||||
val engine = ensureEngine(slots)
|
||||
val pinned = releaseNs != C.TIME_UNSET
|
||||
// Budget left until the video frame's vsync when we START servicing.
|
||||
val budgetMs = if (pinned) (releaseNs - tDrain) / 1_000_000 else -1L
|
||||
|
||||
when (val outcome = engine.service(pts, pinned)) {
|
||||
is SpecRenderEngine.Outcome.Post -> {
|
||||
val payload = slots.payloads[outcome.slot]
|
||||
if (outcome.newContent) {
|
||||
payload.frame = outcome.frame
|
||||
payload.contentSeq = ++contentSeqCounter
|
||||
}
|
||||
payload.presentationTimeUs = pts
|
||||
payload.releaseTimeNs = releaseNs
|
||||
onFrameReady(payload)
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"render pts=${pts / 1000}ms seq=${payload.contentSeq} waitMs=$waitMs budgetMs=$budgetMs " +
|
||||
"libassMs=$lastLibassMs lockWaitMs=${assHandler.render?.lastLockWaitMs} " +
|
||||
"specHit=${outcome.specHit} changed=${payload.frame.changed} quads=${payload.frame.quadCount} " +
|
||||
"atlas=${payload.frame.atlasWidth}x${payload.frame.atlasHeight} truncated=${payload.frame.truncated}"
|
||||
)
|
||||
}
|
||||
}
|
||||
SpecRenderEngine.Outcome.Skip -> {
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(TAG, "skip pts=${pts / 1000}ms waitMs=$waitMs budgetMs=$budgetMs (no content)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-render the predicted next frame in the dead time between requests so the
|
||||
// next service is (usually) a GL-only hit. Never delays a waiting request.
|
||||
engine.speculateAfter(pts, pinned, hasPending = pending.get() != null)?.let { write ->
|
||||
val payload = slots.payloads[write.slot]
|
||||
payload.frame = write.frame
|
||||
payload.contentSeq = ++contentSeqCounter
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"spec after=${pts / 1000}ms seq=${payload.contentSeq} libassMs=$lastLibassMs " +
|
||||
"lockWaitMs=${assHandler.render?.lastLockWaitMs} slot=${write.slot} quads=${write.frame.quadCount}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
maybePrefetch(engine, slots, pts, pinned)
|
||||
}
|
||||
|
||||
/** Start time of the last event boundary we cache-warmed (libass/track ms). */
|
||||
private var lastPrefetchedStartMs = Long.MIN_VALUE
|
||||
|
||||
/** Wall time of the last prefetch render, for the cooldown. */
|
||||
private var lastPrefetchNs = Long.MIN_VALUE / 2
|
||||
|
||||
/**
|
||||
* Cache-warms the next upcoming subtitle event so heavy typesetting pays its
|
||||
* cache-cold rasterization (seconds on weak devices) before the sign appears
|
||||
* instead of at appearance.
|
||||
*
|
||||
* The render blocks this thread, and during playback a new request is never
|
||||
* more than one frame interval away — so a prefetch is only allowed when its
|
||||
* delay cannot be SEEN, not merely when the queue is momentarily empty
|
||||
* (the v1 mistake, which thrashed on densely-authored per-frame events and
|
||||
* stalled visible dialogue):
|
||||
* - the screen must be static ([unchangedStreak]): requests delayed behind
|
||||
* the prefetch re-render identical content, so their lateness is invisible;
|
||||
* - the warmed event must be the NEXT on-screen change (no other event start
|
||||
* or end before it) — this also kills dense per-frame event sections,
|
||||
* where the next change is always ≤ one frame away;
|
||||
* - a cooldown bounds the worst-case overhead to one render per window.
|
||||
*/
|
||||
private fun maybePrefetch(engine: SpecRenderEngine, slots: AtlasSlots, ptsUs: Long, pinned: Boolean) {
|
||||
if (!speculationEnabled) return
|
||||
if (!pinned) return
|
||||
if (pending.get() != null) return
|
||||
if (unchangedStreak < PREFETCH_STATIC_STREAK) return
|
||||
val now = System.nanoTime()
|
||||
if (now - lastPrefetchNs < PREFETCH_COOLDOWN_NS) return
|
||||
val track = assHandler.track ?: return
|
||||
val nowMs = ptsUs / 1000
|
||||
// Events closer than MIN_AHEAD are the regular per-frame path's business;
|
||||
// beyond HORIZON the warmed bitmaps may be evicted before they're needed.
|
||||
val targetMs = track.nextEventStartMs(nowMs + PREFETCH_MIN_AHEAD_MS)
|
||||
if (targetMs < 0 || targetMs == lastPrefetchedStartMs) return
|
||||
if (targetMs > nowMs + PREFETCH_HORIZON_MS) return
|
||||
// Invisibility gate, time-budgeted: a prefetch is invisible as long as it
|
||||
// finishes before anything on screen is due to change (the screen is static
|
||||
// per the streak gate, so requests delayed behind it re-render identical
|
||||
// content). Estimate the cost from the worst render seen this session —
|
||||
// an overestimate only skips warming; an underestimate delays one boundary
|
||||
// by the shortfall. nextEventChangeMs also sees ends, so a dialogue line
|
||||
// due to disappear inside the budget skips the prefetch.
|
||||
val nextChangeMs = track.nextEventChangeMs(nowMs)
|
||||
if (nextChangeMs in 0 until targetMs) {
|
||||
val runwayMs = nextChangeMs - nowMs
|
||||
val costEstimateMs = (maxLibassMs * 5 / 4).coerceIn(PREFETCH_COST_FLOOR_MS, PREFETCH_COST_CEIL_MS)
|
||||
if (runwayMs < costEstimateMs + PREFETCH_SAFETY_MS) return
|
||||
}
|
||||
lastPrefetchedStartMs = targetMs
|
||||
lastPrefetchNs = now
|
||||
engine.prefetch(targetMs * 1000)?.let { write ->
|
||||
val payload = slots.payloads[write.slot]
|
||||
payload.frame = write.frame
|
||||
payload.contentSeq = ++contentSeqCounter
|
||||
}
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"prefetch evt=${targetMs}ms aheadMs=${targetMs - nowMs} " +
|
||||
"tookMs=${(System.nanoTime() - now) / 1_000_000} libassMs=$lastLibassMs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseAndWait() {
|
||||
if (!::handler.isInitialized) {
|
||||
quit()
|
||||
return
|
||||
}
|
||||
postShutdownAndWait(handler, MSG_RELEASE) { /* nothing thread-local to tear down */ }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AssLibassThread"
|
||||
private const val MSG_RENDER = 1
|
||||
private const val MSG_RELEASE = 2
|
||||
private const val UNSET = Long.MIN_VALUE
|
||||
|
||||
/** Don't prefetch events the per-frame speculation will reach imminently. */
|
||||
private const val PREFETCH_MIN_AHEAD_MS = 1_000L
|
||||
|
||||
/** Don't warm caches so early that the bitmaps could be evicted again. */
|
||||
private const val PREFETCH_HORIZON_MS = 15_000L
|
||||
|
||||
/** Static-screen requirement before a prefetch may block this thread. */
|
||||
private const val PREFETCH_STATIC_STREAK = 3
|
||||
|
||||
/** Minimum spacing between prefetch renders. */
|
||||
private const val PREFETCH_COOLDOWN_NS = 2_000_000_000L
|
||||
|
||||
/** Cost-estimate clamp for the time-budgeted invisibility gate: never
|
||||
* assume a prefetch cheaper than the floor (estimator may not have seen a
|
||||
* heavy frame yet) nor pointlessly demand more runway than the ceiling. */
|
||||
private const val PREFETCH_COST_FLOOR_MS = 250L
|
||||
private const val PREFETCH_COST_CEIL_MS = 1_500L
|
||||
|
||||
/** Slack added to the cost estimate when checking the static runway. */
|
||||
private const val PREFETCH_SAFETY_MS = 150L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the EGL surface, uploads the atlas + vertex stream and issues a single
|
||||
* `glDrawArrays` per frame. Swaps immediately with the swap pinned to the video's
|
||||
* target release time via [EGLExt.eglPresentationTimeANDROID]; SurfaceFlinger
|
||||
* holds the buffer until then, so the thread is never blocked waiting for a vsync.
|
||||
*/
|
||||
@UnstableApi
|
||||
private class AtlasGlThread(
|
||||
private val surface: Surface,
|
||||
@Volatile private var width: Int,
|
||||
@Volatile private var height: Int,
|
||||
private val assHandler: AssHandler,
|
||||
private val takePending: () -> AtlasPayload?,
|
||||
private val resolveAtlasDims: (maxTextureSize: Int) -> Pair<Int, Int>
|
||||
) : HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY) {
|
||||
|
||||
private lateinit var handler: Handler
|
||||
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
|
||||
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
|
||||
private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE
|
||||
|
||||
private val renderer = AtlasRenderer(assHandler)
|
||||
private var lastUploadedPayload: AtlasPayload? = null
|
||||
private var lastUploadedSeq = -1L
|
||||
private var lastSwappedSeq = -1L
|
||||
|
||||
// Lateness telemetry; single-writer (this thread), read from the stats path.
|
||||
@Volatile var swapCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var lateSwapCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var maxLateMs = 0L
|
||||
private set
|
||||
|
||||
/** Minimum lead (release target − swap completion) over changed-content pinned
|
||||
* swaps; negative = content queued after the video frame's vsync. */
|
||||
@Volatile var minLeadChangedMs = Long.MAX_VALUE
|
||||
private set
|
||||
|
||||
override fun start() {
|
||||
super.start()
|
||||
handler = Handler(looper) { msg ->
|
||||
try {
|
||||
when (msg.what) {
|
||||
MSG_INIT -> initEgl()
|
||||
MSG_DRAW -> drawAndSwap()
|
||||
MSG_SIZE_CHANGED -> sizeChanged(width, height)
|
||||
MSG_RELEASE -> {
|
||||
val ack = msg.obj as Ack
|
||||
ack.release()
|
||||
quit()
|
||||
synchronized(ack.latch) { (ack.latch as Object).notifyAll() }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "GL thread error", e)
|
||||
releaseEgl()
|
||||
}
|
||||
true
|
||||
}
|
||||
handler.sendEmptyMessage(MSG_INIT)
|
||||
}
|
||||
|
||||
fun onSurfaceSizeChanged(width: Int, height: Int) {
|
||||
this.width = width
|
||||
this.height = height
|
||||
handler.sendEmptyMessage(MSG_SIZE_CHANGED)
|
||||
}
|
||||
|
||||
fun triggerDraw() {
|
||||
if (!::handler.isInitialized) return
|
||||
handler.removeMessages(MSG_DRAW)
|
||||
handler.sendEmptyMessage(MSG_DRAW)
|
||||
}
|
||||
|
||||
fun releaseAndWait() {
|
||||
if (!::handler.isInitialized) {
|
||||
quit()
|
||||
return
|
||||
}
|
||||
postShutdownAndWait(handler, MSG_RELEASE) { releaseEgl() }
|
||||
}
|
||||
|
||||
private fun initEgl() {
|
||||
try {
|
||||
eglDisplay = GlUtil.getDefaultEglDisplay()
|
||||
eglContext = GlUtil.createEglContext(eglDisplay)
|
||||
eglSurface = GlUtil.createEglSurface(eglDisplay, surface, C.COLOR_TRANSFER_SDR, false)
|
||||
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
|
||||
renderer.onSurfaceCreated()
|
||||
// Resolve atlas dims from real GL caps (first-wins against the libass
|
||||
// thread's fallback) and allocate the texture once at those dims — uploads
|
||||
// are glTexSubImage2D of the packed rows from then on.
|
||||
val maxTexture = IntArray(1)
|
||||
GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxTexture, 0)
|
||||
val (atlasW, atlasH) = resolveAtlasDims(maxTexture[0])
|
||||
renderer.allocateAtlasTexture(atlasW, atlasH)
|
||||
sizeChanged(width, height)
|
||||
} catch (e: GlUtil.GlException) {
|
||||
Log.e(TAG, "Failed to initialize EGL", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sizeChanged(width: Int, height: Int) {
|
||||
renderer.onSurfaceChanged(width, height)
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
|
||||
GlUtil.clearFocusedBuffers()
|
||||
EGL14.eglSwapBuffers(eglDisplay, eglSurface)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawAndSwap() {
|
||||
if (eglDisplay == EGL14.EGL_NO_DISPLAY) return
|
||||
val payload = takePending() ?: return
|
||||
|
||||
// Render immediately (GL commands queue on the GPU). Re-upload only when the
|
||||
// slot's content actually changed — identity alone is not enough because the
|
||||
// libass side rewrites slot buffers in place (contentSeq tracks the rewrites).
|
||||
val t0 = System.nanoTime()
|
||||
val reuse = payload === lastUploadedPayload && payload.contentSeq == lastUploadedSeq
|
||||
renderer.onDrawFrame(payload, reuseUploads = reuse)
|
||||
lastUploadedPayload = payload
|
||||
lastUploadedSeq = payload.contentSeq
|
||||
val t1 = System.nanoTime()
|
||||
|
||||
// Swap immediately with the presentation time set: SurfaceFlinger holds the
|
||||
// queued buffer until the video frame's target release time, so the subtitle
|
||||
// can never appear early, and the GL thread is free again within a couple of
|
||||
// milliseconds. Sleeping here until near the target vsync (as a removed
|
||||
// TextureView path once required) made this thread blind for almost a whole
|
||||
// frame interval — the single-slot latest-wins handoff would then drop an
|
||||
// intermediate subtitle state (e.g. the transition to blank), showing the
|
||||
// previous state one frame too long.
|
||||
if (payload.releaseTimeNs != C.TIME_UNSET) {
|
||||
EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, payload.releaseTimeNs)
|
||||
}
|
||||
EGL14.eglSwapBuffers(eglDisplay, eglSurface)
|
||||
val t2 = System.nanoTime()
|
||||
if (payload.releaseTimeNs != C.TIME_UNSET) {
|
||||
swapCount++
|
||||
val lateNs = t2 - payload.releaseTimeNs
|
||||
if (lateNs > LATE_THRESHOLD_NS) {
|
||||
lateSwapCount++
|
||||
val lateMs = lateNs / 1_000_000
|
||||
if (lateMs > maxLateMs) maxLateMs = lateMs
|
||||
}
|
||||
// Lead of changed-content swaps is the frame-perfection signal: ≥ 0 means
|
||||
// the new subtitle content reached the queue before the video frame's vsync.
|
||||
if (payload.contentSeq != lastSwappedSeq) {
|
||||
val leadMs = -lateNs / 1_000_000
|
||||
if (leadMs < minLeadChangedMs) minLeadChangedMs = leadMs
|
||||
}
|
||||
}
|
||||
lastSwappedSeq = payload.contentSeq
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
val pinned = payload.releaseTimeNs != C.TIME_UNSET
|
||||
// headroomMs: slack before the target vsync when GL STARTED; leadMs: slack
|
||||
// when the buffer was actually queued (negative = queued after the vsync).
|
||||
val headroomMs = if (pinned) (payload.releaseTimeNs - t0) / 1_000_000 else -1L
|
||||
val leadMs = if (pinned) (payload.releaseTimeNs - t2) / 1_000_000 else -1L
|
||||
Log.d(
|
||||
TAG,
|
||||
"swap pts=${payload.presentationTimeUs / 1000}ms seq=${payload.contentSeq} " +
|
||||
"quads=${payload.frame.quadCount} reused=$reuse drawMs=${(t1 - t0) / 1_000_000} " +
|
||||
"swapMs=${(t2 - t1) / 1_000_000} headroomMs=$headroomMs leadMs=$leadMs pinned=$pinned"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseEgl() {
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
|
||||
try {
|
||||
renderer.onSurfaceDestroyed()
|
||||
GlUtil.destroyEglSurface(eglDisplay, eglSurface)
|
||||
GlUtil.destroyEglContext(eglDisplay, eglContext)
|
||||
} catch (e: GlUtil.GlException) {
|
||||
Log.e(TAG, "Failed to release EGL", e)
|
||||
} finally {
|
||||
eglDisplay = EGL14.EGL_NO_DISPLAY
|
||||
eglContext = EGL14.EGL_NO_CONTEXT
|
||||
eglSurface = EGL14.EGL_NO_SURFACE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AssSurfaceGlThread"
|
||||
private const val MSG_INIT = 1
|
||||
private const val MSG_DRAW = 2
|
||||
private const val MSG_SIZE_CHANGED = 3
|
||||
private const val MSG_RELEASE = 4
|
||||
|
||||
/**
|
||||
* Swaps finishing this far past the target release time arrived after the
|
||||
* buffer should already have been queued and may miss the frame's vsync —
|
||||
* actual slack depends on the display's vsync offset from the release time.
|
||||
*/
|
||||
private const val LATE_THRESHOLD_NS = 4_000_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GL-side work for the atlas-based path. Maintains a single atlas texture and a
|
||||
* single vertex buffer; uploads them per frame (unless the payload identity
|
||||
* matches the last upload) and issues one `glDrawArrays` for the whole frame.
|
||||
*/
|
||||
@UnstableApi
|
||||
private class AtlasRenderer(private val assHandler: AssHandler) {
|
||||
|
||||
private val vertexShaderCode = """
|
||||
attribute vec2 a_Position;
|
||||
attribute vec2 a_TexCoord;
|
||||
attribute vec4 a_Color;
|
||||
uniform vec2 u_SurfaceSize;
|
||||
varying vec2 v_TexCoord;
|
||||
varying vec4 v_Color;
|
||||
void main() {
|
||||
vec2 clip = (a_Position / u_SurfaceSize) * 2.0 - 1.0;
|
||||
clip.y = -clip.y;
|
||||
gl_Position = vec4(clip, 0.0, 1.0);
|
||||
v_TexCoord = a_TexCoord;
|
||||
v_Color = a_Color;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val fragmentShaderCode = """
|
||||
precision mediump float;
|
||||
varying vec2 v_TexCoord;
|
||||
varying vec4 v_Color;
|
||||
uniform sampler2D u_Texture;
|
||||
void main() {
|
||||
float alpha = texture2D(u_Texture, v_TexCoord).a;
|
||||
gl_FragColor = v_Color * alpha;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private var surfaceSize = Size.ZERO
|
||||
private lateinit var glProgram: GlProgram
|
||||
|
||||
private var atlasTexId = 0
|
||||
private var vertexBufferId = 0
|
||||
|
||||
private var aPosition = 0
|
||||
private var aTexCoord = 0
|
||||
private var aColor = 0
|
||||
private var uTexture = 0
|
||||
private var uSurfaceSize = 0
|
||||
|
||||
private var atlasAllocatedW = 0
|
||||
private var atlasAllocatedH = 0
|
||||
|
||||
/**
|
||||
* Allocates the atlas texture once at the resolved dims. The C side bakes UV
|
||||
* denominators = these dims into the vertex stream, so per-frame uploads can be
|
||||
* partial ([uploadAtlas]) without ever reallocating — drivers keep one stable
|
||||
* texture allocation instead of churning on packed-height changes.
|
||||
*/
|
||||
fun allocateAtlasTexture(width: Int, height: Int) {
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, atlasTexId)
|
||||
GLES20.glTexImage2D(
|
||||
GLES20.GL_TEXTURE_2D, 0, GLES20.GL_ALPHA,
|
||||
width, height, 0,
|
||||
GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, null
|
||||
)
|
||||
atlasAllocatedW = width
|
||||
atlasAllocatedH = height
|
||||
}
|
||||
|
||||
fun onSurfaceCreated() {
|
||||
glProgram = GlProgram(vertexShaderCode, fragmentShaderCode)
|
||||
GlUtil.checkGlError()
|
||||
glProgram.use()
|
||||
|
||||
aPosition = glProgram.getAttributeArrayLocationAndEnable("a_Position")
|
||||
aTexCoord = glProgram.getAttributeArrayLocationAndEnable("a_TexCoord")
|
||||
aColor = glProgram.getAttributeArrayLocationAndEnable("a_Color")
|
||||
uTexture = glProgram.getUniformLocation("u_Texture")
|
||||
uSurfaceSize = glProgram.getUniformLocation("u_SurfaceSize")
|
||||
|
||||
val tex = IntArray(1)
|
||||
GLES20.glGenTextures(1, tex, 0)
|
||||
atlasTexId = tex[0]
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, atlasTexId)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
|
||||
GLES20.glUniform1i(uTexture, 0)
|
||||
|
||||
val buf = IntArray(1)
|
||||
GLES20.glGenBuffers(1, buf, 0)
|
||||
vertexBufferId = buf[0]
|
||||
|
||||
GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1)
|
||||
GLES20.glEnable(GLES20.GL_BLEND)
|
||||
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA)
|
||||
}
|
||||
|
||||
fun onSurfaceChanged(width: Int, height: Int) {
|
||||
surfaceSize = Size(width, height)
|
||||
assHandler.render?.setFrameSize(width, height)
|
||||
GLES20.glViewport(0, 0, width, height)
|
||||
GLES20.glUniform2f(uSurfaceSize, width.toFloat(), height.toFloat())
|
||||
}
|
||||
|
||||
fun onDrawFrame(payload: AtlasPayload, reuseUploads: Boolean) {
|
||||
GlUtil.clearFocusedBuffers()
|
||||
|
||||
val frame = payload.frame
|
||||
val quadCount = frame.quadCount
|
||||
if (quadCount == 0) return
|
||||
|
||||
if (!reuseUploads) {
|
||||
uploadAtlas(payload.atlasBuf, frame.atlasWidth, frame.atlasHeight)
|
||||
uploadVertices(payload.vertexBuf, quadCount)
|
||||
}
|
||||
|
||||
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBufferId)
|
||||
val stride = AssAtlasPipelineConfig.BYTES_PER_VERTEX
|
||||
GLES20.glVertexAttribPointer(aPosition, 2, GLES20.GL_FLOAT, false, stride, 0)
|
||||
GLES20.glVertexAttribPointer(aTexCoord, 2, GLES20.GL_FLOAT, false, stride, 8)
|
||||
GLES20.glVertexAttribPointer(aColor, 4, GLES20.GL_FLOAT, false, stride, 16)
|
||||
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, quadCount * 6)
|
||||
}
|
||||
|
||||
private fun uploadAtlas(atlasBuf: ByteBuffer, atlasW: Int, atlasH: Int) {
|
||||
atlasBuf.position(0).limit(atlasW * atlasH)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, atlasTexId)
|
||||
if (atlasW == atlasAllocatedW && atlasH <= atlasAllocatedH) {
|
||||
// Steady state: packed rows into the once-allocated texture.
|
||||
GLES20.glTexSubImage2D(
|
||||
GLES20.GL_TEXTURE_2D, 0, 0, 0, atlasW, atlasH,
|
||||
GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, atlasBuf
|
||||
)
|
||||
} else {
|
||||
// Defensive: dims disagree with the allocation (shouldn't happen — both
|
||||
// sides resolve dims through the same first-wins gate).
|
||||
Log.w("AssAtlasRenderer", "atlas upload ${atlasW}x$atlasH outside allocation ${atlasAllocatedW}x$atlasAllocatedH")
|
||||
GLES20.glTexImage2D(
|
||||
GLES20.GL_TEXTURE_2D, 0, GLES20.GL_ALPHA,
|
||||
atlasW, atlasH, 0,
|
||||
GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, atlasBuf
|
||||
)
|
||||
atlasAllocatedW = atlasW
|
||||
atlasAllocatedH = atlasH
|
||||
}
|
||||
}
|
||||
|
||||
private fun uploadVertices(vertexBuf: ByteBuffer, quadCount: Int) {
|
||||
val size = quadCount * AssAtlasPipelineConfig.BYTES_PER_QUAD
|
||||
vertexBuf.position(0).limit(size)
|
||||
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBufferId)
|
||||
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, size, vertexBuf, GLES20.GL_STREAM_DRAW)
|
||||
}
|
||||
|
||||
fun onSurfaceDestroyed() {
|
||||
if (atlasTexId != 0) {
|
||||
val tex = intArrayOf(atlasTexId)
|
||||
GLES20.glDeleteTextures(1, tex, 0)
|
||||
atlasTexId = 0
|
||||
}
|
||||
if (vertexBufferId != 0) {
|
||||
val buf = intArrayOf(vertexBufferId)
|
||||
GLES20.glDeleteBuffers(1, buf, 0)
|
||||
vertexBufferId = 0
|
||||
}
|
||||
if (::glProgram.isInitialized) glProgram.delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.graphics.PixelFormat
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
|
||||
/**
|
||||
* Subtitle overlay rendered through a dedicated [SurfaceView] layer.
|
||||
*
|
||||
* Uses a SurfaceFlinger layer directly, which lets the atlas-based pipeline
|
||||
* vsync-align its swap with the corresponding video frame via
|
||||
* `eglPresentationTimeANDROID`.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssSubtitleSurfaceView(
|
||||
context: Context,
|
||||
private val assHandler: AssHandler
|
||||
) : SurfaceView(context),
|
||||
SurfaceHolder.Callback {
|
||||
|
||||
private var pipeline: AssAtlasPipeline? = null
|
||||
|
||||
init {
|
||||
setZOrderMediaOverlay(true)
|
||||
holder.setFormat(PixelFormat.TRANSLUCENT)
|
||||
holder.addCallback(this)
|
||||
}
|
||||
|
||||
fun requestRender(presentationTimeUs: Long, releaseTimeNs: Long) {
|
||||
pipeline?.requestRender(presentationTimeUs, releaseTimeNs)
|
||||
}
|
||||
|
||||
/** Re-renders the last position, e.g. after margin changes while paused. */
|
||||
fun invalidateSubtitles() {
|
||||
pipeline?.invalidate()
|
||||
}
|
||||
|
||||
/** Vsync-pinned swaps performed by the current pipeline. */
|
||||
val swapCount: Long get() = pipeline?.swapCount ?: 0L
|
||||
|
||||
/** Pinned swaps that finished past the swap-time budget (possible missed vsync). */
|
||||
val lateSwapCount: Long get() = pipeline?.lateSwapCount ?: 0L
|
||||
|
||||
/** Worst observed swap lateness past the target release time, in milliseconds. */
|
||||
val maxLateMs: Long get() = pipeline?.maxLateMs ?: 0L
|
||||
|
||||
/** Total libass renders performed by the current pipeline. */
|
||||
val renderCount: Long get() = pipeline?.renderCount ?: 0L
|
||||
|
||||
/** Renders where libass reported changed content. */
|
||||
val changedRenderCount: Long get() = pipeline?.changedRenderCount ?: 0L
|
||||
|
||||
/** Renders that overflowed the atlas/vertex capacity. */
|
||||
val overflowCount: Long get() = pipeline?.overflowCount ?: 0L
|
||||
|
||||
/** Duration of the most recent libass render, in milliseconds. */
|
||||
val lastLibassMs: Long get() = pipeline?.lastLibassMs ?: 0L
|
||||
|
||||
/** Worst observed libass render duration, in milliseconds. */
|
||||
val maxLibassMs: Long get() = pipeline?.maxLibassMs ?: 0L
|
||||
|
||||
/** Changed-render duration histogram: [≤10ms, ≤25ms, ≤42ms, ≤84ms, >84ms]. */
|
||||
val libassMsHistogram: List<Long> get() = pipeline?.libassMsHistogram ?: emptyList()
|
||||
|
||||
/** Requests served from a pre-rendered (speculative) frame. */
|
||||
val specHits: Long get() = pipeline?.specHits ?: 0L
|
||||
|
||||
/** Requests where speculation existed but didn't match (seek, state change). */
|
||||
val specMisses: Long get() = pipeline?.specMisses ?: 0L
|
||||
|
||||
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
|
||||
val specSkips: Long get() = pipeline?.specSkips ?: 0L
|
||||
|
||||
/** Cache-warming prefetch renders of upcoming events. */
|
||||
val prefetchCount: Long get() = pipeline?.prefetchCount ?: 0L
|
||||
|
||||
/** Minimum lead of changed-content pinned swaps vs the video frame's release
|
||||
* time, in ms (negative = late); null until one happened. */
|
||||
val minLeadChangedMs: Long? get() = pipeline?.minLeadChangedMs?.takeIf { it != Long.MAX_VALUE }
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
val rect = holder.surfaceFrame
|
||||
assHandler.setOverlaySurfaceSize(rect.width(), rect.height())
|
||||
val lowRam = (context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)
|
||||
?.isLowRamDevice ?: false
|
||||
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam)
|
||||
.also { it.start() }
|
||||
}
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
assHandler.setOverlaySurfaceSize(width, height)
|
||||
pipeline?.onSurfaceSizeChanged(width, height)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
pipeline?.releaseAndWait()
|
||||
pipeline = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* Decision core of the speculative render-ahead pipeline.
|
||||
*
|
||||
* The problem it solves: ExoPlayer's frame-metadata callback gives only ~40 ms
|
||||
* between "video frame scheduled" and that frame's vsync, while a changed-content
|
||||
* libass render can take longer — so a render started at the callback lands a
|
||||
* frame (or more) late. The engine renders the *predicted next* PTS right after
|
||||
* servicing the current one, in the dead time between frames; when the next
|
||||
* request matches the prediction, only the GL upload+swap (~6–11 ms) sits inside
|
||||
* the deadline.
|
||||
*
|
||||
* Pure logic, single-threaded (the libass worker) — rendering, buffers and GL
|
||||
* are behind injected closures, so the state machine is unit-testable. Only the
|
||||
* stat fields are read from other threads.
|
||||
*
|
||||
* Slot ownership invariant: a slot handed to GL ([lastPostedSlot]) or currently
|
||||
* read by GL ([glTakenSlot]) is never chosen as a render target. With 3 slots and
|
||||
* at most 2 exclusions a target always exists; with 2 slots (low-RAM devices)
|
||||
* speculation must be disabled and the legacy alternation behavior falls out.
|
||||
*
|
||||
* Key subtlety inherited from libass: `ass_render_frame`'s `changed` flag compares
|
||||
* against libass's *previous render* — which, with speculation, may be content
|
||||
* that never reached the screen. The engine therefore tracks [libassLastSlot]
|
||||
* (the slot holding libass's most recent render output) rather than the last
|
||||
* *posted* slot, and prefers it as the render target: on `changed == 0` the
|
||||
* buffers were untouched and that slot already holds exactly the right content.
|
||||
*/
|
||||
internal class SpecRenderEngine(
|
||||
private val slotCount: Int,
|
||||
private val speculationEnabled: Boolean,
|
||||
/**
|
||||
* Renders the current track at [timeMs] into the slot's buffers. Returns null
|
||||
* when the renderer/track is gone. The closure owns timing/stat accounting.
|
||||
*/
|
||||
private val renderAt: (timeMs: Long, slot: Int) -> AssAtlasFrame?,
|
||||
/**
|
||||
* Renderer identity + state generation as one comparable value. Must change
|
||||
* whenever a speculatively rendered frame could be stale: margins, sizes,
|
||||
* track switches, renderer recreation.
|
||||
*/
|
||||
private val stateGeneration: () -> Long,
|
||||
/** Slot the GL thread most recently took for drawing, or -1. Never write it. */
|
||||
private val glTakenSlot: () -> Int,
|
||||
/** Diagnostic sink for hit/miss/skip decisions; null disables (no string cost). */
|
||||
private val debugLog: ((String) -> Unit)? = null
|
||||
) {
|
||||
|
||||
/** What the caller should do after [service]. */
|
||||
sealed class Outcome {
|
||||
/** Nothing to post (no renderer, or no rendered content exists yet). */
|
||||
object Skip : Outcome()
|
||||
|
||||
/**
|
||||
* Post [slot] to GL. [newContent] means this call wrote fresh content into
|
||||
* the slot (the caller bumps the payload's content seq). [specHit] means the
|
||||
* content was pre-rendered — no libass render ran inside the deadline.
|
||||
*/
|
||||
class Post(val slot: Int, val frame: AssAtlasFrame, val newContent: Boolean, val specHit: Boolean) : Outcome()
|
||||
}
|
||||
|
||||
/** A speculative render that wrote new content into [slot] (bump its seq). */
|
||||
class SpecWrite(val slot: Int, val frame: AssAtlasFrame)
|
||||
|
||||
// Speculation state: content for specPtsUs is pre-rendered and lives either in
|
||||
// specSlot, or — when the spec render returned changed == 0 — is identical to
|
||||
// libassLastSlot's content (specIsLibassLast).
|
||||
private var specPtsUs = UNSET
|
||||
private var specSlot = -1
|
||||
private var specIsLibassLast = false
|
||||
private var specGen = 0L
|
||||
|
||||
// The slot holding libass's most recent render output and its frame.
|
||||
private var libassLastSlot = -1
|
||||
private var libassLastFrame: AssAtlasFrame? = null
|
||||
private var lastPostedSlot = -1
|
||||
|
||||
// Request-cadence estimator over pinned (playing) requests: median of the last
|
||||
// 8 PTS deltas, valid after 4, reset on any non-monotonic or > 250 ms jump.
|
||||
private val deltas = LongArray(DELTA_SAMPLES)
|
||||
private var deltaCount = 0
|
||||
private var deltaIndex = 0
|
||||
private var lastPinnedPtsUs = UNSET
|
||||
|
||||
// Stats; single-writer (the libass thread), read from the stats path.
|
||||
@Volatile
|
||||
var specHits = 0L
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var specMisses = 0L
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var specSkips = 0L
|
||||
private set
|
||||
|
||||
/**
|
||||
* Services a render request for [ptsUs]. [pinned] is false for invalidate
|
||||
* repaints (paused margin changes etc.), which never feed the cadence
|
||||
* estimator and never count as speculation misses against playback.
|
||||
*/
|
||||
fun service(ptsUs: Long, pinned: Boolean): Outcome {
|
||||
if (pinned) updateDeltaEstimator(ptsUs)
|
||||
|
||||
if (specPtsUs != UNSET) {
|
||||
val eps = epsilonUs()
|
||||
val genNow = stateGeneration()
|
||||
val hit = genNow == specGen && eps > 0 && abs(ptsUs - specPtsUs) <= eps
|
||||
val slot = if (specIsLibassLast) libassLastSlot else specSlot
|
||||
val frame = libassLastFrame
|
||||
val specPts = specPtsUs
|
||||
specPtsUs = UNSET
|
||||
if (hit && slot >= 0 && frame != null) {
|
||||
specHits++
|
||||
lastPostedSlot = slot
|
||||
debugLog?.invoke("hit pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms slot=$slot")
|
||||
return Outcome.Post(slot, frame, newContent = false, specHit = true)
|
||||
}
|
||||
specMisses++
|
||||
debugLog?.invoke(
|
||||
"miss pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms eps=${eps / 1000}ms " +
|
||||
"gen=${if (genNow == specGen) "ok" else "CHANGED"} slot=$slot frame=${frame != null}"
|
||||
)
|
||||
} else {
|
||||
debugLog?.invoke("no-spec pts=${ptsUs / 1000}ms")
|
||||
}
|
||||
|
||||
// On-demand render. Preferring libassLastSlot as the target makes changed == 0
|
||||
// unambiguous: the buffers were untouched and already hold the right content.
|
||||
val target = renderTargetSlot() ?: return Outcome.Skip
|
||||
val frame = renderAt(ptsUs / 1000, target) ?: return Outcome.Skip
|
||||
if (frame.changed == 0) {
|
||||
val lastSlot = libassLastSlot
|
||||
val lastFrame = libassLastFrame ?: return Outcome.Skip
|
||||
if (lastSlot < 0) return Outcome.Skip
|
||||
lastPostedSlot = lastSlot
|
||||
return Outcome.Post(lastSlot, lastFrame, newContent = false, specHit = false)
|
||||
}
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
lastPostedSlot = target
|
||||
return Outcome.Post(target, frame, newContent = true, specHit = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Speculatively renders the predicted next request ([servicedPtsUs] + median
|
||||
* delta) into a free slot. Call after posting the current frame; skipped while
|
||||
* paused ([pinned] false), when a newer request is already waiting, or while
|
||||
* the cadence estimator has no confident delta.
|
||||
*/
|
||||
fun speculateAfter(servicedPtsUs: Long, pinned: Boolean, hasPending: Boolean): SpecWrite? {
|
||||
if (!speculationEnabled) return null
|
||||
if (!pinned || hasPending || !deltaValid()) {
|
||||
specSkips++
|
||||
debugLog?.invoke(
|
||||
"spec-skip after=${servicedPtsUs / 1000}ms pinned=$pinned pending=$hasPending cadence=${deltaValid()}"
|
||||
)
|
||||
return null
|
||||
}
|
||||
val target = renderTargetSlot() ?: run {
|
||||
specSkips++
|
||||
debugLog?.invoke("spec-skip after=${servicedPtsUs / 1000}ms no-free-slot")
|
||||
return null
|
||||
}
|
||||
val gen = stateGeneration()
|
||||
val specPts = servicedPtsUs + medianDeltaUs()
|
||||
val frame = renderAt(specPts / 1000, target) ?: run {
|
||||
specSkips++
|
||||
return null
|
||||
}
|
||||
specGen = gen
|
||||
specPtsUs = specPts
|
||||
if (frame.changed == 0) {
|
||||
// Content at specPts is identical to libass's last render — nothing was
|
||||
// written; a hit will repost libassLastSlot (and GL will skip the upload).
|
||||
specIsLibassLast = true
|
||||
specSlot = -1
|
||||
return null
|
||||
}
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
specIsLibassLast = false
|
||||
specSlot = target
|
||||
return SpecWrite(target, frame)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-renders [ptsUs] (an upcoming event's start) purely to warm the
|
||||
* renderer's glyph/bitmap caches before that content is actually needed —
|
||||
* heavy typesetting otherwise pays its cache-cold rasterization (measured
|
||||
* 0.8–2.6 s on weak devices) exactly when the sign appears. The result is
|
||||
* never posted; like any render it becomes libass's last-rendered content,
|
||||
* so any pending speculation is invalidated first (its slot/content
|
||||
* references would go stale).
|
||||
*
|
||||
* Returns the slot written (caller bumps its content seq) or null when
|
||||
* nothing was rendered.
|
||||
*/
|
||||
fun prefetch(ptsUs: Long): SpecWrite? {
|
||||
specPtsUs = UNSET
|
||||
val target = renderTargetSlot() ?: return null
|
||||
val frame = renderAt(ptsUs / 1000, target) ?: return null
|
||||
prefetchCount++
|
||||
if (frame.changed == 0) return null
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
return SpecWrite(target, frame)
|
||||
}
|
||||
|
||||
/** Cache-warming prefetch renders performed; single-writer, read cross-thread. */
|
||||
@Volatile
|
||||
var prefetchCount = 0L
|
||||
private set
|
||||
|
||||
private fun renderTargetSlot(): Int? {
|
||||
// The GL exclusion only exists in ≥3-slot mode; with 2 slots this reduces to
|
||||
// the legacy "don't write the posted slot" alternation.
|
||||
val taken = if (slotCount > 2) glTakenSlot() else -1
|
||||
val last = libassLastSlot
|
||||
if (last >= 0 && last != lastPostedSlot && last != taken) return last
|
||||
for (s in 0 until slotCount) {
|
||||
if (s != lastPostedSlot && s != taken) return s
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun updateDeltaEstimator(ptsUs: Long) {
|
||||
val prev = lastPinnedPtsUs
|
||||
lastPinnedPtsUs = ptsUs
|
||||
if (prev == UNSET) return
|
||||
val d = ptsUs - prev
|
||||
if (d <= 0 || d > MAX_DELTA_US) {
|
||||
// Seek/discontinuity (or duplicate PTS): forget the cadence.
|
||||
deltaCount = 0
|
||||
deltaIndex = 0
|
||||
return
|
||||
}
|
||||
deltas[deltaIndex] = d
|
||||
deltaIndex = (deltaIndex + 1) % DELTA_SAMPLES
|
||||
if (deltaCount < DELTA_SAMPLES) deltaCount++
|
||||
}
|
||||
|
||||
private fun deltaValid() = deltaCount >= MIN_DELTA_SAMPLES
|
||||
|
||||
private fun medianDeltaUs(): Long {
|
||||
val copy = deltas.copyOfRange(0, deltaCount)
|
||||
copy.sort()
|
||||
return copy[deltaCount / 2]
|
||||
}
|
||||
|
||||
private fun epsilonUs(): Long = if (deltaValid()) minOf(medianDeltaUs() / 2, EPSILON_CAP_US) else 0L
|
||||
|
||||
private companion object {
|
||||
const val UNSET = Long.MIN_VALUE
|
||||
const val DELTA_SAMPLES = 8
|
||||
const val MIN_DELTA_SAMPLES = 4
|
||||
const val MAX_DELTA_US = 250_000L
|
||||
const val EPSILON_CAP_US = 8_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Tests for the speculative render-ahead state machine. The render function is
|
||||
* scripted: each call records (timeMs, slot) and returns the next queued frame.
|
||||
*/
|
||||
class SpecRenderEngineTest {
|
||||
|
||||
private class RenderCall(val timeMs: Long, val slot: Int)
|
||||
|
||||
private class Harness(
|
||||
slotCount: Int = 3,
|
||||
speculationEnabled: Boolean = true
|
||||
) {
|
||||
val calls = mutableListOf<RenderCall>()
|
||||
val script = ArrayDeque<AssAtlasFrame?>()
|
||||
var generation = 0L
|
||||
var glTaken = -1
|
||||
|
||||
val engine = SpecRenderEngine(
|
||||
slotCount = slotCount,
|
||||
speculationEnabled = speculationEnabled,
|
||||
renderAt = { timeMs, slot ->
|
||||
calls.add(RenderCall(timeMs, slot))
|
||||
if (script.isEmpty()) changed() else script.removeFirst()
|
||||
},
|
||||
stateGeneration = { generation },
|
||||
glTakenSlot = { glTaken }
|
||||
)
|
||||
|
||||
/** Primes the cadence estimator with [n] steady requests; returns last pts. */
|
||||
fun prime(n: Int = 5, startUs: Long = 0L, deltaUs: Long = 42_000L): Long {
|
||||
var pts = startUs
|
||||
repeat(n) {
|
||||
engine.service(pts, pinned = true)
|
||||
engine.speculateAfter(pts, pinned = true, hasPending = false)
|
||||
pts += deltaUs
|
||||
}
|
||||
return pts - deltaUs
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DELTA = 42_000L
|
||||
|
||||
fun changed(quads: Int = 5) = AssAtlasFrame(2048, 100, quads, 2, 0)
|
||||
|
||||
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `steady state hits serve without rendering`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
// Cadence is confident by now: the last speculateAfter pre-rendered last+Δ.
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(last + DELTA, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
outcome as SpecRenderEngine.Outcome.Post
|
||||
assertTrue(outcome.specHit)
|
||||
assertFalse(outcome.newContent) // content was written (and seq-bumped) at spec time
|
||||
assertEquals("service must not render on a hit", before, h.calls.size)
|
||||
assertEquals(1L, h.engine.specHits)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hit tolerates jitter within epsilon`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
val outcome = h.engine.service(last + DELTA + 3_000, pinned = true)
|
||||
|
||||
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `seek misses and renders on demand into the spec slot`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
val specSlot = h.calls.last().slot // where the speculative content went
|
||||
|
||||
val before = h.calls.size
|
||||
h.script.add(changed())
|
||||
val outcome = h.engine.service(last + 1_000_000, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
outcome as SpecRenderEngine.Outcome.Post
|
||||
assertFalse(outcome.specHit)
|
||||
assertTrue(outcome.newContent)
|
||||
assertEquals(before + 1, h.calls.size)
|
||||
assertEquals("miss must render into the slot holding libass's last content", specSlot, h.calls.last().slot)
|
||||
assertEquals(1L, h.engine.specMisses)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `miss with changed 0 posts the spec slot not stale screen content`() {
|
||||
// The trap: spec rendered NEW content (never posted); a mismatched request
|
||||
// then returns changed == 0 (identical to libass's LAST render = the spec
|
||||
// content). Posting "last posted" content would be stale — the engine must
|
||||
// post the slot libass last wrote.
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
val specSlot = h.calls.last().slot
|
||||
|
||||
h.script.add(unchanged())
|
||||
val outcome = h.engine.service(last + 200_000, pinned = true) // > ε, miss; estimator resets too
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
outcome as SpecRenderEngine.Outcome.Post
|
||||
assertFalse(outcome.specHit)
|
||||
assertFalse(outcome.newContent)
|
||||
assertEquals("changed==0 must repost libass's last-rendered slot", specSlot, outcome.slot)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `state generation change invalidates speculation`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
h.generation++ // margins/zoom/track switch between spec render and the request
|
||||
h.script.add(changed())
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(last + DELTA, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
assertEquals("stale spec must be re-rendered", before + 1, h.calls.size)
|
||||
assertEquals(1L, h.engine.specMisses)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unpinned requests never feed the estimator or speculate`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
// Paused invalidate-repaint at an arbitrary position.
|
||||
h.script.add(changed())
|
||||
h.engine.service(last, pinned = false)
|
||||
val specBefore = h.calls.size
|
||||
assertNull(h.engine.speculateAfter(last, pinned = false, hasPending = false))
|
||||
assertEquals("unpinned must not speculate", specBefore, h.calls.size)
|
||||
|
||||
// Cadence survives the unpinned request: the next pinned pair still hits.
|
||||
h.engine.service(last + DELTA, pinned = true)
|
||||
h.engine.speculateAfter(last + DELTA, pinned = true, hasPending = false)
|
||||
val outcome = h.engine.service(last + 2 * DELTA, pinned = true)
|
||||
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `speculation skipped while a request is pending`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
val before = h.calls.size
|
||||
|
||||
assertNull(h.engine.speculateAfter(last, pinned = true, hasPending = true))
|
||||
assertEquals(before, h.calls.size)
|
||||
assertTrue(h.engine.specSkips > 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no speculation until cadence is confident`() {
|
||||
val h = Harness()
|
||||
h.engine.service(0, pinned = true)
|
||||
// Only one delta sample so far (needs 4).
|
||||
h.engine.service(DELTA, pinned = true)
|
||||
val before = h.calls.size
|
||||
assertNull(h.engine.speculateAfter(DELTA, pinned = true, hasPending = false))
|
||||
assertEquals(before, h.calls.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `render target avoids posted and gl taken slots`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
val posted = first.slot
|
||||
|
||||
h.glTaken = (posted + 1) % 3
|
||||
h.script.add(changed())
|
||||
val second = h.engine.service(1_000_000, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
|
||||
val expected = (0 until 3).first { it != posted && it != h.glTaken }
|
||||
assertEquals(expected, second.slot)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `changed 0 before any content skips`() {
|
||||
val h = Harness()
|
||||
h.script.add(unchanged())
|
||||
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `renderer gone skips`() {
|
||||
val h = Harness()
|
||||
h.script.add(null)
|
||||
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two slot mode alternates and never speculates`() {
|
||||
val h = Harness(slotCount = 2, speculationEnabled = false)
|
||||
h.script.add(changed())
|
||||
val a = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertNull(h.engine.speculateAfter(0, pinned = true, hasPending = false))
|
||||
|
||||
h.script.add(changed())
|
||||
val b = h.engine.service(DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertTrue(a.slot != b.slot)
|
||||
assertTrue(a.slot in 0..1 && b.slot in 0..1)
|
||||
assertEquals(0, h.calls.count { it.slot >= 2 })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `static dialogue hit reposts the same slot without new content`() {
|
||||
// Spec render returns changed == 0 (nothing moves): a hit must repost the
|
||||
// last-rendered slot so GL skips the upload entirely.
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
var pts = 0L
|
||||
repeat(4) {
|
||||
// build cadence; renders return changed for simplicity
|
||||
pts += DELTA
|
||||
h.engine.service(pts, pinned = true)
|
||||
}
|
||||
h.script.add(unchanged()) // speculative render: nothing changes at pts+Δ
|
||||
assertNull(h.engine.speculateAfter(pts, pinned = true, hasPending = false))
|
||||
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(pts + DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertTrue(outcome.specHit)
|
||||
assertFalse(outcome.newContent)
|
||||
assertEquals(before, h.calls.size)
|
||||
assertNotNull(first) // first slot existed; hit reposts whichever slot was last rendered
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `speculative write reports slot for seq bump`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
h.script.add(changed())
|
||||
val write = h.engine.speculateAfter(last, pinned = true, hasPending = false)
|
||||
assertNotNull(write)
|
||||
assertEquals(h.calls.last().slot, write!!.slot)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `spec predicts pts plus median delta`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
h.script.add(changed())
|
||||
h.engine.speculateAfter(last, pinned = true, hasPending = false)
|
||||
assertEquals((last + DELTA) / 1000, h.calls.last().timeMs)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefetch renders the requested future pts and reports its slot`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
h.engine.service(0, pinned = true) // some content on screen
|
||||
|
||||
h.script.add(changed())
|
||||
val write = h.engine.prefetch(5_000_000)
|
||||
|
||||
assertNotNull(write)
|
||||
assertEquals(5_000L, h.calls.last().timeMs)
|
||||
assertEquals(h.calls.last().slot, write!!.slot)
|
||||
assertEquals(1L, h.engine.prefetchCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefetch invalidates pending speculation`() {
|
||||
// Prefetch rewrites libass's last-rendered content (and possibly the spec
|
||||
// slot itself); a stale spec hit would post future-event content.
|
||||
val h = Harness()
|
||||
val last = h.prime() // leaves a valid spec for last+Δ
|
||||
|
||||
h.script.add(changed())
|
||||
h.engine.prefetch(last + 5_000_000)
|
||||
|
||||
val before = h.calls.size
|
||||
h.script.add(changed())
|
||||
val outcome = h.engine.service(last + DELTA, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
assertEquals("post-prefetch request must render on demand", before + 1, h.calls.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `render after prefetch with changed 0 posts the prefetched slot`() {
|
||||
// changed==0 after a prefetch means "identical to libass's last render" =
|
||||
// the prefetched content — correct exactly when playback reached the
|
||||
// prefetched event. The engine must post that slot, not older content.
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
h.engine.service(0, pinned = true)
|
||||
|
||||
h.script.add(changed())
|
||||
val write = h.engine.prefetch(5_000_000)!!
|
||||
|
||||
h.script.add(unchanged())
|
||||
val outcome = h.engine.service(5_000_000, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertEquals(write.slot, outcome.slot)
|
||||
assertFalse(outcome.newContent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefetch avoids posted and gl taken slots`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val posted = (h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post).slot
|
||||
h.glTaken = (posted + 1) % 3
|
||||
|
||||
h.script.add(changed())
|
||||
val write = h.engine.prefetch(5_000_000)
|
||||
|
||||
val expected = (0 until 3).first { it != posted && it != h.glTaken }
|
||||
assertEquals(expected, write!!.slot)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,11 @@ pluginManagement {
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "8.9.1" apply false
|
||||
id("com.android.library") version "8.9.1" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
|
||||
}
|
||||
|
||||
include(":app")
|
||||
// libass subtitle module (Kotlin/JNI bindings + Media3 glue); the native libass
|
||||
// core stays the upstream Maven artifact io.github.peerless2012:ass.
|
||||
include(":libass")
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<svg viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
|
||||
<path d="M24.2116 49.1581C22.6599 46.0424 32.8378 27.5879 35.9999 27.5879C39.1666 27.5895 49.3228 46.0764 47.7882 49.1581C46.2536 52.2398 25.7632 52.2738 24.2116 49.1581Z"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M0.481861 64.9951C-4.19479 55.6047 26.4765 0 36 0C45.5328 0 76.153 55.713 71.5274 64.9951C66.9018 74.2773 5.15852 74.3856 0.481861 64.9951ZM12.7358 56.847C15.8005 62.9995 56.2536 62.9314 59.2843 56.847C62.3149 50.761 42.2515 14.2605 36.0093 14.2605C29.767 14.2605 9.67118 50.6944 12.7358 56.847Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 614 B |
@@ -0,0 +1,3 @@
|
||||
<svg viewBox="636.71 89.58 269.72 269.72" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
|
||||
<path d="M774.47 359.3H677.74L768.67 224.5L677.74 89.58H774.47L865.4 224.5L774.47 359.3Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 199 B |
|
After Width: | Height: | Size: 121 KiB |
@@ -1,15 +0,0 @@
|
||||
## iOS
|
||||
|
||||
| Home | Library | Media Card | Season |
|
||||
|------|---------|------------|--------|
|
||||
|  |  |  |  |
|
||||
|
||||
## macOS
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
Before Width: | Height: | Size: 3.8 MiB |
|
Before Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 2.6 MiB |
|
Before Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 4.4 MiB |
|
Before Width: | Height: | Size: 3.4 MiB |
|
Before Width: | Height: | Size: 3.0 MiB |
|
Before Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,17 @@
|
||||
targets:
|
||||
$default:
|
||||
builders:
|
||||
json_serializable:
|
||||
options:
|
||||
create_to_json: true
|
||||
explicit_to_json: true
|
||||
field_rename: none
|
||||
include_if_null: true
|
||||
checked: false
|
||||
freezed:
|
||||
options:
|
||||
copy_with: true
|
||||
equal: true
|
||||
to_string: true
|
||||
slang_build_runner:
|
||||
enabled: false
|
||||
@@ -1,141 +1,34 @@
|
||||
PODS:
|
||||
- background_downloader (0.0.1):
|
||||
- Flutter
|
||||
- connectivity_plus (0.0.1):
|
||||
- Flutter
|
||||
- cupertino_http (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- device_info_plus (0.0.1):
|
||||
- Flutter
|
||||
- file_picker (0.0.1):
|
||||
- Flutter
|
||||
- Flutter (1.0.0)
|
||||
- in_app_review (2.0.0):
|
||||
- os_media_controls (0.2.4):
|
||||
- Flutter
|
||||
- os_media_controls (0.0.1):
|
||||
- Flutter
|
||||
- package_info_plus (0.4.5):
|
||||
- Flutter
|
||||
- Sentry/HybridSDK (8.58.0)
|
||||
- sentry_flutter (9.16.0):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- Sentry/HybridSDK (= 8.58.0)
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqflite_darwin (0.0.4):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqlite3 (3.52.0):
|
||||
- sqlite3/common (= 3.52.0)
|
||||
- sqlite3/common (3.52.0)
|
||||
- sqlite3/dbstatvtab (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/fts5 (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/math (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/perf-threadsafe (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/rtree (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/session (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3_flutter_libs (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqlite3 (~> 3.52.0)
|
||||
- sqlite3/dbstatvtab
|
||||
- sqlite3/fts5
|
||||
- sqlite3/math
|
||||
- sqlite3/perf-threadsafe
|
||||
- sqlite3/rtree
|
||||
- sqlite3/session
|
||||
- universal_gamepad (0.1.0):
|
||||
- Flutter
|
||||
- url_launcher_ios (0.0.1):
|
||||
- Flutter
|
||||
- wakelock_plus (0.0.1):
|
||||
- Flutter
|
||||
|
||||
DEPENDENCIES:
|
||||
- background_downloader (from `.symlinks/plugins/background_downloader/ios`)
|
||||
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
|
||||
- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)
|
||||
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
|
||||
- file_picker (from `.symlinks/plugins/file_picker/ios`)
|
||||
- Flutter (from `Flutter`)
|
||||
- in_app_review (from `.symlinks/plugins/in_app_review/ios`)
|
||||
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
|
||||
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
|
||||
- sentry_flutter (from `.symlinks/plugins/sentry_flutter/ios`)
|
||||
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`)
|
||||
- sqlite3_flutter_libs (from `.symlinks/plugins/sqlite3_flutter_libs/darwin`)
|
||||
- universal_gamepad (from `.symlinks/plugins/universal_gamepad/ios`)
|
||||
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
|
||||
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- Sentry
|
||||
- sqlite3
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
background_downloader:
|
||||
:path: ".symlinks/plugins/background_downloader/ios"
|
||||
connectivity_plus:
|
||||
:path: ".symlinks/plugins/connectivity_plus/ios"
|
||||
cupertino_http:
|
||||
:path: ".symlinks/plugins/cupertino_http/darwin"
|
||||
device_info_plus:
|
||||
:path: ".symlinks/plugins/device_info_plus/ios"
|
||||
file_picker:
|
||||
:path: ".symlinks/plugins/file_picker/ios"
|
||||
Flutter:
|
||||
:path: Flutter
|
||||
in_app_review:
|
||||
:path: ".symlinks/plugins/in_app_review/ios"
|
||||
os_media_controls:
|
||||
:path: ".symlinks/plugins/os_media_controls/ios"
|
||||
package_info_plus:
|
||||
:path: ".symlinks/plugins/package_info_plus/ios"
|
||||
sentry_flutter:
|
||||
:path: ".symlinks/plugins/sentry_flutter/ios"
|
||||
shared_preferences_foundation:
|
||||
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
|
||||
sqflite_darwin:
|
||||
:path: ".symlinks/plugins/sqflite_darwin/darwin"
|
||||
sqlite3_flutter_libs:
|
||||
:path: ".symlinks/plugins/sqlite3_flutter_libs/darwin"
|
||||
universal_gamepad:
|
||||
:path: ".symlinks/plugins/universal_gamepad/ios"
|
||||
url_launcher_ios:
|
||||
:path: ".symlinks/plugins/url_launcher_ios/ios"
|
||||
wakelock_plus:
|
||||
:path: ".symlinks/plugins/wakelock_plus/ios"
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
background_downloader: 50e91d979067b82081aba359d7d916b3ba5fadad
|
||||
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
|
||||
cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
|
||||
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
|
||||
file_picker: 8fc6fe5e42585a217d44d22f79ec046cb8d81140
|
||||
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
|
||||
in_app_review: 7dd1ea365263f834b8464673f9df72c80c17c937
|
||||
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
|
||||
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
|
||||
Sentry: d587a8fe91ca13503ecd69a1905f3e8a0fcf61be
|
||||
sentry_flutter: 31101687061fb85211ebab09ce6eb8db4e9ba74f
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
||||
sqlite3: a51c07cf16e023d6c48abd5e5791a61a47354921
|
||||
sqlite3_flutter_libs: b3e120efe9a82017e5552a620f696589ed4f62ab
|
||||
universal_gamepad: e10172778a8a399cce234494968f38724974919e
|
||||
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
|
||||
wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
|
||||
os_media_controls: 048eb9a75974191b2496d85575b6edcefc572d4e
|
||||
universal_gamepad: 838bbb70d37d8c7c719038aa397214f2c4c4f866
|
||||
|
||||
PODFILE CHECKSUM: 16bb7f67e16d8aaa2bfb97666803fbfb291b6559
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@
|
||||
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
|
||||
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */; };
|
||||
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */; };
|
||||
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */; };
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -73,9 +75,11 @@
|
||||
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvPlayerCoreBase.swift; path = ../shared/apple/MpvPlayer/MpvPlayerCoreBase.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvPlayerPluginShared.swift; path = ../shared/apple/MpvPlayer/MpvPlayerPluginShared.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalDisplayManager.swift; sourceTree = "<group>"; };
|
||||
BB346A1D0705AB171F80B11B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
DE48FF2E074644167608B23D /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
|
||||
F3553CDE70191F0FC81A782E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -91,6 +95,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
|
||||
6A8A46212EDB320D0057B88C /* MPVKit in Frameworks */,
|
||||
69E1B4BB161DC9D84D1DFC62 /* Pods_Runner.framework in Frameworks */,
|
||||
);
|
||||
@@ -121,6 +126,7 @@
|
||||
children = (
|
||||
B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */,
|
||||
B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */,
|
||||
B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */,
|
||||
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */,
|
||||
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */,
|
||||
92F969587D0E464D999910F4 /* MpvPipController.swift */,
|
||||
@@ -144,6 +150,7 @@
|
||||
9740EEB11CF90186004384FC /* Flutter */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,
|
||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
|
||||
9740EEB21CF90195004384FC /* Debug.xcconfig */,
|
||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
|
||||
@@ -212,6 +219,9 @@
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
97C146ED1CF9000F007C117D /* Runner */ = {
|
||||
packageProductDependencies = (
|
||||
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
|
||||
);
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
|
||||
buildPhases = (
|
||||
@@ -263,6 +273,7 @@
|
||||
);
|
||||
mainGroup = 97C146E51CF9000F007C117D;
|
||||
packageReferences = (
|
||||
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,
|
||||
6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */,
|
||||
);
|
||||
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
|
||||
@@ -406,6 +417,7 @@
|
||||
files = (
|
||||
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */,
|
||||
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */,
|
||||
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */,
|
||||
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */,
|
||||
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */,
|
||||
92F969587D0E464D999910F5 /* MpvPipController.swift in Sources */,
|
||||
@@ -777,7 +789,7 @@
|
||||
repositoryURL = "https://github.com/edde746/MPVKit";
|
||||
requirement = {
|
||||
kind = revision;
|
||||
revision = 29803ccbfa631997d496f34c2c1ed191cc8fd2c3;
|
||||
revision = 245b69dce22156e81b79c84cfcb748358b674e47;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
@@ -788,7 +800,17 @@
|
||||
package = 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */;
|
||||
productName = MPVKit;
|
||||
};
|
||||
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = FlutterGeneratedPluginSwiftPackage;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
};
|
||||
rootObject = 97C146E61CF9000F007C117D /* Project object */;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,84 @@
|
||||
{
|
||||
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "csqlite",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/simolus3/CSQLite.git",
|
||||
"state" : {
|
||||
"revision" : "1ee46d19a4f451a7aa64ffc64fc99b4748131e62"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkcamera",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKCamera",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "5c691d11014b910aff69f960475d70e65d9dcc96"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkimagepickercontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKImagePickerController",
|
||||
"state" : {
|
||||
"branch" : "4.3.9",
|
||||
"revision" : "0bdfeacefa308545adde07bef86e349186335915"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkphotogallery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKPhotoGallery",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "mpvkit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "29803ccbfa631997d496f34c2c1ed191cc8fd2c3"
|
||||
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sdwebimage",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/SDWebImage/SDWebImage",
|
||||
"state" : {
|
||||
"revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0",
|
||||
"version" : "5.21.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sentry-cocoa",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/getsentry/sentry-cocoa",
|
||||
"state" : {
|
||||
"revision" : "16cd512711375fa73f25ae5e373f596bdf4251ae",
|
||||
"version" : "8.58.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftygif",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/kirualex/SwiftyGif.git",
|
||||
"state" : {
|
||||
"revision" : "4430cbc148baa3907651d40562d96325426f409a",
|
||||
"version" : "5.4.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "tocropviewcontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/TimOliver/TOCropViewController",
|
||||
"state" : {
|
||||
"revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e",
|
||||
"version" : "2.8.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
"version" : 2
|
||||
}
|
||||
|
||||
@@ -5,6 +5,24 @@
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<PreActions>
|
||||
<ExecutionAction
|
||||
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
|
||||
<ActionContent
|
||||
title = "Run Prepare Flutter Framework Script"
|
||||
scriptText = "/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" prepare ">
|
||||
<EnvironmentBuildable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
|
||||
BuildableName = "Runner.app"
|
||||
BlueprintName = "Runner"
|
||||
ReferencedContainer = "container:Runner.xcodeproj">
|
||||
</BuildableReference>
|
||||
</EnvironmentBuildable>
|
||||
</ActionContent>
|
||||
</ExecutionAction>
|
||||
</PreActions>
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
|
||||
@@ -1,14 +1,84 @@
|
||||
{
|
||||
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "csqlite",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/simolus3/CSQLite.git",
|
||||
"state" : {
|
||||
"revision" : "1ee46d19a4f451a7aa64ffc64fc99b4748131e62"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkcamera",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKCamera",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "5c691d11014b910aff69f960475d70e65d9dcc96"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkimagepickercontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKImagePickerController",
|
||||
"state" : {
|
||||
"branch" : "4.3.9",
|
||||
"revision" : "0bdfeacefa308545adde07bef86e349186335915"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkphotogallery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKPhotoGallery",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "mpvkit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "29803ccbfa631997d496f34c2c1ed191cc8fd2c3"
|
||||
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sdwebimage",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/SDWebImage/SDWebImage",
|
||||
"state" : {
|
||||
"revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0",
|
||||
"version" : "5.21.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sentry-cocoa",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/getsentry/sentry-cocoa",
|
||||
"state" : {
|
||||
"revision" : "16cd512711375fa73f25ae5e373f596bdf4251ae",
|
||||
"version" : "8.58.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftygif",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/kirualex/SwiftyGif.git",
|
||||
"state" : {
|
||||
"revision" : "4430cbc148baa3907651d40562d96325426f409a",
|
||||
"version" : "5.4.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "tocropviewcontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/TimOliver/TOCropViewController",
|
||||
"state" : {
|
||||
"revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e",
|
||||
"version" : "2.8.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
"version" : 2
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import Flutter
|
||||
import UIKit
|
||||
import AVFoundation
|
||||
import MediaPlayer
|
||||
|
||||
@main
|
||||
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
||||
private var deviceAdjustmentChannel: FlutterMethodChannel?
|
||||
private var originalBrightness: CGFloat?
|
||||
private var volumeView: MPVolumeView?
|
||||
private weak var volumeSlider: UISlider?
|
||||
|
||||
override func application(
|
||||
_ application: UIApplication,
|
||||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
|
||||
@@ -29,5 +35,119 @@ import AVFoundation
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "MpvPlayerPlugin") {
|
||||
MpvPlayerPlugin.register(with: registrar)
|
||||
}
|
||||
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "DeviceAdjustmentChannel") {
|
||||
registerDeviceAdjustmentChannel(messenger: registrar.messenger())
|
||||
}
|
||||
}
|
||||
|
||||
private func registerDeviceAdjustmentChannel(messenger: FlutterBinaryMessenger) {
|
||||
let channel = FlutterMethodChannel(name: "com.plezy/device_adjustment", binaryMessenger: messenger)
|
||||
channel.setMethodCallHandler { [weak self] call, result in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleDeviceAdjustmentCall(call, result: result)
|
||||
}
|
||||
}
|
||||
deviceAdjustmentChannel = channel
|
||||
}
|
||||
|
||||
private func handleDeviceAdjustmentCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
switch call.method {
|
||||
case "getBrightness":
|
||||
result(Double(UIScreen.main.brightness))
|
||||
case "setBrightness":
|
||||
guard let value = normalizedArgument(call.arguments, result: result) else { return }
|
||||
if originalBrightness == nil {
|
||||
originalBrightness = UIScreen.main.brightness
|
||||
}
|
||||
UIScreen.main.brightness = CGFloat(value)
|
||||
result(nil)
|
||||
case "restoreBrightness":
|
||||
if let originalBrightness = originalBrightness {
|
||||
UIScreen.main.brightness = originalBrightness
|
||||
self.originalBrightness = nil
|
||||
}
|
||||
result(nil)
|
||||
case "getMediaVolume":
|
||||
result(Double(AVAudioSession.sharedInstance().outputVolume))
|
||||
case "setMediaVolume":
|
||||
guard let value = normalizedArgument(call.arguments, result: result) else { return }
|
||||
if setMediaVolume(value) {
|
||||
result(nil)
|
||||
} else {
|
||||
result(
|
||||
FlutterError(code: "DEVICE_ADJUSTMENT_UNAVAILABLE", message: "System volume slider unavailable", details: nil)
|
||||
)
|
||||
}
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
|
||||
private func normalizedArgument(_ arguments: Any?, result: @escaping FlutterResult) -> Double? {
|
||||
guard let value = arguments as? NSNumber else {
|
||||
result(FlutterError(code: "INVALID_ARGUMENT", message: "Expected a numeric value", details: nil))
|
||||
return nil
|
||||
}
|
||||
let doubleValue = value.doubleValue
|
||||
guard doubleValue.isFinite else {
|
||||
result(FlutterError(code: "INVALID_ARGUMENT", message: "Expected a finite numeric value", details: nil))
|
||||
return nil
|
||||
}
|
||||
return min(1.0, max(0.0, doubleValue))
|
||||
}
|
||||
|
||||
private func setMediaVolume(_ value: Double) -> Bool {
|
||||
guard let slider = ensureVolumeSlider() else { return false }
|
||||
slider.setValue(Float(value), animated: false)
|
||||
slider.sendActions(for: .valueChanged)
|
||||
slider.sendActions(for: .touchUpInside)
|
||||
return true
|
||||
}
|
||||
|
||||
private func ensureVolumeSlider() -> UISlider? {
|
||||
if let volumeSlider = volumeSlider { return volumeSlider }
|
||||
|
||||
let volumeView = self.volumeView ?? MPVolumeView(frame: CGRect(x: -1000, y: -1000, width: 1, height: 1))
|
||||
volumeView.showsRouteButton = false
|
||||
volumeView.showsVolumeSlider = true
|
||||
volumeView.alpha = 0.01
|
||||
volumeView.isUserInteractionEnabled = false
|
||||
|
||||
if volumeView.superview == nil {
|
||||
activeWindow?.addSubview(volumeView)
|
||||
}
|
||||
volumeView.layoutIfNeeded()
|
||||
|
||||
self.volumeView = volumeView
|
||||
let slider = findVolumeSlider(in: volumeView)
|
||||
volumeSlider = slider
|
||||
return slider
|
||||
}
|
||||
|
||||
private func findVolumeSlider(in view: UIView) -> UISlider? {
|
||||
if let slider = view as? UISlider { return slider }
|
||||
for subview in view.subviews {
|
||||
if let slider = findVolumeSlider(in: subview) { return slider }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private var activeWindow: UIWindow? {
|
||||
if #available(iOS 13.0, *) {
|
||||
for scene in UIApplication.shared.connectedScenes {
|
||||
guard let windowScene = scene as? UIWindowScene else { continue }
|
||||
if let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow }) {
|
||||
return keyWindow
|
||||
}
|
||||
}
|
||||
for scene in UIApplication.shared.connectedScenes {
|
||||
guard let windowScene = scene as? UIWindowScene, let window = windowScene.windows.first else { continue }
|
||||
return window
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return UIApplication.shared.windows.first(where: { $0.isKeyWindow }) ?? UIApplication.shared.windows.first
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : {
|
||||
"alpha" : "1.000",
|
||||
"blue" : "0xF8",
|
||||
"green" : "0xF7",
|
||||
"red" : "0xF7"
|
||||
}
|
||||
},
|
||||
"idiom" : "universal"
|
||||
},
|
||||
{
|
||||
"appearances" : [
|
||||
{
|
||||
"appearance" : "luminosity",
|
||||
"value" : "dark"
|
||||
}
|
||||
],
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : {
|
||||
"alpha" : "1.000",
|
||||
"blue" : "0x12",
|
||||
"green" : "0x0F",
|
||||
"red" : "0x0E"
|
||||
}
|
||||
},
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
|
||||
<capability name="Named colors" minToolsVersion="9.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--View Controller-->
|
||||
@@ -19,7 +20,7 @@
|
||||
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
|
||||
</imageView>
|
||||
</subviews>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<color key="backgroundColor" name="LaunchBackground"/>
|
||||
<constraints>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
|
||||
@@ -33,5 +34,8 @@
|
||||
</scenes>
|
||||
<resources>
|
||||
<image name="LaunchImage" width="168" height="185"/>
|
||||
<namedColor name="LaunchBackground">
|
||||
<color red="0.96862745098039216" green="0.96862745098039216" blue="0.97254901960784312" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</namedColor>
|
||||
</resources>
|
||||
</document>
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(FLUTTER_BUILD_NUMBER)</string>
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
<false/>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
@@ -33,12 +35,12 @@
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>NSBonjourServices</key>
|
||||
<array>
|
||||
<string>_plexmediasvr._tcp</string>
|
||||
</array>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>This app needs to connect to your Plex Media Server on your local network.</string>
|
||||
<string>This app needs to connect to your media servers on your local network.</string>
|
||||
<key>NSLocationWhenInUseUsageDescription</key>
|
||||
<string>Plezy uses location access when iOS requires it to detect your local network and connect to your media servers.</string>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
<string>Plezy needs photo library access so you can choose images to upload as media artwork.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Camera is used to scan QR codes for Companion Remote pairing.</string>
|
||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||
@@ -70,7 +72,7 @@
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
<false/>
|
||||
<true/>
|
||||
<key>UISceneConfigurations</key>
|
||||
<dict>
|
||||
<key>UIWindowSceneSessionRoleApplication</key>
|
||||
@@ -86,6 +88,28 @@
|
||||
<string>Main</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>UIWindowSceneSessionRoleExternalDisplay</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UISceneClassName</key>
|
||||
<string>UIWindowScene</string>
|
||||
<key>UISceneDelegateClassName</key>
|
||||
<string>$(PRODUCT_MODULE_NAME).ExternalDisplaySceneDelegate</string>
|
||||
<key>UISceneConfigurationName</key>
|
||||
<string>external-display</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>UIWindowSceneSessionRoleExternalDisplayNonInteractive</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UISceneClassName</key>
|
||||
<string>UIWindowScene</string>
|
||||
<key>UISceneDelegateClassName</key>
|
||||
<string>$(PRODUCT_MODULE_NAME).ExternalDisplaySceneDelegate</string>
|
||||
<key>UISceneConfigurationName</key>
|
||||
<string>external-display</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import UIKit
|
||||
|
||||
final class ExternalDisplayManager {
|
||||
static let shared = ExternalDisplayManager()
|
||||
|
||||
private weak var activeCore: MpvPlayerCore?
|
||||
private var externalScene: UIWindowScene?
|
||||
private var externalWindow: UIWindow?
|
||||
private var externalRootViewController: UIViewController?
|
||||
|
||||
private init() {}
|
||||
|
||||
static func isExternalDisplayRole(_ role: UISceneSession.Role) -> Bool {
|
||||
role.rawValue == "UIWindowSceneSessionRoleExternalDisplay"
|
||||
|| role.rawValue == "UIWindowSceneSessionRoleExternalDisplayNonInteractive"
|
||||
}
|
||||
|
||||
static var hasActiveApplicationScene: Bool {
|
||||
applicationWindowScenes.contains { $0.activationState == .foregroundActive }
|
||||
}
|
||||
|
||||
static func mainApplicationWindow() -> UIWindow? {
|
||||
let scenes = applicationWindowScenes.sorted {
|
||||
scenePriority($0.activationState) < scenePriority($1.activationState)
|
||||
}
|
||||
|
||||
for scene in scenes {
|
||||
if let window = scene.windows.first(where: { $0.isKeyWindow }) {
|
||||
return window
|
||||
}
|
||||
}
|
||||
|
||||
for scene in scenes {
|
||||
if let window = scene.windows.first(where: { !$0.isHidden }) {
|
||||
return window
|
||||
}
|
||||
}
|
||||
|
||||
return scenes.first?.windows.first
|
||||
}
|
||||
|
||||
private static var applicationWindowScenes: [UIWindowScene] {
|
||||
UIApplication.shared.connectedScenes.compactMap { scene in
|
||||
guard let windowScene = scene as? UIWindowScene,
|
||||
!isExternalDisplayRole(windowScene.session.role)
|
||||
else { return nil }
|
||||
return windowScene
|
||||
}
|
||||
}
|
||||
|
||||
private static func scenePriority(_ state: UIScene.ActivationState) -> Int {
|
||||
switch state {
|
||||
case .foregroundActive:
|
||||
return 0
|
||||
case .foregroundInactive:
|
||||
return 1
|
||||
case .background:
|
||||
return 2
|
||||
case .unattached:
|
||||
return 3
|
||||
@unknown default:
|
||||
return 4
|
||||
}
|
||||
}
|
||||
|
||||
var videoSuperview: UIView? {
|
||||
externalRootViewController?.view
|
||||
}
|
||||
|
||||
func attach(core: MpvPlayerCore) {
|
||||
activeCore = core
|
||||
discoverExistingExternalScene()
|
||||
activeCore?.externalDisplayDidChange()
|
||||
}
|
||||
|
||||
func detach(core: MpvPlayerCore) {
|
||||
if activeCore === core {
|
||||
activeCore = nil
|
||||
}
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func connect(scene: UIWindowScene) -> UIWindow? {
|
||||
guard Self.isExternalDisplayRole(scene.session.role) else { return nil }
|
||||
|
||||
externalScene = scene
|
||||
let window = ensureWindow(for: scene)
|
||||
activeCore?.externalDisplayDidChange()
|
||||
print("[ExternalDisplayManager] External display connected")
|
||||
return window
|
||||
}
|
||||
|
||||
func disconnect(scene: UIScene) {
|
||||
guard scene === externalScene else { return }
|
||||
|
||||
externalWindow?.isHidden = true
|
||||
externalWindow = nil
|
||||
externalRootViewController = nil
|
||||
externalScene = nil
|
||||
activeCore?.externalDisplayDidChange()
|
||||
print("[ExternalDisplayManager] External display disconnected")
|
||||
}
|
||||
|
||||
func update(scene: UIWindowScene) {
|
||||
guard scene === externalScene else { return }
|
||||
externalRootViewController?.view.frame = scene.coordinateSpace.bounds
|
||||
activeCore?.externalDisplayDidChange()
|
||||
}
|
||||
|
||||
private func discoverExistingExternalScene() {
|
||||
guard externalScene == nil else { return }
|
||||
|
||||
for scene in UIApplication.shared.connectedScenes {
|
||||
guard let windowScene = scene as? UIWindowScene,
|
||||
Self.isExternalDisplayRole(windowScene.session.role)
|
||||
else { continue }
|
||||
_ = connect(scene: windowScene)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func ensureWindow(for scene: UIWindowScene) -> UIWindow {
|
||||
if let existing = externalWindow, existing.windowScene === scene {
|
||||
return existing
|
||||
}
|
||||
|
||||
externalWindow?.isHidden = true
|
||||
|
||||
let rootViewController = UIViewController()
|
||||
rootViewController.view.frame = scene.coordinateSpace.bounds
|
||||
rootViewController.view.backgroundColor = .black
|
||||
|
||||
let window = UIWindow(windowScene: scene)
|
||||
window.rootViewController = rootViewController
|
||||
window.backgroundColor = .black
|
||||
window.isHidden = false
|
||||
|
||||
externalRootViewController = rootViewController
|
||||
externalWindow = window
|
||||
return window
|
||||
}
|
||||
}
|
||||
|
||||
class ExternalDisplaySceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func scene(
|
||||
_ scene: UIScene,
|
||||
willConnectTo session: UISceneSession,
|
||||
options connectionOptions: UIScene.ConnectionOptions
|
||||
) {
|
||||
guard let windowScene = scene as? UIWindowScene,
|
||||
ExternalDisplayManager.isExternalDisplayRole(session.role)
|
||||
else { return }
|
||||
|
||||
window = ExternalDisplayManager.shared.connect(scene: windowScene)
|
||||
}
|
||||
|
||||
func sceneDidDisconnect(_ scene: UIScene) {
|
||||
ExternalDisplayManager.shared.disconnect(scene: scene)
|
||||
window = nil
|
||||
}
|
||||
|
||||
func windowScene(
|
||||
_ windowScene: UIWindowScene,
|
||||
didUpdate previousCoordinateSpace: UICoordinateSpace,
|
||||
interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation,
|
||||
traitCollection previousTraitCollection: UITraitCollection
|
||||
) {
|
||||
ExternalDisplayManager.shared.update(scene: windowScene)
|
||||
}
|
||||
}
|
||||
@@ -1,49 +1,44 @@
|
||||
import AVFoundation
|
||||
import AVKit
|
||||
import UIKit
|
||||
|
||||
#if os(tvOS)
|
||||
// tvOS stub: AVPictureInPictureController has different constraints on tvOS
|
||||
// and is not supported by the Plezy flow. Provide a no-op shell so callers
|
||||
// in MpvPlayerPlugin compile unchanged; isSupported reports false so PiP is
|
||||
// never attempted at runtime.
|
||||
protocol MpvPipDelegate: AnyObject {
|
||||
// tvOS stub: AVPictureInPictureController has different constraints on tvOS
|
||||
// and is not supported by the Plezy flow. Provide a no-op shell so callers
|
||||
// in MpvPlayerPlugin compile unchanged; isSupported reports false so PiP is
|
||||
// never attempted at runtime.
|
||||
protocol MpvPipDelegate: AnyObject {
|
||||
func pipWillStart()
|
||||
func pipDidStart()
|
||||
func pipDidStop(restored: Bool)
|
||||
func pipDidFailToStart(error: Error?)
|
||||
func pipSetPlaying(_ playing: Bool)
|
||||
func pipSkip(byInterval seconds: Double)
|
||||
func pipSkip(byInterval seconds: Double, completion: @escaping () -> Void)
|
||||
var isPipPlaying: Bool { get }
|
||||
var pipDuration: Double { get }
|
||||
}
|
||||
}
|
||||
|
||||
class MpvPipController: NSObject {
|
||||
class MpvPipController: NSObject {
|
||||
static var isSupported: Bool { false }
|
||||
weak var delegate: MpvPipDelegate?
|
||||
var isPipActive: Bool { false }
|
||||
var autoStartEnabled: Bool { false }
|
||||
var layerPointer: UnsafeMutableRawPointer {
|
||||
// Return a dummy non-null pointer — layerPointer is handed to mpv for
|
||||
// rendering into PiP, which never activates on tvOS.
|
||||
UnsafeMutableRawPointer(bitPattern: 0x1)!
|
||||
}
|
||||
init(sampleBufferDisplayLayer: AVSampleBufferDisplayLayer) { super.init() }
|
||||
func setup(with layer: CALayer, containerView: UIView) {}
|
||||
func setAutoStart(_ enabled: Bool) {}
|
||||
func warmLayer(currentTime: Double, isPlaying: Bool) {}
|
||||
func pushBlankFrame(width: Int32 = 1920, height: Int32 = 1080) {}
|
||||
func startPip(waitForFrame: Bool = true, completion: @escaping (Bool) -> Void) {
|
||||
completion(false)
|
||||
completion(false)
|
||||
}
|
||||
func stopPip() {}
|
||||
func invalidatePlaybackState() {}
|
||||
func flushLayer() {}
|
||||
func syncTimebase(currentTime: Double, isPlaying: Bool) {}
|
||||
func teardown() {}
|
||||
}
|
||||
}
|
||||
#else
|
||||
|
||||
/// Delegate to notify the plugin of PiP lifecycle events
|
||||
protocol MpvPipDelegate: AnyObject {
|
||||
/// Delegate to notify the plugin of PiP lifecycle events
|
||||
protocol MpvPipDelegate: AnyObject {
|
||||
/// Called when PiP is about to start (system or app-initiated)
|
||||
func pipWillStart()
|
||||
func pipDidStart()
|
||||
@@ -53,360 +48,258 @@ protocol MpvPipDelegate: AnyObject {
|
||||
/// Forward play/pause commands from PiP overlay to mpv
|
||||
func pipSetPlaying(_ playing: Bool)
|
||||
/// Forward skip forward/backward commands from PiP overlay to mpv
|
||||
func pipSkip(byInterval seconds: Double)
|
||||
func pipSkip(byInterval seconds: Double, completion: @escaping () -> Void)
|
||||
/// Query whether mpv is currently playing
|
||||
var isPipPlaying: Bool { get }
|
||||
/// Get total duration in seconds
|
||||
var pipDuration: Double { get }
|
||||
}
|
||||
}
|
||||
|
||||
/// Encapsulates all iOS Picture-in-Picture logic using AVSampleBufferDisplayLayer.
|
||||
/// Requires iOS 15+ for the ContentSource API; on older versions, `setup()` is a no-op.
|
||||
class MpvPipController: NSObject {
|
||||
/// Encapsulates all iOS Picture-in-Picture logic using AVSampleBufferDisplayLayer.
|
||||
/// Requires iOS 15+ for the ContentSource API; on older versions, `setup()` is a no-op.
|
||||
class MpvPipController: NSObject {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private var pipController: AVPictureInPictureController?
|
||||
private let sampleBufferLayer = AVSampleBufferDisplayLayer()
|
||||
private var containerView: UIView?
|
||||
private weak var sampleBufferLayer: AVSampleBufferDisplayLayer?
|
||||
weak var delegate: MpvPipDelegate?
|
||||
|
||||
/// Pointer to the sample buffer layer for passing to mpv as `wid`
|
||||
var layerPointer: UnsafeMutableRawPointer {
|
||||
Unmanaged.passUnretained(sampleBufferLayer).toOpaque()
|
||||
}
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
setup()
|
||||
init(sampleBufferDisplayLayer: AVSampleBufferDisplayLayer) {
|
||||
self.sampleBufferLayer = sampleBufferDisplayLayer
|
||||
super.init()
|
||||
setup()
|
||||
}
|
||||
|
||||
private func setup() {
|
||||
guard #available(iOS 15.0, *) else { return }
|
||||
guard #available(iOS 15.0, *) else { return }
|
||||
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
} catch {
|
||||
print("[MpvPipController] Failed to configure audio session: \(error)")
|
||||
}
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
} catch {
|
||||
print("[MpvPipController] Failed to configure audio session: \(error)")
|
||||
}
|
||||
|
||||
// The sample buffer layer must be in a visible view hierarchy for
|
||||
// isPictureInPicturePossible to become true.
|
||||
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
|
||||
let window = windowScene.windows.first(where: { $0.isKeyWindow }) {
|
||||
let view = UIView(frame: window.bounds)
|
||||
view.clipsToBounds = true
|
||||
view.isUserInteractionEnabled = false
|
||||
sampleBufferLayer.frame = view.bounds
|
||||
view.layer.addSublayer(sampleBufferLayer)
|
||||
window.addSubview(view)
|
||||
containerView = view
|
||||
}
|
||||
|
||||
createPipController()
|
||||
createPipController()
|
||||
}
|
||||
|
||||
/// Helper that conforms to the iOS 15+ delegate protocols
|
||||
private var delegateHelper: AnyObject?
|
||||
|
||||
private func createPipController() {
|
||||
guard #available(iOS 15.0, *) else { return }
|
||||
let helper = PipDelegateHelper(controller: self)
|
||||
let contentSource = AVPictureInPictureController.ContentSource(
|
||||
sampleBufferDisplayLayer: sampleBufferLayer,
|
||||
playbackDelegate: helper
|
||||
)
|
||||
self.delegateHelper = helper
|
||||
pipController = AVPictureInPictureController(contentSource: contentSource)
|
||||
pipController?.delegate = helper
|
||||
if #available(iOS 14.2, *) {
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = false
|
||||
}
|
||||
guard #available(iOS 15.0, *), let sampleBufferLayer else { return }
|
||||
let helper = PipDelegateHelper(controller: self)
|
||||
let contentSource = AVPictureInPictureController.ContentSource(
|
||||
sampleBufferDisplayLayer: sampleBufferLayer,
|
||||
playbackDelegate: helper
|
||||
)
|
||||
self.delegateHelper = helper
|
||||
pipController = AVPictureInPictureController(contentSource: contentSource)
|
||||
pipController?.delegate = helper
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = false
|
||||
}
|
||||
|
||||
/// Enable/disable system auto-PiP (starts PiP automatically on background transition)
|
||||
func setAutoStart(_ enabled: Bool) {
|
||||
guard #available(iOS 14.2, *) else { return }
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = enabled
|
||||
guard #available(iOS 14.2, *) else { return }
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = enabled
|
||||
}
|
||||
|
||||
/// Push a black frame to the sample buffer layer so PiP has content
|
||||
/// to display immediately (before vo_pip decodes the first real frame).
|
||||
func pushBlankFrame(width: Int32 = 1920, height: Int32 = 1080) {
|
||||
var pixelBuffer: CVPixelBuffer?
|
||||
let attrs: [String: Any] = [
|
||||
kCVPixelBufferIOSurfacePropertiesKey as String: [:],
|
||||
]
|
||||
let status = CVPixelBufferCreate(
|
||||
kCFAllocatorDefault, Int(width), Int(height),
|
||||
kCVPixelFormatType_32BGRA, attrs as CFDictionary, &pixelBuffer
|
||||
)
|
||||
guard status == kCVReturnSuccess, let pb = pixelBuffer else { return }
|
||||
|
||||
// Fill with black
|
||||
CVPixelBufferLockBaseAddress(pb, [])
|
||||
if let base = CVPixelBufferGetBaseAddress(pb) {
|
||||
memset(base, 0, CVPixelBufferGetDataSize(pb))
|
||||
}
|
||||
CVPixelBufferUnlockBaseAddress(pb, [])
|
||||
|
||||
// Use current timebase time for PTS (if available) so the frame isn't stale
|
||||
let pts: CMTime
|
||||
if let tb = sampleBufferLayer.controlTimebase {
|
||||
pts = CMTimebaseGetTime(tb)
|
||||
} else {
|
||||
pts = CMTime(value: 0, timescale: 30)
|
||||
}
|
||||
|
||||
var timing = CMSampleTimingInfo(
|
||||
duration: CMTime(value: 1, timescale: 30),
|
||||
presentationTimeStamp: pts,
|
||||
decodeTimeStamp: .invalid
|
||||
)
|
||||
|
||||
// Create format description and sample buffer
|
||||
var formatDesc: CMVideoFormatDescription?
|
||||
CMVideoFormatDescriptionCreateForImageBuffer(
|
||||
allocator: kCFAllocatorDefault,
|
||||
imageBuffer: pb,
|
||||
formatDescriptionOut: &formatDesc
|
||||
)
|
||||
guard let fmt = formatDesc else { return }
|
||||
|
||||
var sampleBuffer: CMSampleBuffer?
|
||||
CMSampleBufferCreateReadyWithImageBuffer(
|
||||
allocator: kCFAllocatorDefault,
|
||||
imageBuffer: pb,
|
||||
formatDescription: fmt,
|
||||
sampleTiming: &timing,
|
||||
sampleBufferOut: &sampleBuffer
|
||||
)
|
||||
guard let sb = sampleBuffer else { return }
|
||||
|
||||
// Set DisplayImmediately so it shows regardless of timebase timing
|
||||
if let attachments = CMSampleBufferGetSampleAttachmentsArray(sb, createIfNecessary: true) as? [NSMutableDictionary],
|
||||
let dict = attachments.first {
|
||||
dict[kCMSampleAttachmentKey_DisplayImmediately] = true
|
||||
}
|
||||
|
||||
sampleBufferLayer.enqueue(sb)
|
||||
}
|
||||
|
||||
/// Sync the layer's controlTimebase with the actual playback position.
|
||||
/// This makes the PiP progress bar show the correct time.
|
||||
/// MPVKit owns the sample-buffer layer timebase. PiP only reads it.
|
||||
func syncTimebase(currentTime: Double, isPlaying: Bool) {
|
||||
guard let timebase = sampleBufferLayer.controlTimebase else { return }
|
||||
let cmTime = CMTime(seconds: currentTime, preferredTimescale: 1000)
|
||||
CMTimebaseSetTime(timebase, time: cmTime)
|
||||
CMTimebaseSetRate(timebase, rate: isPlaying ? 1.0 : 0.0)
|
||||
}
|
||||
|
||||
/// Ensure the layer has a timebase and blank frame so the system considers
|
||||
/// PiP possible (required for canStartPictureInPictureAutomaticallyFromInline).
|
||||
/// Ensure the layer has MPVKit's renderer-owned timebase before PiP starts.
|
||||
func warmLayer(currentTime: Double, isPlaying: Bool) {
|
||||
if sampleBufferLayer.controlTimebase == nil {
|
||||
var timebase: CMTimebase?
|
||||
CMTimebaseCreateWithSourceClock(
|
||||
allocator: kCFAllocatorDefault,
|
||||
sourceClock: CMClockGetHostTimeClock(),
|
||||
timebaseOut: &timebase
|
||||
)
|
||||
if let tb = timebase {
|
||||
sampleBufferLayer.controlTimebase = tb
|
||||
}
|
||||
}
|
||||
syncTimebase(currentTime: currentTime, isPlaying: isPlaying)
|
||||
pushBlankFrame()
|
||||
if sampleBufferLayer?.controlTimebase == nil {
|
||||
print("[MpvPipController] Waiting for MPVKit renderer timebase before PiP")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
static var isSupported: Bool {
|
||||
guard #available(iOS 15.0, *) else { return false }
|
||||
return AVPictureInPictureController.isPictureInPictureSupported()
|
||||
guard #available(iOS 15.0, *) else { return false }
|
||||
return AVPictureInPictureController.isPictureInPictureSupported()
|
||||
}
|
||||
|
||||
/// Start PiP. When `waitForFrame` is false (auto-PiP), skips the frame
|
||||
/// readiness check since the scene is about to deactivate.
|
||||
func startPip(waitForFrame: Bool = true, completion: @escaping (Bool) -> Void) {
|
||||
guard let pipController = pipController else {
|
||||
completion(false)
|
||||
return
|
||||
guard let pipController = pipController else {
|
||||
completion(false)
|
||||
return
|
||||
}
|
||||
|
||||
var attempts = 0
|
||||
func tryStart() {
|
||||
let possible = pipController.isPictureInPicturePossible
|
||||
let hasTimebase = self.sampleBufferLayer?.controlTimebase != nil
|
||||
|
||||
let hasFrame: Bool
|
||||
if !waitForFrame {
|
||||
hasFrame = true // Skip frame check for auto-PiP
|
||||
} else if #available(iOS 17.4, *) {
|
||||
hasFrame = self.sampleBufferLayer?.isReadyForDisplay ?? false
|
||||
} else {
|
||||
hasFrame = true
|
||||
}
|
||||
|
||||
var attempts = 0
|
||||
func tryStart() {
|
||||
let possible = pipController.isPictureInPicturePossible
|
||||
let hasTimebase = sampleBufferLayer.controlTimebase != nil
|
||||
|
||||
let hasFrame: Bool
|
||||
if !waitForFrame {
|
||||
hasFrame = true // Skip frame check for auto-PiP
|
||||
} else if #available(iOS 17.4, *) {
|
||||
hasFrame = sampleBufferLayer.isReadyForDisplay
|
||||
} else {
|
||||
hasFrame = true
|
||||
}
|
||||
|
||||
if possible && hasTimebase && hasFrame {
|
||||
print("[MpvPipController] vo_pip ready after \(attempts) retries, starting PiP")
|
||||
pipController.startPictureInPicture()
|
||||
completion(true)
|
||||
} else if attempts < 40 {
|
||||
attempts += 1
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { tryStart() }
|
||||
} else {
|
||||
print("[MpvPipController] PiP not ready after \(attempts) retries (possible=\(possible), timebase=\(hasTimebase))")
|
||||
completion(false)
|
||||
}
|
||||
if possible && hasTimebase && hasFrame {
|
||||
print("[MpvPipController] vo_avfoundation ready after \(attempts) retries, starting PiP")
|
||||
pipController.startPictureInPicture()
|
||||
completion(true)
|
||||
} else if attempts < 40 {
|
||||
attempts += 1
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { tryStart() }
|
||||
} else {
|
||||
print(
|
||||
"[MpvPipController] PiP not ready after \(attempts) retries (possible=\(possible), timebase=\(hasTimebase))"
|
||||
)
|
||||
completion(false)
|
||||
}
|
||||
tryStart()
|
||||
}
|
||||
tryStart()
|
||||
}
|
||||
|
||||
func stopPip() {
|
||||
pipController?.stopPictureInPicture()
|
||||
pipController?.stopPictureInPicture()
|
||||
}
|
||||
|
||||
/// Invalidate the playback state so PiP updates its UI (play/pause button)
|
||||
func invalidatePlaybackState() {
|
||||
pipController?.invalidatePlaybackState()
|
||||
guard #available(iOS 15.0, *) else { return }
|
||||
pipController?.invalidatePlaybackState()
|
||||
}
|
||||
|
||||
/// Fully tear down PiP — removes the container view from the window and
|
||||
/// destroys the AVPictureInPictureController so the system can no longer
|
||||
/// trigger auto-PiP after the player is disposed.
|
||||
/// Fully tear down PiP without touching the shared inline display layer.
|
||||
func teardown() {
|
||||
pipController?.stopPictureInPicture()
|
||||
if #available(iOS 14.2, *) {
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = false
|
||||
}
|
||||
pipController = nil
|
||||
delegateHelper = nil
|
||||
sampleBufferLayer.flushAndRemoveImage()
|
||||
sampleBufferLayer.controlTimebase = nil
|
||||
sampleBufferLayer.removeFromSuperlayer()
|
||||
containerView?.removeFromSuperview()
|
||||
containerView = nil
|
||||
pipController?.stopPictureInPicture()
|
||||
if #available(iOS 14.2, *) {
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = false
|
||||
}
|
||||
pipController = nil
|
||||
delegateHelper = nil
|
||||
}
|
||||
|
||||
/// Flush enqueued sample buffers from the layer to free video frame memory
|
||||
func flushLayer() {
|
||||
sampleBufferLayer.flushAndRemoveImage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PiP Delegate Helper (iOS 15+)
|
||||
// MARK: - PiP Delegate Helper (iOS 15+)
|
||||
|
||||
/// Separate class conforming to AVPictureInPictureControllerDelegate and
|
||||
/// AVPictureInPictureSampleBufferPlaybackDelegate since these require iOS 15+
|
||||
/// availability for the ContentSource-based delegate methods.
|
||||
@available(iOS 15.0, *)
|
||||
private class PipDelegateHelper: NSObject, AVPictureInPictureControllerDelegate,
|
||||
/// Separate class conforming to AVPictureInPictureControllerDelegate and
|
||||
/// AVPictureInPictureSampleBufferPlaybackDelegate since these require iOS 15+
|
||||
/// availability for the ContentSource-based delegate methods.
|
||||
@available(iOS 15.0, *)
|
||||
private class PipDelegateHelper: NSObject, AVPictureInPictureControllerDelegate,
|
||||
AVPictureInPictureSampleBufferPlaybackDelegate
|
||||
{
|
||||
{
|
||||
weak var controller: MpvPipController?
|
||||
private var isRestoring = false
|
||||
|
||||
init(controller: MpvPipController) {
|
||||
self.controller = controller
|
||||
super.init()
|
||||
self.controller = controller
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - AVPictureInPictureControllerDelegate
|
||||
|
||||
func pictureInPictureControllerWillStartPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
print("[MpvPipController] PiP will start")
|
||||
controller?.delegate?.pipWillStart()
|
||||
print("[MpvPipController] PiP will start")
|
||||
controller?.delegate?.pipWillStart()
|
||||
}
|
||||
|
||||
func pictureInPictureControllerDidStartPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
print("[MpvPipController] PiP did start")
|
||||
controller?.delegate?.pipDidStart()
|
||||
print("[MpvPipController] PiP did start")
|
||||
controller?.delegate?.pipDidStart()
|
||||
}
|
||||
|
||||
func pictureInPictureControllerDidStopPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
let restored = isRestoring
|
||||
isRestoring = false
|
||||
print("[MpvPipController] PiP did stop (restored: \(restored))")
|
||||
controller?.delegate?.pipDidStop(restored: restored)
|
||||
let restored = isRestoring
|
||||
isRestoring = false
|
||||
print("[MpvPipController] PiP did stop (restored: \(restored))")
|
||||
controller?.delegate?.pipDidStop(restored: restored)
|
||||
}
|
||||
|
||||
func pictureInPictureController(
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
failedToStartPictureInPictureWithError error: Error
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
failedToStartPictureInPictureWithError error: Error
|
||||
) {
|
||||
print("[MpvPipController] PiP failed to start: \(error)")
|
||||
controller?.delegate?.pipDidFailToStart(error: error)
|
||||
print("[MpvPipController] PiP failed to start: \(error)")
|
||||
controller?.delegate?.pipDidFailToStart(error: error)
|
||||
}
|
||||
|
||||
func pictureInPictureController(
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler:
|
||||
@escaping (Bool) -> Void
|
||||
) {
|
||||
print("[MpvPipController] PiP restore user interface")
|
||||
isRestoring = true
|
||||
completionHandler(true)
|
||||
print("[MpvPipController] PiP restore user interface")
|
||||
isRestoring = true
|
||||
completionHandler(true)
|
||||
}
|
||||
|
||||
func pictureInPictureControllerWillStopPictureInPicture(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) {
|
||||
print("[MpvPipController] PiP will stop")
|
||||
print("[MpvPipController] PiP will stop")
|
||||
}
|
||||
|
||||
// MARK: - AVPictureInPictureSampleBufferPlaybackDelegate
|
||||
|
||||
func pictureInPictureController(
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
setPlaying playing: Bool
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
setPlaying playing: Bool
|
||||
) {
|
||||
print("[MpvPipController] PiP setPlaying: \(playing)")
|
||||
controller?.delegate?.pipSetPlaying(playing)
|
||||
print("[MpvPipController] PiP setPlaying: \(playing)")
|
||||
controller?.delegate?.pipSetPlaying(playing)
|
||||
}
|
||||
|
||||
func pictureInPictureControllerTimeRangeForPlayback(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) -> CMTimeRange {
|
||||
let duration = controller?.delegate?.pipDuration ?? 0
|
||||
if duration > 0 {
|
||||
return CMTimeRange(
|
||||
start: .zero,
|
||||
duration: CMTime(seconds: duration, preferredTimescale: 1000)
|
||||
)
|
||||
}
|
||||
return CMTimeRange(start: .zero, duration: CMTime(seconds: 1, preferredTimescale: 1))
|
||||
let duration = controller?.delegate?.pipDuration ?? 0
|
||||
if duration > 0 {
|
||||
return CMTimeRange(
|
||||
start: .zero,
|
||||
duration: CMTime(seconds: duration, preferredTimescale: 1000)
|
||||
)
|
||||
}
|
||||
return CMTimeRange(start: .zero, duration: CMTime(seconds: 1, preferredTimescale: 1))
|
||||
}
|
||||
|
||||
func pictureInPictureControllerIsPlaybackPaused(
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
_ pictureInPictureController: AVPictureInPictureController
|
||||
) -> Bool {
|
||||
return !(controller?.delegate?.isPipPlaying ?? false)
|
||||
return !(controller?.delegate?.isPipPlaying ?? false)
|
||||
}
|
||||
|
||||
func pictureInPictureController(
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
didTransitionToRenderSize newRenderSize: CMVideoDimensions
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
didTransitionToRenderSize newRenderSize: CMVideoDimensions
|
||||
) {}
|
||||
|
||||
func pictureInPictureController(
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
skipByInterval skipInterval: CMTime,
|
||||
completion completionHandler: @escaping () -> Void
|
||||
_ pictureInPictureController: AVPictureInPictureController,
|
||||
skipByInterval skipInterval: CMTime,
|
||||
completion completionHandler: @escaping () -> Void
|
||||
) {
|
||||
let seconds = CMTimeGetSeconds(skipInterval)
|
||||
print("[MpvPipController] PiP skip by \(seconds)s")
|
||||
controller?.delegate?.pipSkip(byInterval: seconds)
|
||||
let seconds = CMTimeGetSeconds(skipInterval)
|
||||
print("[MpvPipController] PiP skip by \(seconds)s")
|
||||
guard let delegate = controller?.delegate else {
|
||||
completionHandler()
|
||||
return
|
||||
}
|
||||
delegate.pipSkip(byInterval: seconds, completion: completionHandler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // !os(tvOS)
|
||||
|
||||
@@ -5,392 +5,506 @@ import AVKit
|
||||
/// Flutter plugin that bridges MPV player to Dart via method and event channels
|
||||
class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginShared {
|
||||
|
||||
// MARK: - Properties
|
||||
// MARK: - Properties
|
||||
|
||||
private var playerCore: MpvPlayerCore?
|
||||
var eventSink: FlutterEventSink?
|
||||
private weak var registrar: FlutterPluginRegistrar?
|
||||
var nameToId: [String: Int] = [:]
|
||||
private var playerCore: MpvPlayerCore?
|
||||
var eventSink: FlutterEventSink?
|
||||
private weak var registrar: FlutterPluginRegistrar?
|
||||
var nameToId: [String: Int] = [:]
|
||||
|
||||
// MpvPluginShared conformance
|
||||
var coreBase: MpvPlayerCoreBase? { playerCore }
|
||||
func setPlayerVisible(_ visible: Bool) { playerCore?.setVisible(visible) }
|
||||
func updatePlayerFrame() { playerCore?.updateFrame() }
|
||||
// MpvPluginShared conformance
|
||||
var coreBase: MpvPlayerCoreBase? { playerCore }
|
||||
func setPlayerVisible(_ visible: Bool, restoreOnWindowVisible _: Bool) { playerCore?.setVisible(visible) }
|
||||
func updatePlayerFrame() { playerCore?.updateFrame() }
|
||||
|
||||
// PiP
|
||||
private var pipController: MpvPipController?
|
||||
private var pipChannel: FlutterMethodChannel?
|
||||
private var autoPipEnabled = false
|
||||
private var isManualPipRequest = false
|
||||
private var pipTimebaseSyncTimer: Timer?
|
||||
private var pendingInlineRestoreAfterPip = false
|
||||
private var sceneActivationObserverRegistered = false
|
||||
// PiP
|
||||
private var pipController: MpvPipController?
|
||||
private var pipChannel: FlutterMethodChannel?
|
||||
private var autoPipEnabled = false
|
||||
private var isManualPipRequest = false
|
||||
private var pipTimebaseSyncTimer: Timer?
|
||||
private var pendingInlineRestoreAfterPip = false
|
||||
private var sceneActivationObserverRegistered = false
|
||||
|
||||
// MARK: - FlutterPlugin Registration
|
||||
// MARK: - FlutterPlugin Registration
|
||||
|
||||
static func register(with registrar: FlutterPluginRegistrar) {
|
||||
let methodChannel = FlutterMethodChannel(
|
||||
name: "com.plezy/mpv_player",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
let eventChannel = FlutterEventChannel(
|
||||
name: "com.plezy/mpv_player/events",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
let pipChannel = FlutterMethodChannel(
|
||||
name: "com.plezy/pip",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
static func register(with registrar: FlutterPluginRegistrar) {
|
||||
let methodChannel = FlutterMethodChannel(
|
||||
name: "com.plezy/mpv_player",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
let eventChannel = FlutterEventChannel(
|
||||
name: "com.plezy/mpv_player/events",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
let pipChannel = FlutterMethodChannel(
|
||||
name: "com.plezy/pip",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
|
||||
let instance = MpvPlayerPlugin()
|
||||
instance.registrar = registrar
|
||||
instance.pipChannel = pipChannel
|
||||
let instance = MpvPlayerPlugin()
|
||||
instance.registrar = registrar
|
||||
instance.pipChannel = pipChannel
|
||||
|
||||
registrar.addMethodCallDelegate(instance, channel: methodChannel)
|
||||
eventChannel.setStreamHandler(instance)
|
||||
pipChannel.setMethodCallHandler(instance.handlePipCall)
|
||||
registrar.addMethodCallDelegate(instance, channel: methodChannel)
|
||||
eventChannel.setStreamHandler(instance)
|
||||
pipChannel.setMethodCallHandler(instance.handlePipCall)
|
||||
}
|
||||
|
||||
// MARK: - FlutterStreamHandler
|
||||
|
||||
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink)
|
||||
-> FlutterError?
|
||||
{
|
||||
self.eventSink = events
|
||||
return nil
|
||||
}
|
||||
|
||||
func onCancel(withArguments arguments: Any?) -> FlutterError? {
|
||||
self.eventSink = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: - FlutterPlugin Method Handler
|
||||
|
||||
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
switch call.method {
|
||||
case "initialize":
|
||||
handleInitialize(result: result)
|
||||
case "dispose":
|
||||
handleDispose(call: call, result: result)
|
||||
case "setProperty":
|
||||
handleSetProperty(call: call, result: result)
|
||||
case "getProperty":
|
||||
handleGetProperty(call: call, result: result)
|
||||
case "observeProperty":
|
||||
handleObserveProperty(call: call, result: result)
|
||||
case "command":
|
||||
handleCommand(call: call, result: result)
|
||||
case "setDisplayCriteria":
|
||||
handleSetDisplayCriteria(call: call, result: result)
|
||||
case "setVisible":
|
||||
handleSetVisible(call: call, result: result)
|
||||
case "isInitialized":
|
||||
result(playerCore?.isInitialized ?? false)
|
||||
case "updateFrame":
|
||||
handleUpdateFrame(result: result)
|
||||
case "setLogLevel":
|
||||
handleSetLogLevel(call: call, result: result)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FlutterStreamHandler
|
||||
// MARK: - PiP
|
||||
|
||||
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
|
||||
self.eventSink = events
|
||||
return nil
|
||||
private func ensurePipController() -> MpvPipController? {
|
||||
if let existing = pipController { return existing }
|
||||
guard let layer = playerCore?.sampleBufferDisplayLayer else { return nil }
|
||||
let controller = MpvPipController(sampleBufferDisplayLayer: layer)
|
||||
controller.delegate = self
|
||||
pipController = controller
|
||||
return controller
|
||||
}
|
||||
|
||||
private func registerSceneActivationObserver() {
|
||||
guard !sceneActivationObserverRegistered else { return }
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(sceneDidActivate),
|
||||
name: UIScene.didActivateNotification,
|
||||
object: nil
|
||||
)
|
||||
sceneActivationObserverRegistered = true
|
||||
}
|
||||
|
||||
private func unregisterSceneActivationObserver() {
|
||||
guard sceneActivationObserverRegistered else { return }
|
||||
NotificationCenter.default.removeObserver(
|
||||
self, name: UIScene.didActivateNotification, object: nil)
|
||||
sceneActivationObserverRegistered = false
|
||||
}
|
||||
|
||||
private var isSceneActive: Bool {
|
||||
#if os(iOS)
|
||||
ExternalDisplayManager.hasActiveApplicationScene
|
||||
#else
|
||||
UIApplication.shared.connectedScenes.contains { $0.activationState == .foregroundActive }
|
||||
#endif
|
||||
}
|
||||
|
||||
private func restoreInlinePlayerAfterPip() {
|
||||
guard pendingInlineRestoreAfterPip,
|
||||
let playerCore = playerCore,
|
||||
!playerCore.isPipActive,
|
||||
!playerCore.isPipStarting
|
||||
else { return }
|
||||
|
||||
print("[MpvPlayerPlugin] Restoring inline player after PiP")
|
||||
playerCore.setVisible(true)
|
||||
playerCore.updateFrame()
|
||||
if playerCore.isPaused {
|
||||
playerCore.forceDraw()
|
||||
}
|
||||
pendingInlineRestoreAfterPip = false
|
||||
}
|
||||
|
||||
func onCancel(withArguments arguments: Any?) -> FlutterError? {
|
||||
self.eventSink = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: - FlutterPlugin Method Handler
|
||||
|
||||
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
switch call.method {
|
||||
case "initialize":
|
||||
handleInitialize(result: result)
|
||||
case "dispose":
|
||||
handleDispose(result: result)
|
||||
case "setProperty":
|
||||
handleSetProperty(call: call, result: result)
|
||||
case "getProperty":
|
||||
handleGetProperty(call: call, result: result)
|
||||
case "observeProperty":
|
||||
handleObserveProperty(call: call, result: result)
|
||||
case "command":
|
||||
handleCommand(call: call, result: result)
|
||||
case "setVisible":
|
||||
handleSetVisible(call: call, result: result)
|
||||
case "isInitialized":
|
||||
result(playerCore?.isInitialized ?? false)
|
||||
case "updateFrame":
|
||||
handleUpdateFrame(result: result)
|
||||
case "setLogLevel":
|
||||
handleSetLogLevel(call: call, result: result)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PiP
|
||||
|
||||
private func ensurePipController() -> MpvPipController {
|
||||
if let existing = pipController { return existing }
|
||||
let controller = MpvPipController()
|
||||
controller.delegate = self
|
||||
pipController = controller
|
||||
return controller
|
||||
}
|
||||
|
||||
private func registerSceneActivationObserver() {
|
||||
guard !sceneActivationObserverRegistered else { return }
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(sceneDidActivate),
|
||||
name: UIScene.didActivateNotification,
|
||||
object: nil
|
||||
)
|
||||
sceneActivationObserverRegistered = true
|
||||
}
|
||||
|
||||
private func unregisterSceneActivationObserver() {
|
||||
guard sceneActivationObserverRegistered else { return }
|
||||
NotificationCenter.default.removeObserver(self, name: UIScene.didActivateNotification, object: nil)
|
||||
sceneActivationObserverRegistered = false
|
||||
}
|
||||
|
||||
private var isSceneActive: Bool {
|
||||
UIApplication.shared.connectedScenes.contains { $0.activationState == .foregroundActive }
|
||||
}
|
||||
|
||||
private func restoreInlinePlayerAfterPip() {
|
||||
guard pendingInlineRestoreAfterPip,
|
||||
let playerCore = playerCore,
|
||||
!playerCore.isPipActive,
|
||||
!playerCore.isPipStarting else { return }
|
||||
|
||||
print("[MpvPlayerPlugin] Restoring inline player after PiP")
|
||||
playerCore.setVisible(true)
|
||||
playerCore.updateFrame()
|
||||
if playerCore.isPaused {
|
||||
playerCore.forceDraw()
|
||||
}
|
||||
pendingInlineRestoreAfterPip = false
|
||||
}
|
||||
|
||||
private func handlePipCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { result(nil); return }
|
||||
switch call.method {
|
||||
case "isSupported":
|
||||
result(MpvPipController.isSupported)
|
||||
case "enter":
|
||||
self.enterPip(manual: true, result: result)
|
||||
case "setAutoPipReady":
|
||||
if let args = call.arguments as? [String: Any], let ready = args["ready"] as? Bool {
|
||||
self.autoPipEnabled = ready
|
||||
if ready {
|
||||
let pip = self.ensurePipController()
|
||||
pip.setAutoStart(true)
|
||||
// Warm the layer so the system considers PiP possible
|
||||
if let pc = self.playerCore {
|
||||
pip.warmLayer(currentTime: pc.timePos, isPlaying: !pc.isPaused)
|
||||
}
|
||||
} else {
|
||||
self.pipController?.setAutoStart(false)
|
||||
}
|
||||
}
|
||||
result(nil)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
private func handlePipCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { result(nil); return }
|
||||
switch call.method {
|
||||
case "isSupported":
|
||||
result(MpvPipController.isSupported)
|
||||
case "enter":
|
||||
self.enterPip(manual: true, result: result)
|
||||
case "setAutoPipReady":
|
||||
if let args = call.arguments as? [String: Any], let ready = args["ready"] as? Bool {
|
||||
self.autoPipEnabled = ready
|
||||
if ready {
|
||||
guard let pip = self.ensurePipController() else {
|
||||
result(nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Switch to PiP VO and prepare the sample buffer layer for PiP display.
|
||||
/// Returns the MpvPipController on success, nil on failure.
|
||||
@discardableResult
|
||||
private func switchToPipAndPrepare() -> MpvPipController? {
|
||||
guard let playerCore = playerCore else { return nil }
|
||||
let pip = ensurePipController()
|
||||
guard playerCore.switchToPipVO(layerPtr: pip.layerPointer) else { return nil }
|
||||
pendingInlineRestoreAfterPip = false
|
||||
playerCore.isPipStarting = true
|
||||
pip.pushBlankFrame()
|
||||
pip.syncTimebase(currentTime: playerCore.timePos, isPlaying: !playerCore.isPaused)
|
||||
pip.invalidatePlaybackState()
|
||||
return pip
|
||||
}
|
||||
|
||||
/// Manual PiP entry (button press). Auto-PiP is handled by the system via
|
||||
/// canStartPictureInPictureAutomaticallyFromInline + pipWillStart delegate.
|
||||
private func enterPip(manual: Bool, result: FlutterResult? = nil) {
|
||||
guard MpvPipController.isSupported else {
|
||||
result?(["success": false, "errorCode": "ios_version", "errorMessage": "Requires iOS 15.0+"])
|
||||
return
|
||||
}
|
||||
guard playerCore != nil else {
|
||||
result?(["success": false, "errorCode": "failed", "errorMessage": "Player not initialized"])
|
||||
return
|
||||
}
|
||||
guard let pip = switchToPipAndPrepare() else {
|
||||
result?(["success": false, "errorCode": "vo_switch_failed", "errorMessage": "Failed to switch VO"])
|
||||
return
|
||||
}
|
||||
|
||||
isManualPipRequest = manual
|
||||
pip.startPip(waitForFrame: manual) { [weak self] started in
|
||||
if started {
|
||||
result?(["success": true])
|
||||
} else {
|
||||
self?.cleanupPip(notify: false)
|
||||
result?(["success": false, "errorCode": "failed", "errorMessage": "PiP failed to start"])
|
||||
pip.setAutoStart(true)
|
||||
// Warm the layer so the system considers PiP possible
|
||||
if let pc = self.playerCore {
|
||||
pip.warmLayer(currentTime: pc.timePos, isPlaying: !pc.isPaused)
|
||||
}
|
||||
} else {
|
||||
self.pipController?.setAutoStart(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unified cleanup for all PiP exit paths
|
||||
private func cleanupPip(notify: Bool, pause: Bool = false) {
|
||||
playerCore?.isPipStarting = false
|
||||
playerCore?.isPipActive = false
|
||||
isManualPipRequest = false
|
||||
stopPipTimebaseSync()
|
||||
pipController?.flushLayer()
|
||||
let restoredInlineVO = playerCore?.switchToGpuNextVO() ?? false
|
||||
if pause { playerCore?.setProperty("pause", value: "yes") }
|
||||
pendingInlineRestoreAfterPip = restoredInlineVO
|
||||
if pendingInlineRestoreAfterPip {
|
||||
if isSceneActive {
|
||||
restoreInlinePlayerAfterPip()
|
||||
} else {
|
||||
print("[MpvPlayerPlugin] Deferring inline restore until scene activation")
|
||||
}
|
||||
}
|
||||
if notify { pipChannel?.invokeMethod("onPipChanged", arguments: false) }
|
||||
}
|
||||
|
||||
/// Scene became active — restore inline playback if needed and re-warm the
|
||||
/// sample-buffer layer so future auto-PiP remains possible.
|
||||
@objc private func sceneDidActivate() {
|
||||
restoreInlinePlayerAfterPip()
|
||||
if autoPipEnabled, let pip = pipController, let pc = playerCore, !pc.isPipActive {
|
||||
pip.warmLayer(currentTime: pc.timePos, isPlaying: !pc.isPaused)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Timebase Sync
|
||||
|
||||
private func syncPipTimebase() {
|
||||
guard let playerCore = playerCore, let pipController = pipController else { return }
|
||||
pipController.syncTimebase(
|
||||
currentTime: playerCore.timePos,
|
||||
isPlaying: !playerCore.isPaused
|
||||
)
|
||||
}
|
||||
|
||||
private func startPipTimebaseSync() {
|
||||
stopPipTimebaseSync()
|
||||
pipTimebaseSyncTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
|
||||
self?.syncPipTimebase()
|
||||
}
|
||||
}
|
||||
|
||||
private func stopPipTimebaseSync() {
|
||||
pipTimebaseSyncTimer?.invalidate()
|
||||
pipTimebaseSyncTimer = nil
|
||||
}
|
||||
|
||||
// MARK: - Platform-Specific Method Handlers
|
||||
|
||||
private func handleInitialize(result: @escaping FlutterResult) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else {
|
||||
result(FlutterError(code: "ERROR", message: "Plugin deallocated", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
if self.playerCore?.isInitialized == true {
|
||||
self.registerSceneActivationObserver()
|
||||
result(true)
|
||||
return
|
||||
}
|
||||
|
||||
guard let window = self.findKeyWindow() else {
|
||||
result(FlutterError(code: "NO_WINDOW", message: "Could not find key window", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
let core = MpvPlayerCore()
|
||||
core.delegate = self
|
||||
|
||||
guard core.initialize(in: window) else {
|
||||
result(FlutterError(code: "MPV_INIT_FAILED", message: "Failed to initialize MPV", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
self.playerCore = core
|
||||
self.registerSceneActivationObserver()
|
||||
core.setVisible(false)
|
||||
result(true)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleDispose(result: @escaping FlutterResult) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { result(nil); return }
|
||||
self.pipController?.teardown()
|
||||
self.pipController = nil
|
||||
self.autoPipEnabled = false
|
||||
self.pendingInlineRestoreAfterPip = false
|
||||
self.unregisterSceneActivationObserver()
|
||||
self.stopPipTimebaseSync()
|
||||
self.playerCore?.dispose()
|
||||
self.playerCore = nil
|
||||
result(nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleSetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
guard let args = call.arguments as? [String: Any],
|
||||
let name = args["name"] as? String,
|
||||
let value = args["value"] as? String else {
|
||||
result(FlutterError(code: "INVALID_ARGS", message: "Missing 'name' or 'value' argument", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.setProperty(name, value: value)
|
||||
|
||||
if name == "pause" {
|
||||
pipController?.invalidatePlaybackState()
|
||||
if playerCore?.isPipActive == true { syncPipTimebase() }
|
||||
}
|
||||
|
||||
result(nil)
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare the shared AVFoundation display layer for PiP display.
|
||||
/// Returns the MpvPipController on success, nil on failure.
|
||||
@discardableResult
|
||||
private func preparePip() -> MpvPipController? {
|
||||
guard let playerCore = playerCore else { return nil }
|
||||
guard let pip = ensurePipController() else { return nil }
|
||||
pendingInlineRestoreAfterPip = false
|
||||
playerCore.setPipSubtitleCompositing(true)
|
||||
playerCore.isPipStarting = true
|
||||
pip.syncTimebase(currentTime: playerCore.timePos, isPlaying: !playerCore.isPaused)
|
||||
pip.invalidatePlaybackState()
|
||||
return pip
|
||||
}
|
||||
|
||||
/// Manual PiP entry (button press). Auto-PiP is handled by the system via
|
||||
/// canStartPictureInPictureAutomaticallyFromInline + pipWillStart delegate.
|
||||
private func enterPip(manual: Bool, result: FlutterResult? = nil) {
|
||||
guard MpvPipController.isSupported else {
|
||||
result?([
|
||||
"success": false, "errorCode": "ios_version", "errorMessage": "Requires iOS 15.0+",
|
||||
])
|
||||
return
|
||||
}
|
||||
guard playerCore != nil else {
|
||||
result?([
|
||||
"success": false, "errorCode": "failed", "errorMessage": "Player not initialized",
|
||||
])
|
||||
return
|
||||
}
|
||||
guard let pip = preparePip() else {
|
||||
result?([
|
||||
"success": false, "errorCode": "pip_prepare_failed",
|
||||
"errorMessage": "Failed to prepare PiP",
|
||||
])
|
||||
return
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
isManualPipRequest = manual
|
||||
pip.startPip(waitForFrame: manual) { [weak self] started in
|
||||
if started {
|
||||
result?(["success": true])
|
||||
} else {
|
||||
self?.cleanupPip(notify: false)
|
||||
result?([
|
||||
"success": false, "errorCode": "failed", "errorMessage": "PiP failed to start",
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func findKeyWindow() -> UIWindow? {
|
||||
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
|
||||
let window = windowScene.windows.first(where: { $0.isKeyWindow }) else {
|
||||
return nil
|
||||
/// Unified cleanup for all PiP exit paths
|
||||
private func cleanupPip(notify: Bool, pause: Bool = false) {
|
||||
playerCore?.setPipSubtitleCompositing(false)
|
||||
playerCore?.isPipStarting = false
|
||||
playerCore?.isPipActive = false
|
||||
isManualPipRequest = false
|
||||
stopPipTimebaseSync()
|
||||
if pause {
|
||||
playerCore?.setPropertyAsync("pause", value: "yes") { [weak self] _ in
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
self?.syncPipTimebase()
|
||||
}
|
||||
}
|
||||
pendingInlineRestoreAfterPip = true
|
||||
if pendingInlineRestoreAfterPip {
|
||||
if isSceneActive {
|
||||
restoreInlinePlayerAfterPip()
|
||||
} else {
|
||||
print("[MpvPlayerPlugin] Deferring inline restore until scene activation")
|
||||
}
|
||||
}
|
||||
if notify { pipChannel?.invokeMethod("onPipChanged", arguments: false) }
|
||||
}
|
||||
|
||||
/// Scene became active — restore inline playback if needed and re-warm the
|
||||
/// sample-buffer layer so future auto-PiP remains possible.
|
||||
@objc private func sceneDidActivate() {
|
||||
restoreInlinePlayerAfterPip()
|
||||
if autoPipEnabled, let pip = pipController, let pc = playerCore, !pc.isPipActive {
|
||||
pip.warmLayer(currentTime: pc.timePos, isPlaying: !pc.isPaused)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Timebase Sync
|
||||
|
||||
private func syncPipTimebase() {
|
||||
guard let playerCore = playerCore, let pipController = pipController else { return }
|
||||
pipController.syncTimebase(
|
||||
currentTime: playerCore.timePos,
|
||||
isPlaying: !playerCore.isPaused
|
||||
)
|
||||
}
|
||||
|
||||
private func startPipTimebaseSync() {
|
||||
stopPipTimebaseSync()
|
||||
pipTimebaseSyncTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) {
|
||||
[weak self] _ in
|
||||
self?.syncPipTimebase()
|
||||
}
|
||||
}
|
||||
|
||||
private func stopPipTimebaseSync() {
|
||||
pipTimebaseSyncTimer?.invalidate()
|
||||
pipTimebaseSyncTimer = nil
|
||||
}
|
||||
|
||||
// MARK: - Platform-Specific Method Handlers
|
||||
|
||||
private func handleInitialize(result: @escaping FlutterResult) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else {
|
||||
result(FlutterError(code: "ERROR", message: "Plugin deallocated", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
if self.playerCore?.isInitialized == true {
|
||||
self.registerSceneActivationObserver()
|
||||
result(true)
|
||||
return
|
||||
}
|
||||
|
||||
guard let window = self.findKeyWindow() else {
|
||||
result(
|
||||
FlutterError(
|
||||
code: "NO_WINDOW", message: "Could not find key window", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
let core = MpvPlayerCore()
|
||||
core.delegate = self
|
||||
|
||||
guard core.initialize(in: window) else {
|
||||
result(
|
||||
FlutterError(
|
||||
code: "MPV_INIT_FAILED", message: "Failed to initialize MPV", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
self.playerCore = core
|
||||
self.registerSceneActivationObserver()
|
||||
core.setVisible(false)
|
||||
result(true)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleDispose(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
let args = call.arguments as? [String: Any]
|
||||
let preserveDisplayMode = args?["preserveDisplayMode"] as? Bool ?? false
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { result(nil); return }
|
||||
NSLog("[MpvPlayerPlugin] dispose preserveDisplayMode=%@", preserveDisplayMode.description)
|
||||
self.pipController?.teardown()
|
||||
self.pipController = nil
|
||||
self.autoPipEnabled = false
|
||||
self.pendingInlineRestoreAfterPip = false
|
||||
self.unregisterSceneActivationObserver()
|
||||
self.stopPipTimebaseSync()
|
||||
self.playerCore?.dispose(preserveDisplayCriteria: preserveDisplayMode)
|
||||
self.playerCore = nil
|
||||
result(nil)
|
||||
}
|
||||
}
|
||||
|
||||
func didSetPauseProperty(value: String) {
|
||||
pipController?.invalidatePlaybackState()
|
||||
if playerCore?.isPipActive == true { syncPipTimebase() }
|
||||
}
|
||||
|
||||
private func handleSetDisplayCriteria(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
guard let args = call.arguments as? [String: Any] else {
|
||||
result(FlutterError(code: "INVALID_ARGS", message: "Missing arguments", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
guard let core = playerCore else {
|
||||
result(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let extraDelayMs = int64Value(args["extraDelayMs"]).map { Int(clamping: $0) } ?? 0
|
||||
guard let raw = args["criteria"] as? [String: Any] else {
|
||||
DispatchQueue.main.async {
|
||||
core.setServerDisplayCriteriaForPlayback(nil, extraDelayMs: extraDelayMs) {
|
||||
result(nil)
|
||||
}
|
||||
return window
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let criteria = ServerDisplayCriteria(
|
||||
doviProfile: int64Value(raw["doviProfile"]) ?? 0,
|
||||
doviLevel: int64Value(raw["doviLevel"]) ?? 0,
|
||||
doviCompatibilityId: int64Value(raw["doviCompatibilityId"]),
|
||||
fps: doubleValue(raw["fps"]) ?? 0,
|
||||
width: Int32(truncatingIfNeeded: int64Value(raw["width"]) ?? 0),
|
||||
height: Int32(truncatingIfNeeded: int64Value(raw["height"]) ?? 0),
|
||||
gamma: stringValue(raw["transfer"]),
|
||||
primaries: stringValue(raw["primaries"]),
|
||||
colorMatrix: stringValue(raw["matrix"])
|
||||
)
|
||||
DispatchQueue.main.async {
|
||||
core.setServerDisplayCriteriaForPlayback(criteria, extraDelayMs: extraDelayMs) {
|
||||
result(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func int64Value(_ value: Any?) -> Int64? {
|
||||
switch value {
|
||||
case let value as Int64:
|
||||
return value
|
||||
case let value as Int:
|
||||
return Int64(value)
|
||||
case let value as NSNumber:
|
||||
return value.int64Value
|
||||
case let value as String:
|
||||
return Int64(value)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func doubleValue(_ value: Any?) -> Double? {
|
||||
switch value {
|
||||
case let value as Double:
|
||||
return value
|
||||
case let value as NSNumber:
|
||||
return value.doubleValue
|
||||
case let value as String:
|
||||
return Double(value)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func stringValue(_ value: Any?) -> String? {
|
||||
guard let value else { return nil }
|
||||
let string = String(describing: value).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return string.isEmpty ? nil : string
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func findKeyWindow() -> UIWindow? {
|
||||
#if os(iOS)
|
||||
return ExternalDisplayManager.mainApplicationWindow()
|
||||
#else
|
||||
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||
|
||||
for scene in scenes {
|
||||
if let window = scene.windows.first(where: { $0.isKeyWindow }) {
|
||||
return window
|
||||
}
|
||||
}
|
||||
|
||||
for scene in scenes {
|
||||
if let window = scene.windows.first(where: { !$0.isHidden }) {
|
||||
return window
|
||||
}
|
||||
}
|
||||
|
||||
return scenes.first?.windows.first
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - MpvPipDelegate
|
||||
|
||||
extension MpvPlayerPlugin: MpvPipDelegate {
|
||||
|
||||
func pipWillStart() {
|
||||
// If PiP was system-initiated (not via our enterPip), switch VO now
|
||||
guard let playerCore = playerCore, !playerCore.isPipStarting else { return }
|
||||
print("[MpvPlayerPlugin] System-initiated PiP detected, switching VO")
|
||||
if switchToPipAndPrepare() == nil {
|
||||
print("[MpvPlayerPlugin] VO switch failed for system-initiated PiP")
|
||||
pipController?.stopPip()
|
||||
}
|
||||
func pipWillStart() {
|
||||
// If PiP was system-initiated (not via our enterPip), prepare the shared layer now.
|
||||
guard let playerCore = playerCore, !playerCore.isPipStarting else { return }
|
||||
print("[MpvPlayerPlugin] System-initiated PiP detected, preparing shared layer")
|
||||
if preparePip() == nil {
|
||||
print("[MpvPlayerPlugin] PiP preparation failed for system-initiated PiP")
|
||||
pipController?.stopPip()
|
||||
}
|
||||
}
|
||||
|
||||
func pipDidStart() {
|
||||
playerCore?.isPipStarting = false
|
||||
playerCore?.isPipActive = true
|
||||
pendingInlineRestoreAfterPip = false
|
||||
pipChannel?.invokeMethod("onPipChanged", arguments: true)
|
||||
syncPipTimebase()
|
||||
startPipTimebaseSync()
|
||||
func pipDidStart() {
|
||||
playerCore?.isPipStarting = false
|
||||
playerCore?.isPipActive = true
|
||||
pendingInlineRestoreAfterPip = false
|
||||
pipChannel?.invokeMethod("onPipChanged", arguments: true)
|
||||
syncPipTimebase()
|
||||
startPipTimebaseSync()
|
||||
|
||||
if isManualPipRequest {
|
||||
isManualPipRequest = false
|
||||
UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
|
||||
}
|
||||
if isManualPipRequest {
|
||||
isManualPipRequest = false
|
||||
UIControl().sendAction(
|
||||
#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
|
||||
}
|
||||
}
|
||||
|
||||
func pipDidStop(restored: Bool) {
|
||||
cleanupPip(notify: true, pause: !restored)
|
||||
func pipDidStop(restored: Bool) {
|
||||
cleanupPip(notify: true, pause: !restored)
|
||||
}
|
||||
|
||||
func pipDidFailToStart(error: Error?) {
|
||||
cleanupPip(notify: true)
|
||||
}
|
||||
|
||||
func pipSetPlaying(_ playing: Bool) {
|
||||
playerCore?.setPropertyAsync("pause", value: playing ? "no" : "yes") { [weak self] _ in
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
self?.syncPipTimebase()
|
||||
}
|
||||
}
|
||||
|
||||
func pipDidFailToStart(error: Error?) {
|
||||
cleanupPip(notify: true)
|
||||
func pipSkip(byInterval seconds: Double, completion: @escaping () -> Void) {
|
||||
guard let playerCore = playerCore else {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
|
||||
func pipSetPlaying(_ playing: Bool) {
|
||||
playerCore?.setProperty("pause", value: playing ? "no" : "yes")
|
||||
pipController?.invalidatePlaybackState()
|
||||
syncPipTimebase()
|
||||
let newTime = max(0, playerCore.timePos + seconds)
|
||||
playerCore.commandAsync(["seek", String(newTime), "absolute"]) { [weak self] _ in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
completion()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func pipSkip(byInterval seconds: Double) {
|
||||
guard let playerCore = playerCore else { return }
|
||||
let newTime = max(0, playerCore.timePos + seconds)
|
||||
playerCore.command(["seek", String(newTime), "absolute"])
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
|
||||
self?.syncPipTimebase()
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
}
|
||||
}
|
||||
|
||||
var isPipPlaying: Bool { !(playerCore?.isPaused ?? true) }
|
||||
var pipDuration: Double { playerCore?.duration ?? 0 }
|
||||
var isPipPlaying: Bool { !(playerCore?.isPaused ?? true) }
|
||||
var pipDuration: Double { playerCore?.duration ?? 0 }
|
||||
}
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
require 'dotenv/load'
|
||||
Dotenv.load("../../.env")
|
||||
require 'shellwords'
|
||||
|
||||
PROJECT_ROOT = File.expand_path("../..", __dir__)
|
||||
PROJECT_ROOT_ARG = Shellwords.escape(PROJECT_ROOT)
|
||||
|
||||
Dotenv.load(File.join(PROJECT_ROOT, ".env"))
|
||||
|
||||
default_platform(:ios)
|
||||
|
||||
platform :ios do
|
||||
desc "Build and deploy to App Store"
|
||||
lane :deploy_appstore do
|
||||
git_commit = `git rev-parse --short HEAD`.strip
|
||||
git_commit = `git -C #{PROJECT_ROOT_ARG} rev-parse --short HEAD`.strip
|
||||
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_IN_APP_REVIEW=true --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=app-store --split-debug-info=debug-info/ios")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && flutter build ipa --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=app-store --dart-define=SENTRY_DIST=app-store --split-debug-info=debug-info/ios")
|
||||
|
||||
# Upload debug symbols
|
||||
sh("cd #{ENV['PWD']}/.. && ./scripts/upload-symbols.sh ios")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=app-store ./scripts/upload-symbols.sh ios")
|
||||
|
||||
# Upload to App Store
|
||||
upload_to_app_store(
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
import '../media/media_backend.dart';
|
||||
import '../models/plex/plex_home_user.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
|
||||
/// Identifier of a backend kind a [Connection] points at. Lighter-weight than
|
||||
/// [MediaBackend] for places that only care about persistence/auth shape
|
||||
/// (e.g. database column values).
|
||||
enum ConnectionKind {
|
||||
plex,
|
||||
jellyfin;
|
||||
|
||||
String get id => switch (this) {
|
||||
ConnectionKind.plex => 'plex',
|
||||
ConnectionKind.jellyfin => 'jellyfin',
|
||||
};
|
||||
|
||||
static ConnectionKind fromId(String id) => switch (id) {
|
||||
'plex' => ConnectionKind.plex,
|
||||
'jellyfin' => ConnectionKind.jellyfin,
|
||||
_ => throw ArgumentError('Unknown ConnectionKind id: $id'),
|
||||
};
|
||||
|
||||
MediaBackend get backend => switch (this) {
|
||||
ConnectionKind.plex => MediaBackend.plex,
|
||||
ConnectionKind.jellyfin => MediaBackend.jellyfin,
|
||||
};
|
||||
}
|
||||
|
||||
/// Health snapshot for a connection. Updated by the orchestrator each time a
|
||||
/// session is established or refreshed.
|
||||
enum ConnectionStatus { unknown, online, offline, authError, disabled }
|
||||
|
||||
/// A media server connection — a unit of authentication the user added.
|
||||
///
|
||||
/// A `PlexAccountConnection` carries one Plex account + its discovered servers + an
|
||||
/// optional active Home profile. A `JellyfinConnection` is a single server +
|
||||
/// user. Most users only ever add one connection.
|
||||
sealed class Connection {
|
||||
String get id;
|
||||
ConnectionKind get kind;
|
||||
String get displayName;
|
||||
ConnectionStatus get status;
|
||||
DateTime get createdAt;
|
||||
DateTime? get lastAuthenticatedAt;
|
||||
|
||||
/// Backend kind as a [MediaBackend] — for UI that branches on backend
|
||||
/// (badges, etc.). Just a passthrough to [kind.backend].
|
||||
MediaBackend get backend => kind.backend;
|
||||
|
||||
/// Primary label shown in connection-list UIs. Plex shows the active
|
||||
/// profile/account name; Jellyfin shows the server name.
|
||||
String get displayLabel;
|
||||
|
||||
/// Secondary line shown beneath [displayLabel] in connection-list UIs.
|
||||
/// Plex: server count; Jellyfin: `userName · baseUrl`. May be null when
|
||||
/// no useful subtitle exists.
|
||||
String? get displaySubtitle;
|
||||
|
||||
/// Backend-specific config payload, persisted as JSON. Each subclass
|
||||
/// defines the schema.
|
||||
Map<String, Object?> toConfigJson();
|
||||
}
|
||||
|
||||
/// A Plex account connection.
|
||||
///
|
||||
/// Fields here mirror what [PlexAuthService] gathers during PIN OAuth: an
|
||||
/// account token (long-lived), the per-device client identifier (so plex.tv
|
||||
/// doesn't see a "new device" each launch), and the optional Home user the
|
||||
/// user has switched into.
|
||||
class PlexAccountConnection extends Connection {
|
||||
@override
|
||||
final String id;
|
||||
|
||||
@override
|
||||
final ConnectionStatus status;
|
||||
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
|
||||
@override
|
||||
final DateTime? lastAuthenticatedAt;
|
||||
|
||||
/// plex.tv account access token.
|
||||
final String accountToken;
|
||||
|
||||
/// Per-device client identifier. Stable across launches.
|
||||
final String clientIdentifier;
|
||||
|
||||
/// Display name shown for this connection (typically the Plex account email
|
||||
/// or username, fallback "Plex").
|
||||
final String accountLabel;
|
||||
|
||||
/// Active Home user, or `null` for the main account.
|
||||
final PlexHomeUser? activeProfile;
|
||||
|
||||
/// Servers discovered for this account (cached). Populated by the auth
|
||||
/// flow and refreshed periodically.
|
||||
final List<PlexServer> servers;
|
||||
|
||||
PlexAccountConnection({
|
||||
required this.id,
|
||||
required this.accountToken,
|
||||
required this.clientIdentifier,
|
||||
required this.accountLabel,
|
||||
this.activeProfile,
|
||||
this.servers = const [],
|
||||
this.status = ConnectionStatus.unknown,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
});
|
||||
|
||||
@override
|
||||
ConnectionKind get kind => ConnectionKind.plex;
|
||||
|
||||
@override
|
||||
String get displayName => activeProfile != null && activeProfile!.title.isNotEmpty
|
||||
? '${activeProfile!.title} · $accountLabel'
|
||||
: accountLabel;
|
||||
|
||||
@override
|
||||
String get displayLabel => displayName;
|
||||
|
||||
@override
|
||||
String? get displaySubtitle => servers.length == 1 ? '1 Plex server' : '${servers.length} Plex servers';
|
||||
|
||||
PlexAccountConnection copyWith({
|
||||
String? id,
|
||||
String? accountToken,
|
||||
String? clientIdentifier,
|
||||
String? accountLabel,
|
||||
PlexHomeUser? activeProfile,
|
||||
bool clearActiveProfile = false,
|
||||
List<PlexServer>? servers,
|
||||
ConnectionStatus? status,
|
||||
DateTime? createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
return PlexAccountConnection(
|
||||
id: id ?? this.id,
|
||||
accountToken: accountToken ?? this.accountToken,
|
||||
clientIdentifier: clientIdentifier ?? this.clientIdentifier,
|
||||
accountLabel: accountLabel ?? this.accountLabel,
|
||||
activeProfile: clearActiveProfile ? null : (activeProfile ?? this.activeProfile),
|
||||
servers: servers ?? this.servers,
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt ?? this.lastAuthenticatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, Object?> toConfigJson() {
|
||||
return {
|
||||
'accountToken': accountToken,
|
||||
'clientIdentifier': clientIdentifier,
|
||||
'accountLabel': accountLabel,
|
||||
'activeProfile': activeProfile?.toJson(),
|
||||
'servers': servers.map((s) => s.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
factory PlexAccountConnection.fromConfigJson({
|
||||
required String id,
|
||||
required Map<String, Object?> json,
|
||||
required ConnectionStatus status,
|
||||
required DateTime createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
final profileJson = json['activeProfile'];
|
||||
final activeProfile = profileJson is Map<String, dynamic> ? PlexHomeUser.fromJson(profileJson) : null;
|
||||
final serversJson = json['servers'];
|
||||
final servers = serversJson is List
|
||||
? serversJson.whereType<Map<String, dynamic>>().map(PlexServer.fromJson).toList()
|
||||
: <PlexServer>[];
|
||||
return PlexAccountConnection(
|
||||
id: id,
|
||||
accountToken: json['accountToken'] as String? ?? '',
|
||||
clientIdentifier: json['clientIdentifier'] as String? ?? '',
|
||||
accountLabel: json['accountLabel'] as String? ?? 'Plex',
|
||||
activeProfile: activeProfile,
|
||||
servers: servers,
|
||||
status: status,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-server Jellyfin connection.
|
||||
class JellyfinConnection extends Connection {
|
||||
@override
|
||||
final String id;
|
||||
|
||||
@override
|
||||
final ConnectionStatus status;
|
||||
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
|
||||
@override
|
||||
final DateTime? lastAuthenticatedAt;
|
||||
|
||||
/// Active server base URL, no trailing slash. e.g. `https://jellyfin.home.lan`.
|
||||
final String baseUrl;
|
||||
|
||||
/// Candidate server URLs for this Jellyfin server, with [baseUrl] first.
|
||||
/// Existing installs only have [baseUrl]; deserialization backfills this.
|
||||
final List<String> baseUrls;
|
||||
|
||||
/// Server's reported name (System/Info).
|
||||
final String serverName;
|
||||
|
||||
/// Server's machine identifier (System/Info `Id`).
|
||||
final String serverMachineId;
|
||||
|
||||
/// Authenticated Jellyfin user id (UUID).
|
||||
final String userId;
|
||||
|
||||
/// Authenticated user's display name.
|
||||
final String userName;
|
||||
|
||||
/// Long-lived access token from `/Users/AuthenticateByName`.
|
||||
final String accessToken;
|
||||
|
||||
/// Per-device client identifier (same value sent in the
|
||||
/// `Authorization: MediaBrowser DeviceId="..."` header).
|
||||
final String deviceId;
|
||||
|
||||
/// Whether this user is a Jellyfin admin (`/Users/{id}.Policy.IsAdministrator`).
|
||||
/// Captured at auth time so the UI can gate admin-only entries (delete,
|
||||
/// match/unmatch, edit metadata) without an extra round-trip.
|
||||
final bool isAdministrator;
|
||||
|
||||
JellyfinConnection({
|
||||
required this.id,
|
||||
required this.baseUrl,
|
||||
List<String>? baseUrls,
|
||||
required this.serverName,
|
||||
required this.serverMachineId,
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
required this.accessToken,
|
||||
required this.deviceId,
|
||||
this.isAdministrator = false,
|
||||
this.status = ConnectionStatus.unknown,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
}) : baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
|
||||
|
||||
@override
|
||||
ConnectionKind get kind => ConnectionKind.jellyfin;
|
||||
|
||||
@override
|
||||
String get displayName => '$userName · $serverName';
|
||||
|
||||
@override
|
||||
String get displayLabel => serverName;
|
||||
|
||||
@override
|
||||
String? get displaySubtitle {
|
||||
final extraCount = baseUrls.length - 1;
|
||||
final suffix = extraCount > 0 ? ' +$extraCount' : '';
|
||||
return '$userName · ${_truncateUrl(baseUrl)}$suffix';
|
||||
}
|
||||
|
||||
static String _truncateUrl(String url) {
|
||||
if (url.length <= 40) return url;
|
||||
return '${url.substring(0, 37)}…';
|
||||
}
|
||||
|
||||
static List<String> _normalizeBaseUrls(String activeBaseUrl, List<String>? urls) {
|
||||
final result = <String>[];
|
||||
final seen = <String>{};
|
||||
|
||||
void add(String url) {
|
||||
final trimmed = url.trim();
|
||||
if (trimmed.isEmpty || !seen.add(trimmed)) return;
|
||||
result.add(trimmed);
|
||||
}
|
||||
|
||||
add(activeBaseUrl);
|
||||
for (final url in urls ?? const <String>[]) {
|
||||
add(url);
|
||||
}
|
||||
return List.unmodifiable(result);
|
||||
}
|
||||
|
||||
JellyfinConnection copyWith({
|
||||
String? id,
|
||||
String? baseUrl,
|
||||
List<String>? baseUrls,
|
||||
String? serverName,
|
||||
String? serverMachineId,
|
||||
String? userId,
|
||||
String? userName,
|
||||
String? accessToken,
|
||||
String? deviceId,
|
||||
bool? isAdministrator,
|
||||
ConnectionStatus? status,
|
||||
DateTime? createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
final nextBaseUrl = baseUrl ?? this.baseUrl;
|
||||
return JellyfinConnection(
|
||||
id: id ?? this.id,
|
||||
baseUrl: nextBaseUrl,
|
||||
baseUrls: baseUrls ?? this.baseUrls,
|
||||
serverName: serverName ?? this.serverName,
|
||||
serverMachineId: serverMachineId ?? this.serverMachineId,
|
||||
userId: userId ?? this.userId,
|
||||
userName: userName ?? this.userName,
|
||||
accessToken: accessToken ?? this.accessToken,
|
||||
deviceId: deviceId ?? this.deviceId,
|
||||
isAdministrator: isAdministrator ?? this.isAdministrator,
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt ?? this.lastAuthenticatedAt,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, Object?> toConfigJson() {
|
||||
return {
|
||||
'baseUrl': baseUrl,
|
||||
'baseUrls': baseUrls,
|
||||
'serverName': serverName,
|
||||
'serverMachineId': serverMachineId,
|
||||
'userId': userId,
|
||||
'userName': userName,
|
||||
'accessToken': accessToken,
|
||||
'deviceId': deviceId,
|
||||
'isAdministrator': isAdministrator,
|
||||
};
|
||||
}
|
||||
|
||||
factory JellyfinConnection.fromConfigJson({
|
||||
required String id,
|
||||
required Map<String, Object?> json,
|
||||
required ConnectionStatus status,
|
||||
required DateTime createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
final rawBaseUrls = json['baseUrls'];
|
||||
final baseUrls = rawBaseUrls is List ? rawBaseUrls.whereType<String>().toList(growable: false) : const <String>[];
|
||||
final rawBaseUrl = json['baseUrl'] as String?;
|
||||
final baseUrl = rawBaseUrl != null && rawBaseUrl.isNotEmpty
|
||||
? rawBaseUrl
|
||||
: (baseUrls.isNotEmpty ? baseUrls.first : '');
|
||||
return JellyfinConnection(
|
||||
id: id,
|
||||
baseUrl: baseUrl,
|
||||
baseUrls: baseUrls,
|
||||
serverName: json['serverName'] as String? ?? 'Jellyfin',
|
||||
serverMachineId: json['serverMachineId'] as String? ?? '',
|
||||
userId: json['userId'] as String? ?? '',
|
||||
userName: json['userName'] as String? ?? '',
|
||||
accessToken: json['accessToken'] as String? ?? '',
|
||||
deviceId: json['deviceId'] as String? ?? '',
|
||||
isAdministrator: json['isAdministrator'] as bool? ?? false,
|
||||
status: status,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'connection.dart';
|
||||
|
||||
/// Backend-neutral auth service interface. Each backend's implementation
|
||||
/// (`PlexConnectionAuthService`, `JellyfinConnectionAuthService`) drives its
|
||||
/// own UX (PIN flow vs. password) but produces the same opaque
|
||||
/// [Connection] record at the end.
|
||||
abstract class ConnectionAuthService {
|
||||
/// Best-effort check that an existing token still works. Returns false on
|
||||
/// 401/403; throws on transport failures the caller should retry.
|
||||
Future<bool> validate(Connection connection);
|
||||
|
||||
/// Refresh whatever side-channel state belongs to a connection — for Plex
|
||||
/// that's the discovered server list and Home users; for Jellyfin it's a
|
||||
/// no-op once auth has succeeded. Returns the updated connection.
|
||||
Future<Connection> refresh(Connection connection);
|
||||
|
||||
/// Revoke the token server-side and forget local credentials. The caller
|
||||
/// is responsible for removing the row from [ConnectionRegistry].
|
||||
Future<void> signOut(Connection connection);
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../models/plex/plex_home.dart';
|
||||
import '../models/plex/plex_home_user.dart';
|
||||
import '../profiles/profile.dart';
|
||||
import '../profiles/profile_registry.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../services/server_registry.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'connection.dart';
|
||||
import 'connection_registry.dart';
|
||||
|
||||
/// One-shot helpers that bridge between the legacy single-Plex-account
|
||||
/// SharedPreferences state (`StorageService.plexToken` +
|
||||
/// `currentUserUUID` + `homeUsersCache` + `ServerRegistry.getServers()`)
|
||||
/// and the new [ConnectionRegistry] world.
|
||||
///
|
||||
/// Plex Home users are NOT persisted here — the bootstrap copies the
|
||||
/// legacy `homeUsersCache` into the per-connection
|
||||
/// `plex_home_users_{connectionId}` SharedPreferences slot so
|
||||
/// [PlexHomeService] picks it up on cold start.
|
||||
class ConnectionBootstrap {
|
||||
ConnectionBootstrap({
|
||||
required this.storage,
|
||||
required this.connectionRegistry,
|
||||
required this.serverRegistry,
|
||||
required this.profileRegistry,
|
||||
Future<List<PlexHomeUser>> Function(String accountToken)? plexHomeUserFetcher,
|
||||
Future<Map<String, dynamic>> Function(String accountToken)? plexUserInfoFetcher,
|
||||
}) : _plexHomeUserFetcher = plexHomeUserFetcher ?? _fetchPlexHomeUsers,
|
||||
_plexUserInfoFetcher = plexUserInfoFetcher ?? _fetchPlexUserInfo;
|
||||
|
||||
final StorageService storage;
|
||||
final ConnectionRegistry connectionRegistry;
|
||||
final ServerRegistry serverRegistry;
|
||||
final ProfileRegistry profileRegistry;
|
||||
final Future<List<PlexHomeUser>> Function(String accountToken) _plexHomeUserFetcher;
|
||||
final Future<Map<String, dynamic>> Function(String accountToken) _plexUserInfoFetcher;
|
||||
|
||||
static const String _keyProfileMigrationV1Done = 'profile_migration_v1_done';
|
||||
|
||||
/// Run all idempotent boot-time migrations. Best-effort — errors are
|
||||
/// logged but never thrown.
|
||||
Future<void> run() async {
|
||||
await seedFromDevTokenDefine();
|
||||
final hadLegacyPlexToken = (storage.getPlexToken() ?? '').isNotEmpty;
|
||||
final hadLegacyProfileState = _hasLegacyProfileState();
|
||||
final migratedAccount = await migrateLegacyPlexAccount();
|
||||
final account = await _firstPlexAccount(migratedAccount);
|
||||
final alreadyMigrated = storage.prefs.getBool(_keyProfileMigrationV1Done) ?? false;
|
||||
if (!alreadyMigrated) {
|
||||
if (account == null && (hadLegacyPlexToken || hadLegacyProfileState)) {
|
||||
appLogger.w('Migration: legacy profile state present but Plex account was not migrated; will retry later');
|
||||
return;
|
||||
}
|
||||
// Drop any plex_home rows left over from the pre-refactor data
|
||||
// model — Plex Home users are now fetched live, never persisted.
|
||||
await profileRegistry.dropAllPlexHomeRows();
|
||||
if (account != null) {
|
||||
final prepared = await _preparePlexVirtualProfile(account);
|
||||
if (!prepared) {
|
||||
if (migratedAccount != null && hadLegacyPlexToken) {
|
||||
await connectionRegistry.remove(migratedAccount.id);
|
||||
}
|
||||
appLogger.w('Migration: could not hydrate Plex Home profiles for ${account.id}; will retry later');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (hadLegacyPlexToken) {
|
||||
await storage.clearLegacyPlexToken();
|
||||
}
|
||||
await storage.clearServersList();
|
||||
await storage.prefs.setBool(_keyProfileMigrationV1Done, true);
|
||||
} else {
|
||||
await storage.clearServersList();
|
||||
await _recoverLegacyProfilePromotionIfNeeded(account);
|
||||
await _migrateLegacyPlexHomeUsersCacheForExistingAccount(account);
|
||||
}
|
||||
}
|
||||
|
||||
bool _hasLegacyProfileState() {
|
||||
return (storage.getCurrentUserUUID() ?? '').isNotEmpty ||
|
||||
(storage.prefs.getString('home_users_cache') ?? '').isNotEmpty;
|
||||
}
|
||||
|
||||
/// Screenshot automation injects a Plex token via the `PLEX_TOKEN`
|
||||
/// dart-define so the app boots already-signed-in. Inserts a
|
||||
/// [PlexAccountConnection] directly when the env var is non-empty AND
|
||||
/// the registry doesn't already have a Plex account, fetching the user
|
||||
/// info + servers like the auth screen does. No-op in normal builds.
|
||||
Future<void> seedFromDevTokenDefine() async {
|
||||
const devToken = String.fromEnvironment('PLEX_TOKEN');
|
||||
if (devToken.isEmpty) return;
|
||||
final existing = await connectionRegistry.list();
|
||||
if (existing.whereType<PlexAccountConnection>().isNotEmpty) return;
|
||||
|
||||
try {
|
||||
final auth = await PlexAuthService.create();
|
||||
try {
|
||||
final info = await auth.getUserInfo(devToken);
|
||||
final servers = await auth.fetchServers(devToken);
|
||||
final clientId = await storage.getOrCreateClientIdentifier();
|
||||
final conn = PlexAccountConnection(
|
||||
id: 'plex.$clientId',
|
||||
accountToken: devToken,
|
||||
clientIdentifier: clientId,
|
||||
accountLabel: (info['username'] as String?) ?? (info['email'] as String?) ?? 'Plex',
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
);
|
||||
await connectionRegistry.upsert(conn);
|
||||
appLogger.i('Seeded Plex account from PLEX_TOKEN dart-define as ${conn.id}');
|
||||
} finally {
|
||||
auth.dispose();
|
||||
}
|
||||
} catch (e, st) {
|
||||
appLogger.w('PLEX_TOKEN seed failed', error: e, stackTrace: st);
|
||||
}
|
||||
}
|
||||
|
||||
/// If a legacy Plex token sits in [StorageService] without a corresponding
|
||||
/// row in [ConnectionRegistry], wrap it as a [PlexAccountConnection] and
|
||||
/// insert. Best-effort: errors are logged but never thrown.
|
||||
Future<PlexAccountConnection?> migrateLegacyPlexAccount() async {
|
||||
final token = storage.getPlexToken();
|
||||
if (token == null || token.isEmpty) return null;
|
||||
|
||||
final existing = await connectionRegistry.list();
|
||||
final alreadyMigrated = existing
|
||||
.whereType<PlexAccountConnection>()
|
||||
.where((c) => c.accountToken == token)
|
||||
.firstOrNull;
|
||||
if (alreadyMigrated != null) {
|
||||
return alreadyMigrated;
|
||||
}
|
||||
|
||||
try {
|
||||
final clientId = await storage.getOrCreateClientIdentifier();
|
||||
final servers = await serverRegistry.getServers();
|
||||
|
||||
String accountLabel = 'Plex';
|
||||
String accountUuid = '';
|
||||
try {
|
||||
final info = await _plexUserInfoFetcher(token);
|
||||
accountLabel = (info['username'] as String?) ?? (info['email'] as String?) ?? 'Plex';
|
||||
accountUuid = (info['uuid'] as String?)?.trim() ?? '';
|
||||
} catch (e) {
|
||||
appLogger.d('Plex migration: account label lookup failed (using fallback): $e');
|
||||
}
|
||||
|
||||
final conn = PlexAccountConnection(
|
||||
id: 'plex.${accountUuid.isNotEmpty ? accountUuid : clientId}',
|
||||
accountToken: token,
|
||||
clientIdentifier: clientId,
|
||||
accountLabel: accountLabel,
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
);
|
||||
await connectionRegistry.upsert(conn);
|
||||
appLogger.i('Migrated legacy Plex account into ConnectionRegistry as ${conn.id}');
|
||||
return conn;
|
||||
} catch (e, st) {
|
||||
appLogger.w('Plex account migration failed', error: e, stackTrace: st);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Hydrate Plex Home users for [account] and select a virtual Plex Home
|
||||
/// profile. Plex users are never persisted as local Plezy profiles.
|
||||
Future<bool> _preparePlexVirtualProfile(PlexAccountConnection account) async {
|
||||
final copied = await _migrateLegacyPlexHomeUsersCache(account.id);
|
||||
var users = copied ? _readPlexHomeUsersCache(account.id) : null;
|
||||
users ??= await _fetchAndCachePlexHomeUsers(account);
|
||||
final hydratedUsers = users;
|
||||
if (hydratedUsers.isEmpty) return false;
|
||||
|
||||
final legacyActiveUuid = storage.getCurrentUserUUID();
|
||||
PlexHomeUser selected;
|
||||
if (legacyActiveUuid != null && legacyActiveUuid.isNotEmpty) {
|
||||
selected = hydratedUsers.firstWhere(
|
||||
(u) => u.uuid == legacyActiveUuid,
|
||||
orElse: () => _preferredPlexHomeUser(hydratedUsers),
|
||||
);
|
||||
if (selected.uuid != legacyActiveUuid) {
|
||||
appLogger.w('Migration: legacy Plex Home UUID $legacyActiveUuid not found; using ${selected.uuid} instead');
|
||||
}
|
||||
} else {
|
||||
selected = _preferredPlexHomeUser(hydratedUsers);
|
||||
}
|
||||
|
||||
final activeProfileId = plexHomeProfileId(accountConnectionId: account.id, homeUserUuid: selected.uuid);
|
||||
await storage.setActiveProfileId(activeProfileId);
|
||||
await storage.clearCurrentUserUUID();
|
||||
await Future.wait([storage.prefs.remove('home_users_cache'), storage.prefs.remove('home_users_cache_expiry')]);
|
||||
appLogger.i('Migration: selected Plex Home profile ${selected.displayName} → $activeProfileId');
|
||||
return true;
|
||||
}
|
||||
|
||||
PlexHomeUser _preferredPlexHomeUser(List<PlexHomeUser> users) {
|
||||
return users.firstWhere((u) => u.admin, orElse: () => users.first);
|
||||
}
|
||||
|
||||
Future<bool> _migrateLegacyPlexHomeUsersCache(String connectionId) async {
|
||||
final raw = storage.prefs.getString('home_users_cache');
|
||||
if (raw == null || raw.isEmpty) return false;
|
||||
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! Map<String, dynamic>) return false;
|
||||
final home = PlexHome.fromJson(decoded);
|
||||
if (home.users.isEmpty) return false;
|
||||
await storage.savePlexHomeUsersCache(connectionId, home.users.map((u) => u.toJson()).toList());
|
||||
appLogger.i('Migration: copied ${home.users.length} Plex Home users into cache for $connectionId');
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
appLogger.w('Plex Home cache migration failed', error: e, stackTrace: st);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
List<PlexHomeUser>? _readPlexHomeUsersCache(String connectionId) {
|
||||
final raw = storage.getPlexHomeUsersCacheJson(connectionId);
|
||||
if (raw == null || raw.isEmpty) return null;
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! List) return null;
|
||||
return decoded.whereType<Map<String, dynamic>>().map(PlexHomeUser.fromJson).toList();
|
||||
} catch (e, st) {
|
||||
appLogger.w('Migration: failed to read Plex Home cache for $connectionId', error: e, stackTrace: st);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<PlexHomeUser>> _fetchAndCachePlexHomeUsers(PlexAccountConnection account) async {
|
||||
try {
|
||||
final users = await _plexHomeUserFetcher(account.accountToken);
|
||||
if (users.isNotEmpty) {
|
||||
await storage.savePlexHomeUsersCache(account.id, users.map((u) => u.toJson()).toList());
|
||||
appLogger.i('Migration: fetched ${users.length} Plex Home users for ${account.id}');
|
||||
}
|
||||
return users;
|
||||
} catch (e, st) {
|
||||
appLogger.w('Migration: Plex Home fetch failed for ${account.id}', error: e, stackTrace: st);
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _migrateLegacyPlexHomeUsersCacheForExistingAccount(PlexAccountConnection? account) async {
|
||||
if (storage.prefs.getString('home_users_cache') == null) return;
|
||||
var target = account;
|
||||
if (target == null) {
|
||||
final connections = await connectionRegistry.list();
|
||||
for (final conn in connections) {
|
||||
if (conn is PlexAccountConnection) {
|
||||
target = conn;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (target == null) return;
|
||||
final copied = await _migrateLegacyPlexHomeUsersCache(target.id);
|
||||
if (copied) {
|
||||
await Future.wait([storage.prefs.remove('home_users_cache'), storage.prefs.remove('home_users_cache_expiry')]);
|
||||
}
|
||||
}
|
||||
|
||||
Future<PlexAccountConnection?> _firstPlexAccount(PlexAccountConnection? preferred) async {
|
||||
if (preferred != null) return preferred;
|
||||
final connections = await connectionRegistry.list();
|
||||
for (final conn in connections) {
|
||||
if (conn is PlexAccountConnection) return conn;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _recoverLegacyProfilePromotionIfNeeded(PlexAccountConnection? account) async {
|
||||
if (!_hasLegacyProfileState()) return;
|
||||
final target = await _firstPlexAccount(account);
|
||||
if (target == null) return;
|
||||
await _preparePlexVirtualProfile(target);
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<PlexHomeUser>> _fetchPlexHomeUsers(String accountToken) async {
|
||||
final auth = await PlexAuthService.create();
|
||||
try {
|
||||
final home = await auth.getHomeUsers(accountToken);
|
||||
return home.users;
|
||||
} finally {
|
||||
auth.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> _fetchPlexUserInfo(String accountToken) async {
|
||||
final auth = await PlexAuthService.create();
|
||||
try {
|
||||
return await auth.getUserInfo(accountToken);
|
||||
} finally {
|
||||
auth.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
|
||||
import '../database/app_database.dart';
|
||||
import '../services/credential_vault.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'connection.dart';
|
||||
|
||||
/// CRUD over the persisted [Connections] table. The registry is the source
|
||||
/// of truth for which connections the user has added; the runtime
|
||||
/// `MultiServerManager` populates per-server clients from these records.
|
||||
///
|
||||
/// Single-connection users get a default automatically — power users with
|
||||
/// multiple connections can override it via [setDefault].
|
||||
class ConnectionRegistry {
|
||||
ConnectionRegistry(this._db);
|
||||
|
||||
final AppDatabase _db;
|
||||
|
||||
/// Emits the current set of connections after every mutation. Drift's
|
||||
/// `watch()` provides this for free.
|
||||
Stream<List<Connection>> watchConnections() {
|
||||
return (_db.select(_db.connections)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).watch().asyncMap(
|
||||
(rows) async => (await Future.wait(rows.map(_rowToConnection))).whereType<Connection>().toList(),
|
||||
);
|
||||
}
|
||||
|
||||
/// One-shot fetch of all stored connections.
|
||||
Future<List<Connection>> list() async {
|
||||
final rows = await (_db.select(_db.connections)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).get();
|
||||
return (await Future.wait(rows.map(_rowToConnection))).whereType<Connection>().toList();
|
||||
}
|
||||
|
||||
/// Lookup a connection by id.
|
||||
Future<Connection?> get(String id) async {
|
||||
final row = await (_db.select(_db.connections)..where((t) => t.id.equals(id))).getSingleOrNull();
|
||||
if (row == null) return null;
|
||||
return _rowToConnection(row);
|
||||
}
|
||||
|
||||
/// Returns the user's preferred connection — either the row marked
|
||||
/// [Connections.isDefault], or the only row if exactly one exists, or
|
||||
/// null when no connections are stored.
|
||||
Future<Connection?> getDefault() async {
|
||||
final rows = await _db.select(_db.connections).get();
|
||||
if (rows.isEmpty) return null;
|
||||
final flagged = rows.firstWhereOrNull((r) => r.isDefault);
|
||||
final picked = flagged ?? (rows.length == 1 ? rows.single : null);
|
||||
return picked == null ? null : _rowToConnection(picked);
|
||||
}
|
||||
|
||||
/// Insert or replace [connection]. If this is the first stored connection
|
||||
/// it is automatically marked default; re-upserting an existing row keeps
|
||||
/// the row's current `isDefault` (so token/metadata refreshes don't clear
|
||||
/// the default flag).
|
||||
Future<void> upsert(Connection connection) async {
|
||||
final existing = await (_db.select(_db.connections)..where((t) => t.id.equals(connection.id))).getSingleOrNull();
|
||||
final bool isDefault;
|
||||
if (existing != null) {
|
||||
isDefault = existing.isDefault;
|
||||
} else {
|
||||
final any =
|
||||
await (_db.selectOnly(_db.connections)
|
||||
..addColumns([_db.connections.id])
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
isDefault = any == null;
|
||||
}
|
||||
final protectedConfig = await CredentialVault.protectConnectionConfig(
|
||||
connection.kind.id,
|
||||
connection.toConfigJson(),
|
||||
);
|
||||
final row = ConnectionsCompanion(
|
||||
id: Value(connection.id),
|
||||
kind: Value(connection.kind.id),
|
||||
displayName: Value(connection.displayName),
|
||||
configJson: Value(jsonEncode(protectedConfig)),
|
||||
isDefault: Value(isDefault),
|
||||
createdAt: Value(connection.createdAt.millisecondsSinceEpoch),
|
||||
lastAuthenticatedAt: Value(connection.lastAuthenticatedAt?.millisecondsSinceEpoch),
|
||||
);
|
||||
await _db.into(_db.connections).insertOnConflictUpdate(row);
|
||||
appLogger.d('ConnectionRegistry: upserted ${connection.kind.id}/${connection.id}');
|
||||
}
|
||||
|
||||
/// Remove a stored connection. If the removed row was the default, the
|
||||
/// oldest remaining connection (if any) becomes default.
|
||||
Future<void> remove(String id) async {
|
||||
await (_db.delete(_db.connections)..where((t) => t.id.equals(id))).go();
|
||||
final remaining = await (_db.select(_db.connections)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).get();
|
||||
if (remaining.isNotEmpty && !remaining.any((r) => r.isDefault)) {
|
||||
await (_db.update(
|
||||
_db.connections,
|
||||
)..where((t) => t.id.equals(remaining.first.id))).write(const ConnectionsCompanion(isDefault: Value(true)));
|
||||
}
|
||||
appLogger.d('ConnectionRegistry: removed $id');
|
||||
}
|
||||
|
||||
/// Set [id] as the default connection. Clears the flag on all others.
|
||||
Future<void> setDefault(String id) async {
|
||||
await _db.transaction(() async {
|
||||
await _db.update(_db.connections).write(const ConnectionsCompanion(isDefault: Value(false)));
|
||||
await (_db.update(
|
||||
_db.connections,
|
||||
)..where((t) => t.id.equals(id))).write(const ConnectionsCompanion(isDefault: Value(true)));
|
||||
});
|
||||
}
|
||||
|
||||
/// Update only the auth-related metadata on an existing row (token,
|
||||
/// `lastAuthenticatedAt`). Used by the auth flow after a successful
|
||||
/// silent refresh without touching the rest of the config.
|
||||
Future<void> recordAuthSuccess(String id, DateTime at) async {
|
||||
await (_db.update(_db.connections)..where((t) => t.id.equals(id))).write(
|
||||
ConnectionsCompanion(lastAuthenticatedAt: Value(at.millisecondsSinceEpoch)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
await _db.delete(_db.connections).go();
|
||||
}
|
||||
|
||||
/// All Plex accounts in insertion order. Convenience over
|
||||
/// `(await list()).whereType<PlexAccountConnection>()` — cuts ~3 lines from
|
||||
/// every caller that needs to filter by backend.
|
||||
Future<List<PlexAccountConnection>> listPlexAccounts() async {
|
||||
final all = await list();
|
||||
return all.whereType<PlexAccountConnection>().toList();
|
||||
}
|
||||
|
||||
/// All Jellyfin connections in insertion order. Symmetric helper to
|
||||
/// [listPlexAccounts].
|
||||
Future<List<JellyfinConnection>> listJellyfin() async {
|
||||
final all = await list();
|
||||
return all.whereType<JellyfinConnection>().toList();
|
||||
}
|
||||
|
||||
/// Lookup a [PlexAccountConnection] by id. Returns `null` if no row
|
||||
/// matches OR the row exists but isn't a Plex account.
|
||||
Future<PlexAccountConnection?> getPlexAccount(String id) async {
|
||||
final c = await get(id);
|
||||
return c is PlexAccountConnection ? c : null;
|
||||
}
|
||||
|
||||
/// Lookup a [JellyfinConnection] by id. Returns `null` if no row matches
|
||||
/// OR the row exists but isn't a Jellyfin connection.
|
||||
Future<JellyfinConnection?> getJellyfin(String id) async {
|
||||
final c = await get(id);
|
||||
return c is JellyfinConnection ? c : null;
|
||||
}
|
||||
|
||||
Future<Connection?> _rowToConnection(ConnectionRow row) async {
|
||||
try {
|
||||
final json = jsonDecode(row.configJson) as Map<String, dynamic>;
|
||||
final kind = ConnectionKind.fromId(row.kind);
|
||||
final revealed = await CredentialVault.revealConnectionConfig(kind.id, json);
|
||||
final createdAt = DateTime.fromMillisecondsSinceEpoch(row.createdAt);
|
||||
final lastAuth = row.lastAuthenticatedAt == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(row.lastAuthenticatedAt!);
|
||||
final connection = switch (kind) {
|
||||
ConnectionKind.plex => PlexAccountConnection.fromConfigJson(
|
||||
id: row.id,
|
||||
json: revealed.config,
|
||||
status: ConnectionStatus.unknown,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuth,
|
||||
),
|
||||
ConnectionKind.jellyfin => JellyfinConnection.fromConfigJson(
|
||||
id: row.id,
|
||||
json: revealed.config,
|
||||
status: ConnectionStatus.unknown,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuth,
|
||||
),
|
||||
};
|
||||
if (revealed.migrated) {
|
||||
await upsert(connection);
|
||||
}
|
||||
return connection;
|
||||
} catch (e, st) {
|
||||
appLogger.e('ConnectionRegistry: failed to decode connection ${row.id}', error: e, stackTrace: st);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'dart:io';
|
||||
import '../media/ids.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -12,11 +13,45 @@ import '../utils/global_key_utils.dart';
|
||||
|
||||
part 'app_database.g.dart';
|
||||
|
||||
/// String values stored in [OfflineWatchProgress.actionType] (use `.name`).
|
||||
enum OfflineActionType { progress, watched, unwatched }
|
||||
/// Action queued in the offline watch-progress sync table. The serialized
|
||||
/// form ([id]) is what gets persisted in [OfflineWatchProgress.actionType];
|
||||
/// keep these strings stable across renames so existing rows resolve.
|
||||
enum OfflineActionType {
|
||||
progress,
|
||||
watched,
|
||||
unwatched;
|
||||
|
||||
// Simplified database with API cache for offline support
|
||||
@DriftDatabase(tables: [DownloadedMedia, DownloadQueue, ApiCache, OfflineWatchProgress, SyncRules])
|
||||
/// Stable string id used for persistence. Survives an enum-name rename
|
||||
/// (e.g. `progress` → `inProgress`) — `.name` would corrupt every row.
|
||||
String get id => switch (this) {
|
||||
OfflineActionType.progress => 'progress',
|
||||
OfflineActionType.watched => 'watched',
|
||||
OfflineActionType.unwatched => 'unwatched',
|
||||
};
|
||||
|
||||
/// Inverse of [id]. Throws on unknown so a typo in production doesn't
|
||||
/// silently fall back to the wrong action.
|
||||
static OfflineActionType fromId(String id) => switch (id) {
|
||||
'progress' => OfflineActionType.progress,
|
||||
'watched' => OfflineActionType.watched,
|
||||
'unwatched' => OfflineActionType.unwatched,
|
||||
_ => throw ArgumentError('Unknown OfflineActionType id: $id'),
|
||||
};
|
||||
}
|
||||
|
||||
@DriftDatabase(
|
||||
tables: [
|
||||
DownloadedMedia,
|
||||
DownloadOwners,
|
||||
DownloadQueue,
|
||||
ApiCache,
|
||||
OfflineWatchProgress,
|
||||
SyncRules,
|
||||
Connections,
|
||||
Profiles,
|
||||
ProfileConnections,
|
||||
],
|
||||
)
|
||||
class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase() : super(_openConnection());
|
||||
|
||||
@@ -26,11 +61,20 @@ class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase.forTesting(super.e);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 13;
|
||||
int get schemaVersion => 15;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
return MigrationStrategy(
|
||||
// Enforce ProfileConnections → Profiles/Connections cascades.
|
||||
// Drift turns FKs *off* during migrations, so the per-connection
|
||||
// pragma we set in `_openConnection` is wiped on first open. This
|
||||
// hook runs after migrations and re-enables it for subsequent
|
||||
// queries — also applies to in-memory test databases that don't go
|
||||
// through `_openConnection`.
|
||||
beforeOpen: (details) async {
|
||||
await customStatement('PRAGMA foreign_keys = ON');
|
||||
},
|
||||
onCreate: (Migrator m) async {
|
||||
await m.createAll();
|
||||
},
|
||||
@@ -41,19 +85,17 @@ class AppDatabase extends _$AppDatabase {
|
||||
}
|
||||
if (from < 8) {
|
||||
appLogger.i('Adding bgTaskId column to DownloadedMedia (v8 migration)');
|
||||
try {
|
||||
await m.addColumn(downloadedMedia, downloadedMedia.bgTaskId);
|
||||
} catch (e) {
|
||||
appLogger.w('bgTaskId column may already exist: $e');
|
||||
}
|
||||
await _ignoreAlreadyExists(
|
||||
'DownloadedMedia.bgTaskId column',
|
||||
() => m.addColumn(downloadedMedia, downloadedMedia.bgTaskId),
|
||||
);
|
||||
}
|
||||
if (from < 9) {
|
||||
appLogger.i('Adding mediaIndex column to DownloadedMedia (v9 migration)');
|
||||
try {
|
||||
await m.addColumn(downloadedMedia, downloadedMedia.mediaIndex);
|
||||
} catch (e) {
|
||||
appLogger.w('mediaIndex column may already exist: $e');
|
||||
}
|
||||
await _ignoreAlreadyExists(
|
||||
'DownloadedMedia.mediaIndex column',
|
||||
() => m.addColumn(downloadedMedia, downloadedMedia.mediaIndex),
|
||||
);
|
||||
}
|
||||
if (from < 10) {
|
||||
appLogger.i('Adding SyncRules table (v10 migration)');
|
||||
@@ -61,19 +103,14 @@ class AppDatabase extends _$AppDatabase {
|
||||
}
|
||||
if (from < 11) {
|
||||
appLogger.i('Adding enabled column to SyncRules (v11 migration)');
|
||||
try {
|
||||
await m.addColumn(syncRules, syncRules.enabled);
|
||||
} catch (e) {
|
||||
appLogger.w('enabled column may already exist: $e');
|
||||
}
|
||||
await _ignoreAlreadyExists('SyncRules.enabled column', () => m.addColumn(syncRules, syncRules.enabled));
|
||||
}
|
||||
if (from < 12) {
|
||||
appLogger.i('Adding downloadFilter column to SyncRules (v12 migration)');
|
||||
try {
|
||||
await m.addColumn(syncRules, syncRules.downloadFilter);
|
||||
} catch (e) {
|
||||
appLogger.w('downloadFilter column may already exist: $e');
|
||||
}
|
||||
await _ignoreAlreadyExists(
|
||||
'SyncRules.downloadFilter column',
|
||||
() => m.addColumn(syncRules, syncRules.downloadFilter),
|
||||
);
|
||||
}
|
||||
if (from < 13) {
|
||||
appLogger.i('Adding indexes on DownloadedMedia hot-queried columns (v13 migration)');
|
||||
@@ -84,60 +121,251 @@ class AppDatabase extends _$AppDatabase {
|
||||
'idx_downloaded_media_grandparent': idxDownloadedMediaGrandparent,
|
||||
};
|
||||
for (final entry in indexes.entries) {
|
||||
try {
|
||||
await m.create(entry.value);
|
||||
} catch (e) {
|
||||
appLogger.w('Index ${entry.key} may already exist: $e');
|
||||
}
|
||||
await _ignoreAlreadyExists('Index ${entry.key}', () => m.create(entry.value));
|
||||
}
|
||||
}
|
||||
if (from < 14) {
|
||||
appLogger.i(
|
||||
'Adding Connections, Profiles, ProfileConnections, DownloadOwners + scope/profile columns (v14 migration)',
|
||||
);
|
||||
|
||||
await m.createTable(connections);
|
||||
await _ignoreAlreadyExists('Index idx_connections_kind', () => m.create(idxConnectionsKind));
|
||||
|
||||
await m.createTable(profiles);
|
||||
await _ignoreAlreadyExists('Index idx_profiles_kind', () => m.create(idxProfilesKind));
|
||||
|
||||
await m.createTable(profileConnections);
|
||||
await _ignoreAlreadyExists(
|
||||
'Index idx_profile_connections_connection_id',
|
||||
() => m.create(idxProfileConnectionsConnectionId),
|
||||
);
|
||||
await _ignoreAlreadyExists(
|
||||
'Index idx_profile_connections_profile_id',
|
||||
() => m.create(idxProfileConnectionsProfileId),
|
||||
);
|
||||
|
||||
await _ignoreAlreadyExists('DownloadOwners table', () => m.createTable(downloadOwners));
|
||||
await _ignoreAlreadyExists('Index idx_download_owners_profile', () => m.create(idxDownloadOwnersProfile));
|
||||
await _ignoreAlreadyExists(
|
||||
'Index idx_download_owners_global_key',
|
||||
() => m.create(idxDownloadOwnersGlobalKey),
|
||||
);
|
||||
|
||||
await _ignoreAlreadyExists(
|
||||
'DownloadedMedia.clientScopeId column',
|
||||
() => m.addColumn(downloadedMedia, downloadedMedia.clientScopeId),
|
||||
);
|
||||
await _ignoreAlreadyExists(
|
||||
'OfflineWatchProgress.clientScopeId column',
|
||||
() => m.addColumn(offlineWatchProgress, offlineWatchProgress.clientScopeId),
|
||||
);
|
||||
await _ignoreAlreadyExists('SyncRules.profileId column', () => m.addColumn(syncRules, syncRules.profileId));
|
||||
await _ignoreAlreadyExists(
|
||||
'OfflineWatchProgress.profileId column',
|
||||
() => m.addColumn(offlineWatchProgress, offlineWatchProgress.profileId),
|
||||
);
|
||||
|
||||
await customStatement('''
|
||||
UPDATE downloaded_media
|
||||
SET client_scope_id = (
|
||||
SELECT id FROM connections
|
||||
WHERE kind = 'jellyfin'
|
||||
AND substr(id, 1, length(downloaded_media.server_id) + 1) = downloaded_media.server_id || '/'
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE client_scope_id IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM connections
|
||||
WHERE kind = 'jellyfin'
|
||||
AND substr(id, 1, length(downloaded_media.server_id) + 1) = downloaded_media.server_id || '/'
|
||||
)
|
||||
''');
|
||||
await customStatement('''
|
||||
UPDATE offline_watch_progress
|
||||
SET client_scope_id = (
|
||||
SELECT id FROM connections
|
||||
WHERE kind = 'jellyfin'
|
||||
AND substr(id, 1, length(offline_watch_progress.server_id) + 1) = offline_watch_progress.server_id || '/'
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE client_scope_id IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM connections
|
||||
WHERE kind = 'jellyfin'
|
||||
AND substr(id, 1, length(offline_watch_progress.server_id) + 1) = offline_watch_progress.server_id || '/'
|
||||
)
|
||||
''');
|
||||
|
||||
await _ignoreAlreadyExists(
|
||||
'Index idx_offline_watch_progress_server',
|
||||
() => m.create(idxOfflineWatchProgressServer),
|
||||
);
|
||||
await _ignoreAlreadyExists('Index idx_sync_rules_profile', () => m.create(idxSyncRulesProfile));
|
||||
await _ignoreAlreadyExists(
|
||||
'Index idx_offline_watch_progress_profile',
|
||||
() => m.create(idxOfflineWatchProgressProfile),
|
||||
);
|
||||
}
|
||||
if (from < 15) {
|
||||
appLogger.i('Adding mediaSourceId column to DownloadedMedia (v15 migration)');
|
||||
await _ignoreAlreadyExists(
|
||||
'DownloadedMedia.mediaSourceId column',
|
||||
() => m.addColumn(downloadedMedia, downloadedMedia.mediaSourceId),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Offline Watch Progress Operations
|
||||
// ============================================================
|
||||
Future<void> _ignoreAlreadyExists(String label, Future<void> Function() operation) async {
|
||||
try {
|
||||
await operation();
|
||||
} catch (e) {
|
||||
final message = e.toString().toLowerCase();
|
||||
if (message.contains('already exists') || message.contains('duplicate column name')) {
|
||||
appLogger.w('$label already exists during migration: $e');
|
||||
return;
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Expression<bool> _clientScopePredicate(GeneratedColumn<String> column, String? clientScopeId) {
|
||||
return clientScopeId == null ? column.isNull() : column.equals(clientScopeId);
|
||||
}
|
||||
|
||||
Expression<bool> _nullableTextPredicate(GeneratedColumn<String> column, String? value) {
|
||||
return value == null ? column.isNull() : column.equals(value);
|
||||
}
|
||||
|
||||
/// Get all pending offline watch actions for sync
|
||||
Future<List<OfflineWatchProgressItem>> getPendingWatchActions() {
|
||||
return (select(offlineWatchProgress)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).get();
|
||||
Future<List<OfflineWatchProgressItem>> getPendingWatchActions({String? profileId}) {
|
||||
final query = select(offlineWatchProgress)..orderBy([(t) => OrderingTerm.asc(t.createdAt)]);
|
||||
if (profileId != null) {
|
||||
query.where((t) => t.profileId.equals(profileId));
|
||||
}
|
||||
return query.get();
|
||||
}
|
||||
|
||||
/// Claim pre-v18 offline watch actions for [profileId]. Those rows predate
|
||||
/// profile ownership and have `NULL profile_id`; the first active profile
|
||||
/// inherits them so already-watched offline progress is not stranded.
|
||||
Future<void> adoptLegacyOfflineWatchActionsForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return;
|
||||
await (update(
|
||||
offlineWatchProgress,
|
||||
)..where((t) => t.profileId.isNull())).write(OfflineWatchProgressCompanion(profileId: Value(profileId)));
|
||||
}
|
||||
|
||||
/// Get pending watch actions for a specific server
|
||||
Future<List<OfflineWatchProgressItem>> getPendingWatchActionsForServer(String serverId) {
|
||||
Future<List<OfflineWatchProgressItem>> getPendingWatchActionsForServer(ServerId serverId, {String? profileId}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where((t) => t.serverId.equals(serverId))
|
||||
..where(
|
||||
(t) =>
|
||||
t.serverId.equals(serverId) &
|
||||
(profileId == null ? const Constant(true) : t.profileId.equals(profileId)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.asc(t.createdAt)]))
|
||||
.get();
|
||||
}
|
||||
|
||||
/// Get the latest action for a specific item
|
||||
Future<OfflineWatchProgressItem?> getLatestWatchAction(String globalKey) {
|
||||
Future<OfflineWatchProgressItem?> getLatestWatchAction(
|
||||
String globalKey, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where((t) => t.globalKey.equals(globalKey))
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt)])
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)])
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
}
|
||||
|
||||
Future<List<OfflineWatchProgressItem>> getWatchActionsForKey(
|
||||
String globalKey, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
}
|
||||
|
||||
Future<Map<String, List<OfflineWatchProgressItem>>> getWatchActionsForKeys(
|
||||
Set<String> globalKeys, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
Map<String, String?>? clientScopeIdsByGlobalKey,
|
||||
}) async {
|
||||
if (globalKeys.isEmpty) return const {};
|
||||
final rows =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.isIn(globalKeys) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
|
||||
final result = <String, List<OfflineWatchProgressItem>>{};
|
||||
for (final action in rows) {
|
||||
if (clientScopeIdsByGlobalKey != null && clientScopeIdsByGlobalKey.containsKey(action.globalKey)) {
|
||||
final expectedScope = clientScopeIdsByGlobalKey[action.globalKey];
|
||||
if (!_clientScopeValuesMatch(action.clientScopeId, expectedScope)) continue;
|
||||
}
|
||||
result.putIfAbsent(action.globalKey, () => <OfflineWatchProgressItem>[]).add(action);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Get the latest actions for multiple items in a single query
|
||||
///
|
||||
/// Returns a map of globalKey -> latest action for each key.
|
||||
/// Keys with no actions will not be present in the returned map.
|
||||
Future<Map<String, OfflineWatchProgressItem>> getLatestWatchActionsForKeys(Set<String> globalKeys) async {
|
||||
Future<Map<String, OfflineWatchProgressItem>> getLatestWatchActionsForKeys(
|
||||
Set<String> globalKeys, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
Map<String, String?>? clientScopeIdsByGlobalKey,
|
||||
}) async {
|
||||
if (globalKeys.isEmpty) return {};
|
||||
|
||||
// Query all actions for the given keys
|
||||
final allActions =
|
||||
await (select(offlineWatchProgress)
|
||||
..where((t) => t.globalKey.isIn(globalKeys))
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt)]))
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.isIn(globalKeys) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
|
||||
// Group by globalKey and take the latest (first due to ordering)
|
||||
final result = <String, OfflineWatchProgressItem>{};
|
||||
for (final action in allActions) {
|
||||
if (clientScopeIdsByGlobalKey != null && clientScopeIdsByGlobalKey.containsKey(action.globalKey)) {
|
||||
final expectedScope = clientScopeIdsByGlobalKey[action.globalKey];
|
||||
if (!_clientScopeValuesMatch(action.clientScopeId, expectedScope)) continue;
|
||||
}
|
||||
// Only keep the first (latest) action for each key
|
||||
result.putIfAbsent(action.globalKey, () => action);
|
||||
}
|
||||
@@ -145,69 +373,101 @@ class AppDatabase extends _$AppDatabase {
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Insert or update a progress action (merges with existing)
|
||||
Future<void> upsertProgressAction({
|
||||
required String serverId,
|
||||
required String ratingKey,
|
||||
required int viewOffset,
|
||||
required int duration,
|
||||
required bool shouldMarkWatched,
|
||||
}) async {
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
// Check for existing progress entry
|
||||
final existing =
|
||||
await (select(offlineWatchProgress)
|
||||
..where((t) => t.globalKey.equals(globalKey) & t.actionType.equals(OfflineActionType.progress.name))
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
|
||||
if (existing != null) {
|
||||
// Update existing progress entry
|
||||
await (update(offlineWatchProgress)..where((t) => t.id.equals(existing.id))).write(
|
||||
OfflineWatchProgressCompanion(
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
updatedAt: Value(now),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Insert new progress entry
|
||||
await into(offlineWatchProgress).insert(
|
||||
OfflineWatchProgressCompanion.insert(
|
||||
serverId: serverId,
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
actionType: OfflineActionType.progress.name,
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
}
|
||||
bool _clientScopeValuesMatch(String? actual, String? expected) {
|
||||
final normalizedActual = actual == null || actual.isEmpty ? null : actual;
|
||||
final normalizedExpected = expected == null || expected.isEmpty ? null : expected;
|
||||
return normalizedActual == normalizedExpected;
|
||||
}
|
||||
|
||||
/// Insert a manual watch action (watched or unwatched)
|
||||
/// Removes conflicting actions for the same item
|
||||
/// Insert or update a progress action (merges with existing).
|
||||
Future<void> upsertProgressAction({
|
||||
String? profileId,
|
||||
required ServerId serverId,
|
||||
String? clientScopeId,
|
||||
required String ratingKey,
|
||||
required int viewOffset,
|
||||
required int? duration,
|
||||
required bool shouldMarkWatched,
|
||||
}) async {
|
||||
final globalKey = buildGlobalKey(ServerId(serverId), ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
await transaction(() async {
|
||||
final existing =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
_nullableTextPredicate(t.profileId, profileId) &
|
||||
_clientScopePredicate(t.clientScopeId, clientScopeId) &
|
||||
t.actionType.equals(OfflineActionType.progress.id),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.asc(t.id)]))
|
||||
.get();
|
||||
|
||||
final keep = existing.isEmpty ? null : existing.first;
|
||||
if (keep != null) {
|
||||
await (update(offlineWatchProgress)..where((t) => t.id.equals(keep.id))).write(
|
||||
OfflineWatchProgressCompanion(
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
updatedAt: Value(now),
|
||||
),
|
||||
);
|
||||
final duplicateIds = existing.skip(1).map((row) => row.id).toList(growable: false);
|
||||
if (duplicateIds.isNotEmpty) {
|
||||
await (delete(offlineWatchProgress)..where((t) => t.id.isIn(duplicateIds))).go();
|
||||
}
|
||||
} else {
|
||||
await into(offlineWatchProgress).insert(
|
||||
OfflineWatchProgressCompanion.insert(
|
||||
serverId: serverId,
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
actionType: OfflineActionType.progress.id,
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Insert a manual watch action (watched or unwatched).
|
||||
/// Removes conflicting actions for the same item.
|
||||
Future<void> insertWatchAction({
|
||||
required String serverId,
|
||||
String? profileId,
|
||||
required ServerId serverId,
|
||||
String? clientScopeId,
|
||||
required String ratingKey,
|
||||
required String actionType, // 'watched' or 'unwatched'
|
||||
}) async {
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final globalKey = buildGlobalKey(ServerId(serverId), ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
// Remove conflicting actions (opposite action type and progress)
|
||||
await (delete(offlineWatchProgress)..where((t) => t.globalKey.equals(globalKey))).go();
|
||||
await (delete(offlineWatchProgress)..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
_nullableTextPredicate(t.profileId, profileId) &
|
||||
_clientScopePredicate(t.clientScopeId, clientScopeId),
|
||||
))
|
||||
.go();
|
||||
|
||||
// Insert the new action
|
||||
await into(offlineWatchProgress).insert(
|
||||
OfflineWatchProgressCompanion.insert(
|
||||
serverId: serverId,
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
actionType: actionType,
|
||||
@@ -234,10 +494,15 @@ class AppDatabase extends _$AppDatabase {
|
||||
}
|
||||
|
||||
/// Get count of pending sync items
|
||||
Future<int> getPendingSyncCount() async {
|
||||
final count = await (selectOnly(offlineWatchProgress)..addColumns([offlineWatchProgress.id.count()]))
|
||||
.map((row) => row.read(offlineWatchProgress.id.count()))
|
||||
.getSingle();
|
||||
Future<int> getPendingSyncCount({String? profileId, int? maxSyncAttempts}) async {
|
||||
final query = selectOnly(offlineWatchProgress)..addColumns([offlineWatchProgress.id.count()]);
|
||||
if (profileId != null) {
|
||||
query.where(offlineWatchProgress.profileId.equals(profileId));
|
||||
}
|
||||
if (maxSyncAttempts != null) {
|
||||
query.where(offlineWatchProgress.syncAttempts.isSmallerThanValue(maxSyncAttempts));
|
||||
}
|
||||
final count = await query.map((row) => row.read(offlineWatchProgress.id.count())).getSingle();
|
||||
return count ?? 0;
|
||||
}
|
||||
|
||||
@@ -246,12 +511,12 @@ class AppDatabase extends _$AppDatabase {
|
||||
return delete(offlineWatchProgress).go();
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Sync Rules Operations
|
||||
// ============================================================
|
||||
|
||||
Future<List<SyncRuleItem>> getSyncRules() {
|
||||
return select(syncRules).get();
|
||||
Future<List<SyncRuleItem>> getSyncRules({String? profileId}) {
|
||||
final query = select(syncRules);
|
||||
if (profileId != null) {
|
||||
query.where((t) => t.profileId.equals(profileId));
|
||||
}
|
||||
return query.get();
|
||||
}
|
||||
|
||||
Future<SyncRuleItem?> getSyncRule(String globalKey) {
|
||||
@@ -259,7 +524,8 @@ class AppDatabase extends _$AppDatabase {
|
||||
}
|
||||
|
||||
Future<void> insertSyncRule({
|
||||
required String serverId,
|
||||
String profileId = '',
|
||||
required ServerId serverId,
|
||||
required String ratingKey,
|
||||
required String globalKey,
|
||||
required String targetType,
|
||||
@@ -267,9 +533,15 @@ class AppDatabase extends _$AppDatabase {
|
||||
int mediaIndex = 0,
|
||||
String downloadFilter = 'unwatched',
|
||||
}) async {
|
||||
await into(syncRules).insertOnConflictUpdate(
|
||||
// [insertOnConflictUpdate] defaults the conflict target to the primary
|
||||
// key (`id`), which is auto-incremented — the conflict never triggers
|
||||
// and the row's UNIQUE [globalKey] constraint blows up instead. Drive
|
||||
// the upsert off the public [globalKey] so re-creating a rule for the same
|
||||
// shared target updates the existing row.
|
||||
await into(syncRules).insert(
|
||||
SyncRulesCompanion.insert(
|
||||
serverId: serverId,
|
||||
profileId: Value(profileId),
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
targetType: targetType,
|
||||
@@ -278,9 +550,39 @@ class AppDatabase extends _$AppDatabase {
|
||||
mediaIndex: Value(mediaIndex),
|
||||
downloadFilter: Value(downloadFilter),
|
||||
),
|
||||
onConflict: DoUpdate(
|
||||
(_) => SyncRulesCompanion(
|
||||
serverId: Value(serverId),
|
||||
profileId: Value(profileId),
|
||||
ratingKey: Value(ratingKey),
|
||||
targetType: Value(targetType),
|
||||
episodeCount: Value(episodeCount),
|
||||
mediaIndex: Value(mediaIndex),
|
||||
downloadFilter: Value(downloadFilter),
|
||||
),
|
||||
target: [syncRules.globalKey],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Claim pre-v16 public sync rules for [profileId]. Rules created before
|
||||
/// profile ownership have an empty profile id and a public global key.
|
||||
Future<void> adoptLegacySyncRulesForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return;
|
||||
final legacyRules = await (select(syncRules)..where((t) => t.profileId.equals(''))).get();
|
||||
for (final rule in legacyRules) {
|
||||
final scopedKey = buildProfileScopedGlobalKey(profileId, ServerId(rule.serverId), rule.ratingKey);
|
||||
final duplicate = await getSyncRule(scopedKey);
|
||||
if (duplicate != null) {
|
||||
await (delete(syncRules)..where((t) => t.id.equals(rule.id))).go();
|
||||
continue;
|
||||
}
|
||||
await (update(syncRules)..where((t) => t.id.equals(rule.id))).write(
|
||||
SyncRulesCompanion(profileId: Value(profileId), globalKey: Value(scopedKey)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateSyncRuleCount(String globalKey, int episodeCount) async {
|
||||
await (update(
|
||||
syncRules,
|
||||
@@ -309,10 +611,6 @@ class AppDatabase extends _$AppDatabase {
|
||||
await (delete(syncRules)..where((t) => t.globalKey.equals(globalKey))).go();
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Downloaded Media Queries for Watch State Sync
|
||||
// ============================================================
|
||||
|
||||
/// Get all downloaded media items (for syncing watch states)
|
||||
Future<List<DownloadedMediaItem>> getAllDownloadedMetadata() {
|
||||
return (select(downloadedMedia)..where((t) => t.status.equals(DownloadStatus.completed.index))).get();
|
||||
@@ -327,18 +625,13 @@ LazyDatabase _openConnection() {
|
||||
|
||||
final file = File(p.join(dbFolder.path, 'plezy_downloads.db'));
|
||||
|
||||
// Ensure directory exists
|
||||
if (!await file.parent.exists()) {
|
||||
await file.parent.create(recursive: true);
|
||||
}
|
||||
|
||||
// Migrate from old location on desktop (was in Documents subfolder)
|
||||
if (!Platform.isAndroid && !Platform.isIOS && !await file.exists()) {
|
||||
final oldFolder = await getApplicationDocumentsDirectory();
|
||||
final oldFile = File(p.join(oldFolder.path, 'plezy_downloads.db'));
|
||||
if (await oldFile.exists()) {
|
||||
await oldFile.rename(file.path);
|
||||
}
|
||||
await migrateLegacyDesktopDatabase(target: file);
|
||||
}
|
||||
|
||||
return NativeDatabase.createInBackground(
|
||||
@@ -346,7 +639,68 @@ LazyDatabase _openConnection() {
|
||||
setup: (db) {
|
||||
db.execute('PRAGMA journal_mode=WAL');
|
||||
db.execute('PRAGMA synchronous=NORMAL');
|
||||
// Enforce ProfileConnections → Profiles/Connections cascades.
|
||||
// SQLite requires this on every connection — it's not persisted.
|
||||
db.execute('PRAGMA foreign_keys = ON');
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Move the legacy desktop DB from `Documents/` to `ApplicationSupport/`.
|
||||
/// `File.rename` only works within a single volume — Windows users with
|
||||
/// OneDrive-redirected Documents (or any cross-drive setup) hit
|
||||
/// `ERROR_NOT_SAME_DEVICE` (errno 17), and the uncaught throw used to
|
||||
/// strand the splash on "Loading servers..." forever (#1022). Falls back
|
||||
/// to copy + delete on any [FileSystemException] and swallows all errors
|
||||
/// so a failed migration never propagates fatally.
|
||||
///
|
||||
/// [sourceOverride] and [renameOverride] are test seams — production
|
||||
/// callers leave them null.
|
||||
Future<void> migrateLegacyDesktopDatabase({
|
||||
required File target,
|
||||
File? sourceOverride,
|
||||
Future<void> Function(File source, String targetPath)? renameOverride,
|
||||
}) async {
|
||||
final File oldFile;
|
||||
try {
|
||||
if (sourceOverride != null) {
|
||||
oldFile = sourceOverride;
|
||||
} else {
|
||||
final oldFolder = await getApplicationDocumentsDirectory();
|
||||
oldFile = File(p.join(oldFolder.path, 'plezy_downloads.db'));
|
||||
}
|
||||
if (!await oldFile.exists()) return;
|
||||
} catch (e, st) {
|
||||
appLogger.w('Legacy DB migration skipped before source lookup completed', error: e, stackTrace: st);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (renameOverride != null) {
|
||||
await renameOverride(oldFile, target.path);
|
||||
} else {
|
||||
await oldFile.rename(target.path);
|
||||
}
|
||||
appLogger.i('Moved legacy DB from ${oldFile.path} → ${target.path}');
|
||||
return;
|
||||
} on FileSystemException catch (e) {
|
||||
appLogger.w('Legacy DB rename failed (osError=${e.osError?.errorCode}); falling back to copy', error: e);
|
||||
}
|
||||
|
||||
try {
|
||||
await oldFile.copy(target.path);
|
||||
try {
|
||||
await oldFile.delete();
|
||||
} catch (e) {
|
||||
// Leaving the source behind is non-fatal — the new file is canonical.
|
||||
appLogger.w('Legacy DB copied but old file delete failed: $e');
|
||||
}
|
||||
appLogger.i('Copied legacy DB from ${oldFile.path} → ${target.path}');
|
||||
} catch (e, st) {
|
||||
// Copy itself failed (disk full, source locked by OneDrive sync,
|
||||
// permissions). Leave both files alone — drift will create a fresh
|
||||
// empty DB at the new location, and a future relaunch can retry.
|
||||
appLogger.e('Legacy DB migration failed entirely', error: e, stackTrace: st);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,84 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import '../media/ids.dart';
|
||||
|
||||
import 'app_database.dart';
|
||||
import '../models/download_models.dart';
|
||||
import '../profiles/profile.dart';
|
||||
|
||||
/// Extension methods on AppDatabase for download operations
|
||||
extension DownloadDatabaseOperations on AppDatabase {
|
||||
/// Insert a new download into the database
|
||||
Future<void> addDownloadOwner({required String profileId, required String globalKey}) async {
|
||||
if (profileId.isEmpty) return;
|
||||
await into(downloadOwners).insert(
|
||||
DownloadOwnersCompanion.insert(
|
||||
profileId: profileId,
|
||||
globalKey: globalKey,
|
||||
createdAt: DateTime.now().millisecondsSinceEpoch,
|
||||
),
|
||||
mode: InsertMode.insertOrIgnore,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> removeDownloadOwner({required String profileId, required String globalKey}) async {
|
||||
await (delete(downloadOwners)..where((t) => t.profileId.equals(profileId) & t.globalKey.equals(globalKey))).go();
|
||||
}
|
||||
|
||||
Future<void> removeDownloadOwnersForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return;
|
||||
await (delete(downloadOwners)..where((t) => t.profileId.equals(profileId))).go();
|
||||
}
|
||||
|
||||
Future<Set<String>> getDownloadOwnerKeysForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return const {};
|
||||
final rows = await (select(downloadOwners)..where((t) => t.profileId.equals(profileId))).get();
|
||||
return rows.map((row) => row.globalKey).toSet();
|
||||
}
|
||||
|
||||
Future<int> getDownloadOwnerCount(String globalKey) async {
|
||||
return (await _validDownloadOwnerRows(globalKey)).length;
|
||||
}
|
||||
|
||||
Future<bool> hasDownloadOwner(String globalKey, {String? excludingProfileId}) async {
|
||||
final rows = await _validDownloadOwnerRows(globalKey, excludingProfileId: excludingProfileId);
|
||||
return rows.isNotEmpty;
|
||||
}
|
||||
|
||||
Future<List<DownloadOwnerItem>> _validDownloadOwnerRows(String globalKey, {String? excludingProfileId}) async {
|
||||
final rows = await (select(downloadOwners)..where((t) => t.globalKey.equals(globalKey))).get();
|
||||
if (rows.isEmpty) return const [];
|
||||
final candidates = rows
|
||||
.where((row) => excludingProfileId == null || excludingProfileId.isEmpty || row.profileId != excludingProfileId)
|
||||
.toList(growable: false);
|
||||
if (candidates.isEmpty) return const [];
|
||||
|
||||
final localProfileRows = await select(profiles).get();
|
||||
final localProfileIds = localProfileRows.map((row) => row.id).toSet();
|
||||
final connectionRows = await select(connections).get();
|
||||
final connectionIds = connectionRows.map((row) => row.id).toSet();
|
||||
return candidates
|
||||
.where((row) {
|
||||
if (localProfileIds.contains(row.profileId)) return true;
|
||||
final plexHome = parsePlexHomeProfileId(row.profileId);
|
||||
if (plexHome != null) return connectionIds.contains(plexHome.accountConnectionId);
|
||||
return localProfileIds.isEmpty;
|
||||
})
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
/// Claim pre-v17 shared download rows for [profileId]. Rows that already
|
||||
/// have any owner are left untouched so later profiles do not inherit them.
|
||||
Future<void> adoptLegacyDownloadsForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return;
|
||||
final rows = await select(downloadedMedia).get();
|
||||
for (final row in rows) {
|
||||
if (await getDownloadOwnerCount(row.globalKey) == 0) {
|
||||
await addDownloadOwner(profileId: profileId, globalKey: row.globalKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> insertDownload({
|
||||
required String serverId,
|
||||
required ServerId serverId,
|
||||
String? clientScopeId,
|
||||
required String ratingKey,
|
||||
required String globalKey,
|
||||
required String type,
|
||||
@@ -15,10 +86,12 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
String? grandparentRatingKey,
|
||||
required int status,
|
||||
int mediaIndex = 0,
|
||||
String? mediaSourceId,
|
||||
}) async {
|
||||
await into(downloadedMedia).insert(
|
||||
DownloadedMediaCompanion.insert(
|
||||
serverId: serverId,
|
||||
clientScopeId: Value(clientScopeId),
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
type: type,
|
||||
@@ -26,12 +99,12 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
grandparentRatingKey: Value(grandparentRatingKey),
|
||||
status: status,
|
||||
mediaIndex: Value(mediaIndex),
|
||||
mediaSourceId: Value(mediaSourceId),
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
}
|
||||
|
||||
/// Add item to download queue
|
||||
Future<void> addToQueue({
|
||||
required String mediaGlobalKey,
|
||||
int priority = 0,
|
||||
@@ -53,7 +126,6 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
/// Get next item from queue (highest priority, oldest first)
|
||||
/// Only returns items that are not paused
|
||||
Future<DownloadQueueItem?> getNextQueueItem() async {
|
||||
// Join with downloadedMedia to check status and filter out paused items
|
||||
final query = select(
|
||||
downloadQueue,
|
||||
).join([innerJoin(downloadedMedia, downloadedMedia.globalKey.equalsExp(downloadQueue.mediaGlobalKey))]);
|
||||
@@ -70,14 +142,18 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
return result?.readTable(downloadQueue);
|
||||
}
|
||||
|
||||
/// Update download status
|
||||
Future<void> updateDownloadStatus(String globalKey, int status) async {
|
||||
await (update(
|
||||
downloadedMedia,
|
||||
)..where((t) => t.globalKey.equals(globalKey))).write(DownloadedMediaCompanion(status: Value(status)));
|
||||
}
|
||||
|
||||
/// Update download progress
|
||||
Future<void> updateDownloadMediaSource(String globalKey, String? mediaSourceId) async {
|
||||
await (update(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
DownloadedMediaCompanion(mediaSourceId: Value(mediaSourceId)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> updateDownloadProgress(String globalKey, int progress, int downloadedBytes, int totalBytes) async {
|
||||
await (update(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
DownloadedMediaCompanion(
|
||||
@@ -88,7 +164,6 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
);
|
||||
}
|
||||
|
||||
/// Update video file path
|
||||
Future<void> updateVideoFilePath(String globalKey, String filePath) async {
|
||||
await (update(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
DownloadedMediaCompanion(
|
||||
@@ -98,16 +173,13 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
);
|
||||
}
|
||||
|
||||
/// Update artwork paths
|
||||
Future<void> updateArtworkPaths({required String globalKey, String? thumbPath}) async {
|
||||
await (update(
|
||||
downloadedMedia,
|
||||
)..where((t) => t.globalKey.equals(globalKey))).write(DownloadedMediaCompanion(thumbPath: Value(thumbPath)));
|
||||
}
|
||||
|
||||
/// Update download error and increment retry count
|
||||
Future<void> updateDownloadError(String globalKey, String errorMessage) async {
|
||||
// Get current retry count to increment it
|
||||
final existing = await getDownloadedMedia(globalKey);
|
||||
final currentCount = existing?.retryCount ?? 0;
|
||||
|
||||
@@ -116,52 +188,84 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
);
|
||||
}
|
||||
|
||||
/// Clear download error and reset retry count (for retry)
|
||||
Future<void> clearDownloadError(String globalKey) async {
|
||||
await (update(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
const DownloadedMediaCompanion(errorMessage: Value(null), retryCount: Value(0)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Remove item from queue
|
||||
Future<void> removeFromQueue(String mediaGlobalKey) async {
|
||||
await (delete(downloadQueue)..where((t) => t.mediaGlobalKey.equals(mediaGlobalKey))).go();
|
||||
}
|
||||
|
||||
/// Get downloaded media item
|
||||
Future<DownloadedMediaItem?> getDownloadedMedia(String globalKey) {
|
||||
return (select(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).getSingleOrNull();
|
||||
}
|
||||
|
||||
/// Delete a download
|
||||
Future<void> deleteDownload(String globalKey) async {
|
||||
await (delete(downloadOwners)..where((t) => t.globalKey.equals(globalKey))).go();
|
||||
await (delete(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).go();
|
||||
await (delete(downloadQueue)..where((t) => t.mediaGlobalKey.equals(globalKey))).go();
|
||||
}
|
||||
|
||||
/// Get all downloaded episodes for a season
|
||||
Future<List<DownloadedMediaItem>> getEpisodesBySeason(String seasonKey) {
|
||||
return (select(downloadedMedia)..where((t) => t.parentRatingKey.equals(seasonKey))).get();
|
||||
Future<List<DownloadedMediaItem>> getEpisodesBySeason(
|
||||
String seasonKey, {
|
||||
ServerId? serverId,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(downloadedMedia)..where(
|
||||
(t) =>
|
||||
t.parentRatingKey.equals(seasonKey) &
|
||||
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
|
||||
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
||||
/// Get all downloaded episodes for a show
|
||||
Future<List<DownloadedMediaItem>> getEpisodesByShow(String showKey) {
|
||||
return (select(downloadedMedia)..where((t) => t.grandparentRatingKey.equals(showKey))).get();
|
||||
Future<List<DownloadedMediaItem>> getEpisodesByShow(
|
||||
String showKey, {
|
||||
ServerId? serverId,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(downloadedMedia)..where(
|
||||
(t) =>
|
||||
t.grandparentRatingKey.equals(showKey) &
|
||||
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
|
||||
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
||||
/// Get all downloaded items for a specific server
|
||||
Future<List<DownloadedMediaItem>> getDownloadsByServerId(String serverId) {
|
||||
Future<List<DownloadedMediaItem>> getDownloadsByServerId(ServerId serverId) {
|
||||
return (select(downloadedMedia)..where((t) => t.serverId.equals(serverId))).get();
|
||||
}
|
||||
|
||||
/// Update the background_downloader task ID for a download
|
||||
Expression<bool> _optionalServerPredicate(GeneratedColumn<String> column, ServerId? serverId) {
|
||||
return serverId == null ? const Constant(true) : column.equals(serverId);
|
||||
}
|
||||
|
||||
Expression<bool> _optionalClientScopePredicate(
|
||||
GeneratedColumn<String> column,
|
||||
String? clientScopeId, {
|
||||
required bool filterClientScope,
|
||||
}) {
|
||||
if (!filterClientScope && (clientScopeId == null || clientScopeId.isEmpty)) {
|
||||
return const Constant(true);
|
||||
}
|
||||
if (clientScopeId == null || clientScopeId.isEmpty) {
|
||||
return column.isNull() | column.equals('');
|
||||
}
|
||||
return column.equals(clientScopeId);
|
||||
}
|
||||
|
||||
Future<void> updateBgTaskId(String globalKey, String? taskId) async {
|
||||
await (update(
|
||||
downloadedMedia,
|
||||
)..where((t) => t.globalKey.equals(globalKey))).write(DownloadedMediaCompanion(bgTaskId: Value(taskId)));
|
||||
}
|
||||
|
||||
/// Get the background_downloader task ID for a download
|
||||
Future<String?> getBgTaskId(String globalKey) async {
|
||||
final item = await getDownloadedMedia(globalKey);
|
||||
return item?.bgTaskId;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import 'package:drift/drift.dart';
|
||||
|
||||
/// Key-value cache table for Plex API responses.
|
||||
/// Key-value cache table for media-server API responses (Plex, Jellyfin).
|
||||
/// Used for offline support - stores raw JSON responses.
|
||||
class ApiCache extends Table {
|
||||
/// Composite key: serverId:endpoint (e.g., "abc123:/library/metadata/12345")
|
||||
/// Composite key: serverId:endpoint (e.g., "abc123:/library/metadata/12345"
|
||||
/// for Plex, "abc123:/Users/.../Items/..." for Jellyfin)
|
||||
TextColumn get cacheKey => text()();
|
||||
|
||||
/// JSON response data
|
||||
TextColumn get data => text()();
|
||||
|
||||
/// Whether this item is pinned for offline access
|
||||
@@ -37,6 +37,12 @@ class DownloadQueue extends Table {
|
||||
class DownloadedMedia extends Table {
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
TextColumn get serverId => text()();
|
||||
// Downloads are intentionally app-wide/shared, keyed by the public
|
||||
// serverId:ratingKey globalKey below. For Jellyfin, clientScopeId records
|
||||
// which scoped client produced the cached metadata/download request; it is
|
||||
// not part of download ownership and must not be used to hide or duplicate
|
||||
// the physical downloaded item per user/profile.
|
||||
TextColumn get clientScopeId => text().nullable()();
|
||||
TextColumn get ratingKey => text()();
|
||||
TextColumn get globalKey => text().unique()();
|
||||
TextColumn get type => text()();
|
||||
@@ -53,15 +59,38 @@ class DownloadedMedia extends Table {
|
||||
IntColumn get retryCount => integer().withDefault(const Constant(0))();
|
||||
TextColumn get bgTaskId => text().nullable()();
|
||||
IntColumn get mediaIndex => integer().withDefault(const Constant(0))();
|
||||
TextColumn get mediaSourceId => text().nullable()();
|
||||
}
|
||||
|
||||
/// Profile ownership for shared physical downloads.
|
||||
///
|
||||
/// [DownloadedMedia] stores one physical row per public serverId:ratingKey so
|
||||
/// files are deduped across profiles. This table controls which active profile
|
||||
/// can see/use that shared row.
|
||||
@DataClassName('DownloadOwnerItem')
|
||||
@TableIndex(name: 'idx_download_owners_profile', columns: {#profileId})
|
||||
@TableIndex(name: 'idx_download_owners_global_key', columns: {#globalKey})
|
||||
class DownloadOwners extends Table {
|
||||
TextColumn get profileId => text()();
|
||||
TextColumn get globalKey => text()();
|
||||
IntColumn get createdAt => integer()();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {profileId, globalKey};
|
||||
}
|
||||
|
||||
/// Persistent sync rules for auto-downloading unwatched episodes.
|
||||
///
|
||||
/// Each rule keeps a rolling window of N unwatched episodes for a show/season,
|
||||
/// or mirrors the current contents of a collection/playlist.
|
||||
/// Rules are owned by the active top-level profile. Downloads remain app-wide
|
||||
/// and shared by public serverId:ratingKey identity, but rule ownership must not
|
||||
/// cross users because Jellyfin permissions and watch state are user-scoped.
|
||||
@DataClassName('SyncRuleItem')
|
||||
@TableIndex(name: 'idx_sync_rules_profile', columns: {#profileId})
|
||||
class SyncRules extends Table {
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
TextColumn get profileId => text().withDefault(const Constant(''))();
|
||||
TextColumn get serverId => text()();
|
||||
TextColumn get ratingKey => text()();
|
||||
TextColumn get globalKey => text().unique()();
|
||||
@@ -74,18 +103,131 @@ class SyncRules extends Table {
|
||||
TextColumn get downloadFilter => text().withDefault(const Constant('unwatched'))();
|
||||
}
|
||||
|
||||
/// Persisted media-server connections.
|
||||
///
|
||||
/// One row per "connection" the user has added — a Plex account (with its
|
||||
/// discovered servers and active Home profile) or a single Jellyfin server.
|
||||
/// The [configJson] payload is backend-specific and parsed by the
|
||||
/// [Connection] sealed class.
|
||||
@DataClassName('ConnectionRow')
|
||||
@TableIndex(name: 'idx_connections_kind', columns: {#kind})
|
||||
class Connections extends Table {
|
||||
/// Stable identifier for the connection. For Plex it's a generated UUID
|
||||
/// (one per account); for Jellyfin it's the server's machineId.
|
||||
TextColumn get id => text()();
|
||||
|
||||
/// Backend kind: `'plex'` or `'jellyfin'`.
|
||||
TextColumn get kind => text()();
|
||||
|
||||
/// User-visible label (account email, server name).
|
||||
TextColumn get displayName => text()();
|
||||
|
||||
/// Backend-specific config payload (token, baseUrl, profile id, …).
|
||||
TextColumn get configJson => text()();
|
||||
|
||||
/// Whether this is the default connection used at app launch when only
|
||||
/// one connection is present.
|
||||
BoolColumn get isDefault => boolean().withDefault(const Constant(false))();
|
||||
|
||||
/// Timestamp this connection was added (milliseconds since epoch).
|
||||
IntColumn get createdAt => integer()();
|
||||
|
||||
/// Timestamp of the most-recent successful auth refresh (milliseconds
|
||||
/// since epoch). Null until the first successful auth.
|
||||
IntColumn get lastAuthenticatedAt => integer().nullable()();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {id};
|
||||
}
|
||||
|
||||
/// Top-level profiles — see [Profile].
|
||||
///
|
||||
/// A profile is the user-facing identity. Plex Home users auto-surface as
|
||||
/// `kind='plex_home'` rows when their parent Plex account is added; users
|
||||
/// can also create `kind='local'` rows manually. Each profile owns one or
|
||||
/// more connections via [ProfileConnections].
|
||||
@DataClassName('ProfileRow')
|
||||
@TableIndex(name: 'idx_profiles_kind', columns: {#kind})
|
||||
class Profiles extends Table {
|
||||
/// Stable identifier. For Plex Home profiles: `plex-home-{accountId}-{homeUserUuid}`
|
||||
/// (deterministic so re-discovery is idempotent). For locals: `local-{uuid}`.
|
||||
TextColumn get id => text()();
|
||||
|
||||
/// `'local'` | `'plex_home'`.
|
||||
TextColumn get kind => text()();
|
||||
|
||||
TextColumn get displayName => text()();
|
||||
|
||||
/// Plex Home users have a thumb URL; locals fall back to initials/colour.
|
||||
TextColumn get avatarThumbUrl => text().nullable()();
|
||||
|
||||
/// Per-kind config:
|
||||
/// - `local`: `{ "pinHash": "..." }`
|
||||
/// - `plex_home`: `{ "restricted": bool, "admin": bool, "hasPassword": bool, "parentConnectionId": "..." }`
|
||||
TextColumn get configJson => text()();
|
||||
|
||||
IntColumn get sortOrder => integer().withDefault(const Constant(0))();
|
||||
IntColumn get createdAt => integer()();
|
||||
IntColumn get lastUsedAt => integer().nullable()();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {id};
|
||||
}
|
||||
|
||||
/// Many-to-many join between [Profiles] and [Connections], carrying the
|
||||
/// per-profile user-level token used when the profile is active.
|
||||
///
|
||||
/// For Plex: `userToken` is a Home-user token from `/home/users/{uuid}/switch`,
|
||||
/// `userIdentifier` is the Plex Home user UUID. An empty `userToken` is a
|
||||
/// lazy-fetch sentinel — the binder calls `/switch` on first activation.
|
||||
/// The Dart-side [ProfileConnection] model surfaces empty as `null`; the
|
||||
/// column stays non-nullable here to avoid a schema migration.
|
||||
///
|
||||
/// For Jellyfin: `userToken` mirrors the Connection's accessToken (one user
|
||||
/// per Jellyfin connection) and `userIdentifier` is the Jellyfin user id.
|
||||
@DataClassName('ProfileConnectionRow')
|
||||
@TableIndex(name: 'idx_profile_connections_connection_id', columns: {#connectionId})
|
||||
@TableIndex(name: 'idx_profile_connections_profile_id', columns: {#profileId})
|
||||
class ProfileConnections extends Table {
|
||||
// No FK on profile_id: Plex Home profiles are virtual (built by
|
||||
// Profile.virtualPlexHome from PlexHomeService's live cache, never
|
||||
// persisted in `profiles`), so an FK here would reject every join row
|
||||
// they need. The two profile-delete sites clean up join rows manually
|
||||
// via ProfileConnectionRegistry.removeAllForProfile before calling
|
||||
// ProfileRegistry.remove.
|
||||
TextColumn get profileId => text()();
|
||||
TextColumn get connectionId => text().references(Connections, #id, onDelete: KeyAction.cascade)();
|
||||
TextColumn get userToken => text().withDefault(const Constant(''))();
|
||||
TextColumn get userIdentifier => text()();
|
||||
BoolColumn get isDefault => boolean().withDefault(const Constant(false))();
|
||||
IntColumn get tokenAcquiredAt => integer().nullable()();
|
||||
IntColumn get lastUsedAt => integer().nullable()();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {profileId, connectionId};
|
||||
}
|
||||
|
||||
/// Queue for offline watch progress and manual watch actions.
|
||||
///
|
||||
/// Stores watch progress updates and manual watch/unwatch actions
|
||||
/// that need to be synced to the Plex server when back online.
|
||||
/// that need to be synced to the originating media server when back online.
|
||||
@DataClassName('OfflineWatchProgressItem')
|
||||
@TableIndex(name: 'idx_offline_watch_progress_server', columns: {#serverId})
|
||||
@TableIndex(name: 'idx_offline_watch_progress_profile', columns: {#profileId})
|
||||
class OfflineWatchProgress extends Table {
|
||||
/// Auto-incrementing primary key
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
|
||||
/// Active Plezy profile that owns this queued action.
|
||||
TextColumn get profileId => text().nullable()();
|
||||
|
||||
/// Server ID this media belongs to
|
||||
TextColumn get serverId => text()();
|
||||
|
||||
/// Optional user-scoped client/cache id for backends where [serverId] is
|
||||
/// shared by multiple users on the same server.
|
||||
TextColumn get clientScopeId => text().nullable()();
|
||||
|
||||
/// Rating key of the media item
|
||||
TextColumn get ratingKey => text()();
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart';
|
||||
|
||||
/// Sealed base for backend-agnostic media-server exceptions. Both Plex and
|
||||
/// Jellyfin auth/HTTP layers throw subtypes from this hierarchy so consumers
|
||||
/// can catch with one filter and match exhaustively when they care which
|
||||
/// failure mode it is.
|
||||
sealed class MediaServerException implements Exception {
|
||||
final String message;
|
||||
const MediaServerException(this.message);
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType: $message';
|
||||
}
|
||||
|
||||
/// The supplied base URL is unreachable, returns the wrong shape, or doesn't
|
||||
/// look like the expected backend at all. Surfaces in onboarding probes
|
||||
/// (Jellyfin `/System/Info/Public`, Plex resource discovery).
|
||||
class MediaServerUrlException extends MediaServerException {
|
||||
const MediaServerUrlException(super.message);
|
||||
}
|
||||
|
||||
/// Authentication failed — bad password, expired token, disabled user,
|
||||
/// rate-limit. [statusCode] is the HTTP status when the failure was a 4xx
|
||||
/// response; null for transport-layer auth signals (e.g. token rejected
|
||||
/// during refresh).
|
||||
class MediaServerAuthException extends MediaServerException {
|
||||
final int? statusCode;
|
||||
const MediaServerAuthException(super.message, {this.statusCode});
|
||||
}
|
||||
|
||||
/// Auth polling reached a terminal server-side expiry/rejection state before
|
||||
/// the user completed the external sign-in flow.
|
||||
class MediaServerPinExpiredException extends MediaServerAuthException {
|
||||
const MediaServerPinExpiredException() : super('PIN expired before sign-in');
|
||||
}
|
||||
|
||||
/// HTTP transport / non-2xx errors. Carries the status code (when known),
|
||||
/// the parsed response body, and the originating URI so callers can log
|
||||
/// useful diagnostics. Both Plex and Jellyfin route their HTTP failures
|
||||
/// through this type — it's the canonical backend-agnostic transport
|
||||
/// exception.
|
||||
enum MediaServerHttpErrorType { connectionTimeout, receiveTimeout, connectionError, cancelled, unknown }
|
||||
|
||||
class MediaServerHttpException extends MediaServerException {
|
||||
final MediaServerHttpErrorType type;
|
||||
final int? statusCode;
|
||||
final dynamic responseData;
|
||||
final Uri? requestUri;
|
||||
|
||||
MediaServerHttpException({required this.type, String? message, this.statusCode, this.responseData, this.requestUri})
|
||||
: super(message ?? '');
|
||||
|
||||
/// Map a caught exception to a [MediaServerHttpException].
|
||||
factory MediaServerHttpException.from(Object error, {Uri? uri}) {
|
||||
return switch (error) {
|
||||
MediaServerHttpException() => error,
|
||||
RequestAbortedException(:final message, uri: final errorUri) => MediaServerHttpException(
|
||||
type: MediaServerHttpErrorType.cancelled,
|
||||
message: message,
|
||||
requestUri: errorUri ?? uri,
|
||||
),
|
||||
TimeoutException(:final message) => MediaServerHttpException(
|
||||
type: MediaServerHttpErrorType.connectionTimeout,
|
||||
message: message,
|
||||
requestUri: uri,
|
||||
),
|
||||
SocketException(:final message) => MediaServerHttpException(
|
||||
type: MediaServerHttpErrorType.connectionError,
|
||||
message: message,
|
||||
requestUri: uri,
|
||||
),
|
||||
HttpException(:final message) => MediaServerHttpException(
|
||||
type: MediaServerHttpErrorType.connectionError,
|
||||
message: message,
|
||||
requestUri: uri,
|
||||
),
|
||||
ClientException(:final message, uri: final errorUri) => MediaServerHttpException(
|
||||
type: MediaServerHttpErrorType.connectionError,
|
||||
message: message,
|
||||
requestUri: errorUri ?? uri,
|
||||
),
|
||||
_ => MediaServerHttpException(type: MediaServerHttpErrorType.unknown, message: error.toString(), requestUri: uri),
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether the error looks transient (network/timeout) and worth retrying.
|
||||
bool get isTransient =>
|
||||
type == MediaServerHttpErrorType.connectionTimeout ||
|
||||
type == MediaServerHttpErrorType.connectionError ||
|
||||
type == MediaServerHttpErrorType.receiveTimeout;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final parts = <String>[type.name];
|
||||
if (statusCode != null) parts.add('HTTP $statusCode');
|
||||
if (message.isNotEmpty) parts.add(message);
|
||||
final uri = requestUri;
|
||||
if (uri != null) parts.add('${uri.host}${uri.path}');
|
||||
return 'MediaServerHttpException(${parts.join(': ')})';
|
||||
}
|
||||
}
|
||||