diff --git a/app/build.gradle.kts b/app/build.gradle.kts index ba48e2a8..8af54c1a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -9,7 +9,7 @@ plugins { // 支持通过 -PVERSION_NAME / -PVERSION_CODE 显式传入版本信息。 // 未显式传入 VERSION_NAME 时,默认把最后一段 patch 替换为 BUILD_NUMBER。 -val baseAppVersionName = "2.3.0" +val baseAppVersionName = "2.4.0" fun String?.nonBlankOrNull(): String? = this?.trim()?.takeIf { it.isNotBlank() } diff --git a/app/src/main/assets/third_party/ijkplayer/COPYING.LGPLv2.1 b/app/src/main/assets/third_party/ijkplayer/COPYING.LGPLv2.1 new file mode 100644 index 00000000..58af0d37 --- /dev/null +++ b/app/src/main/assets/third_party/ijkplayer/COPYING.LGPLv2.1 @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/app/src/main/assets/third_party/ijkplayer/LICENSE.OpenSSL-1.1.1w b/app/src/main/assets/third_party/ijkplayer/LICENSE.OpenSSL-1.1.1w new file mode 100644 index 00000000..5b5ccdc9 --- /dev/null +++ b/app/src/main/assets/third_party/ijkplayer/LICENSE.OpenSSL-1.1.1w @@ -0,0 +1,124 @@ + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a double license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2019 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ diff --git a/app/src/main/assets/third_party/ijkplayer/LICENSE.libyuv b/app/src/main/assets/third_party/ijkplayer/LICENSE.libyuv new file mode 100644 index 00000000..c911747a --- /dev/null +++ b/app/src/main/assets/third_party/ijkplayer/LICENSE.libyuv @@ -0,0 +1,29 @@ +Copyright 2011 The LibYuv Project Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/app/src/main/assets/third_party/ijkplayer/NOTICE b/app/src/main/assets/third_party/ijkplayer/NOTICE new file mode 100644 index 00000000..f7bd78d2 --- /dev/null +++ b/app/src/main/assets/third_party/ijkplayer/NOTICE @@ -0,0 +1,189 @@ + + Copyright (c) 2005-2008, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/app/src/main/assets/third_party/ijkplayer/PROVENANCE.md b/app/src/main/assets/third_party/ijkplayer/PROVENANCE.md new file mode 100644 index 00000000..5bb6d9b2 --- /dev/null +++ b/app/src/main/assets/third_party/ijkplayer/PROVENANCE.md @@ -0,0 +1,71 @@ +# debugly/ijkplayer Android artifact + +MiruPlay pins the upstream Android release artifact for its experimental ijkplayer backend. + +## Pinned artifact + +- Upstream: https://github.com/debugly/ijkplayer +- Source commit: `2a5114f6b276744159769f17b38bfab1e74ed5ad` +- FFToolChain commit: `b7847f3b362f605085e38a0169f870bf98d0845f` +- Release tag: `k0.8.9-beta-260526101841` +- Artifact URL: https://github.com/debugly/ijkplayer/releases/download/k0.8.9-beta-260526101841/ijkplayer-cmake-release.aar +- Artifact SHA-256: `5e6c3287a361ee0be54df0eb8db0af7d6488f92f5711776ac1fc09027b997e60` +- Upstream Android POM license: LGPL-2.1 +- Core source headers: LGPL-2.1-or-later + +The AAR is not nested into another Android library. MiruPlay extracts and pins only the Java classes plus its two shipped ABI payloads: + +- `player-ijkplayer-android/libs/ijkplayer-classes.jar`: `a441dd1f60251dc4f2c6dc5d885d7a446964412be68dd2fb068b7a23d4a90f7a` +- `arm64-v8a/libijkplayer.so`: `d9f16bbcb68c5fd8ba0f56a8b6f788962631a6749e82511f0f18305527e2d10b` +- `armeabi-v7a/libijkplayer.so`: `6070c560264097dfb44e289c61f6b22dd2dacf154ad770358599210430d2318a` + +## Corresponding source and build + +The pinned source and build inputs are available at: + +- https://github.com/debugly/ijkplayer/tree/2a5114f6b276744159769f17b38bfab1e74ed5ad +- https://github.com/debugly/FFToolChain/tree/b7847f3b362f605085e38a0169f870bf98d0845f + +The published AAR is a pinned distribution artifact. Verify it independently before extraction: + +```bash +curl -L \ + https://github.com/debugly/ijkplayer/releases/download/k0.8.9-beta-260526101841/ijkplayer-cmake-release.aar \ + -o ijkplayer-cmake-release.aar +printf '%s %s\n' \ + 5e6c3287a361ee0be54df0eb8db0af7d6488f92f5711776ac1fc09027b997e60 \ + ijkplayer-cmake-release.aar | sha256sum --check +``` + +The upstream artifact workflow runs on the mutable `macos-15` GitHub image and does not pin a JDK or NDK revision. The published native bytes are therefore verified by the recorded SHA-256, not claimed to be bit-reproducible from an incompletely pinned upstream runner. + +The independent corresponding-source audit used Temurin `21.0.11+10`, Android SDK/build-tools `35/35.0.0`, Android NDK `27.0.12077973`, CMake `3.22.1`, Gradle `8.10.2`, Android Gradle Plugin `8.8.0`, and Clang `18.0.1` (`r522817`). With those tools and Git LFS/submodule support: + +```bash +git clone https://github.com/debugly/ijkplayer.git +git -C ijkplayer checkout 2a5114f6b276744159769f17b38bfab1e74ed5ad +git -C ijkplayer submodule update --init --recursive +cd ijkplayer/android +./install-ffmpeg.sh +cd ijkplayer +./gradlew :ijkplayer-cmake:assembleRelease --no-daemon +``` + +The output is `ijkplayer-cmake/build/outputs/aar/ijkplayer-cmake-release.aar`. The source tree uses symbolic links; Windows checkouts must preserve or materialize `ijkmedia` and `third-libs` before configuring CMake. + +That independent build compiled 94 ijkplayer C/C++ translation units for both shipped ABIs. Its `classes.jar` was byte-identical to the pinned artifact. Both native outputs had identical defined-global-symbol sets, ELF section sets, and dynamic dependencies. Their bytes differ because the upstream macOS NDK compiler carries PGO/LTO metadata and the independent Windows compiler does not; the independent copy also used the release version string where the upstream binary embeds source short hash `2a5114f`. + +## Static dependency audit + +`libijkplayer.so` statically incorporates these pinned FFToolChain products: + +| Component | Source revision | License | Configuration | +| --- | --- | --- | --- | +| FFmpeg fork | `ff4.0--ijk0.8.8--20210426--001` | LGPL-2.1-or-later | `--disable-gpl --disable-nonfree`; selected decoders/demuxers/protocols only | +| OpenSSL | `OpenSSL_1_1_1w` | OpenSSL/SSLeay | Static TLS/crypto dependency of libavformat | +| SoundTouch | `2.4.0` | LGPL-2.1-or-later | Static playback-rate processing | +| libyuv | `f94b8cf7` | BSD-3-Clause | Static pixel conversion | + +The final ARM ELF files dynamically depend only on Android platform libraries: `liblog`, `libandroid`, `libEGL`, `libGLESv2`, `libjnigraphics`, `libOpenSLES`, `libm`, `libz`, `libdl`, and `libc`. + +`COPYING.LGPLv2.1`, `LICENSE.OpenSSL-1.1.1w`, `LICENSE.libyuv`, and `NOTICE` accompany the binary in both this directory and the APK assets. MiruPlay remains GPLv3. diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/PlaybackUiConventions.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/PlaybackUiConventions.kt index 302377b1..7908ab40 100644 --- a/core/model/src/main/kotlin/com/miruplay/tv/model/PlaybackUiConventions.kt +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/PlaybackUiConventions.kt @@ -130,6 +130,7 @@ fun playbackBackendLabel(backend: PlaybackRenderBackend): String = PlaybackRenderBackend.EXPERIMENTAL_GL -> "旧实验 GL" PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> "实验 mpv 内嵌" PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> "实验 mpv 内嵌" + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> "实验 ijkplayer" PlaybackRenderBackend.EXPERIMENTAL_LIBVLC -> "标准 Exo" } diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/ToneMappingModels.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/ToneMappingModels.kt index 7deba6d2..3f38c025 100644 --- a/core/model/src/main/kotlin/com/miruplay/tv/model/ToneMappingModels.kt +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/ToneMappingModels.kt @@ -8,6 +8,7 @@ enum class PlaybackRenderBackend { EXPERIMENTAL_GL, EXPERIMENTAL_MPV_ANDROID, EXPERIMENTAL_MPV_EMBEDDED, + EXPERIMENTAL_IJKPLAYER, EXPERIMENTAL_LIBVLC, } @@ -17,6 +18,7 @@ fun PlaybackRenderBackend.normalizeSupportedBackend(): PlaybackRenderBackend = PlaybackRenderBackend.EXPERIMENTAL_GL -> PlaybackRenderBackend.EXPERIMENTAL_GL PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER PlaybackRenderBackend.EXPERIMENTAL_LIBVLC -> PlaybackRenderBackend.STANDARD_EXO } @@ -25,6 +27,7 @@ fun supportedPlaybackRenderBackends(): List = PlaybackRenderBackend.STANDARD_EXO, PlaybackRenderBackend.EXPERIMENTAL_GL, PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED, + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, ) @Serializable diff --git a/docs/android-tv-player-controls.md b/docs/android-tv-player-controls.md new file mode 100644 index 00000000..aeb7af62 --- /dev/null +++ b/docs/android-tv-player-controls.md @@ -0,0 +1,116 @@ +# Android TV Player Controls + +This document is the user-approved interaction contract for MiruPlay playback controls. Keep the Compose player, remote bindings, tests, and real-device verification aligned with it. + +## Status + +Implemented: + +- With controls hidden, DPAD left and right seek. +- With controls visible, the playback timeline is the default focus target and owns DPAD left and right seek, including repeat events. +- Timeline down enters the functional action row. +- Functional controls and open option panels own DPAD navigation; they must never trigger global seek. + +Implemented in the current worktree, pending integrated device verification: + +- Dedicated media remote keys. +- Player information and diagnostic side panel. +- Refined subtitle and audio parameter panels. +- A more transparent playback chrome. + +## Playback Layout + +The visual hierarchy is: + +```text +Top: Back, title, source +Center: Previous episode, seek backward, play/pause, seek forward, next episode +Bottom: Current time, focusable timeline, total time + Picture, speed, subtitles, audio +``` + +The center and bottom controls should use the existing restrained TV visual style. The chrome must become more transparent than its current black overlays, while preserving focus contrast and readable text over bright video. + +## Focus Contract + +- When chrome appears, focus the timeline. +- Timeline left and right seek. Timeline down focuses the first functional action. Timeline up enters the center transport controls. +- Center transport controls use left and right for adjacent transport buttons and down to return to the timeline. +- Functional actions use left and right for adjacent actions and up to return to the timeline. +- Opening a parameter panel preserves the invoking action as the return target. Back closes the panel and restores that action; a further Back follows existing chrome behavior. +- Never globally consume visible DPAD left or right at the player root. + +## Dedicated Remote Keys + +Dedicated keys are accelerators, not required navigation paths. On-screen controls remain available for every action. + +| Android key | User-visible behavior | +| --- | --- | +| MEDIA_REWIND | Seek backward with seek feedback; repeat continues seeking. | +| MEDIA_FAST_FORWARD | Seek forward with seek feedback; repeat continues seeking. | +| MEDIA_PREVIOUS | Select the previous logical episode when available. | +| MEDIA_NEXT | Select the next logical episode when available. | +| CAPTIONS | Show controls and open the subtitle panel when selectable tracks exist. | +| MENU | Show controls and focus the existing Picture action. Do not add a duplicate options menu. | +| INFO | Toggle the player information and diagnostics side panel. | +| SETTINGS | Remain unbound by default because it is system-owned and may not reach the app. | + +Media previous always selects the previous logical episode. At the first logical episode it is unavailable; it never inherits Media3's restart-current-item threshold behavior. + +## Information Panel + +INFO opens a right-side, read-only side panel while video remains visible. When the panel opens, hide the ordinary control chrome to avoid competing overlays. INFO again or Back closes it. + +The panel has two tabs: + +- Information: anime title, season and episode, current version/source, file/container/duration, video resolution/HDR/codec, selected audio, and selected subtitle. +- Playback and diagnostics: active backend, decoder/output host, position/duration, buffering state, playback speed, dropped-frame or equivalent metrics when available, and current sanitized error/diagnostic state. + +Use unavailable placeholders for absent metrics. Never show credentials, raw signed URLs, auth headers, or private source paths. + +## Subtitle and Audio Panels + +Subtitle and audio selection are bottom horizontal parameter panels, not side drawers. They are optimized for immediate DPAD left/right switching. + +```text +Subtitles 3 available +[Off] [Chinese Simplified - ASS] [Chinese Traditional - ASS] [English - SRT] +``` + +- CAPTIONS opens the subtitle panel and focuses the selected subtitle; when none is selected, focus Off. +- Left and right choose entries. Confirm applies immediately. +- Each entry shows language/title and a compact format plus embedded/external qualifier when available. +- Long track lists scroll horizontally while preserving the focused item onscreen. +- Back or a second CAPTIONS closes the panel and restores focus to the Subtitles action. +- The Audio panel mirrors this interaction. +- Picture and speed may use the same bottom parameter area, but only show their own controls. + +## Implementation Boundary + +Map buttons and dedicated remote keys into one shared player command path. The UI surfaces dispatch commands; the ViewModel owns UI consequences and logical episode selection; player-core owns backend transport execution. DPAD focus navigation is not a command and stays in Compose focus handling. + +Do not route embedded mpv or ijkplayer through the standard Exo MediaSession. Background media-session controls are supported only when the session represents the active authoritative standard Exo backend. + +## Ijkplayer Backend + +The experimental ijkplayer backend is implemented through `player-ijkplayer-android` and the existing generic native video host path. + +Supported and verified: + +- Local SDR H.264/AAC playback on HK1 using the packaged `arm64-v8a` library. +- Native surface lifecycle, play/pause, seek, position/duration, playback speed, completion/error state, and embedded audio-track mapping. +- Media3 `DataSource` bridging through ijkplayer `IAndroidIO`, preserving MiruPlay URI/header/WebDAV policy instead of using ijkplayer native HTTP directly. +- Requested-versus-active backend reporting and TV/WebAPI/WebUI setting parity. + +Explicit capability gates: + +- Sources with external subtitle tracks fall back to standard Exo because upstream ijkplayer has no external subtitle-source API or libass renderer. +- HDR, HDR10+, Dolby Vision, and unknown HDR fall back to standard Exo until target-device behavior is independently validated. +- Embedded timed-text subtitles are not exposed as rendered anime-grade subtitles. +- The backend is experimental and is never selected by default. + +The pinned upstream provenance, hashes, notices, and public-release rebuild requirement are documented in `third_party/ijkplayer/README.md`. + +## Verification + +Unit and Compose tests must cover hidden seek, focused-timeline seek, visible-control navigation, open-panel navigation, remote key repeat behavior, and key-up non-actions. Real-device checks must cover focus visibility, direct media keys when available, INFO panel redaction, subtitle/audio selection, and no seek from functional panels. diff --git a/player-core/build.gradle.kts b/player-core/build.gradle.kts index 3b2a4f20..931e52f7 100644 --- a/player-core/build.gradle.kts +++ b/player-core/build.gradle.kts @@ -24,6 +24,7 @@ dependencies { implementation(project(":core:common")) implementation(project(":repository-api")) implementation(project(":player-mpv-android")) + implementation(project(":player-ijkplayer-android")) api(project(":media-source")) api(libs.androidx.media3.exoplayer) implementation(libs.androidx.media3.effect) diff --git a/player-core/src/main/kotlin/com/miruplay/tv/player/ExoPlaybackController.kt b/player-core/src/main/kotlin/com/miruplay/tv/player/ExoPlaybackController.kt index 3f20662a..1d78c332 100644 --- a/player-core/src/main/kotlin/com/miruplay/tv/player/ExoPlaybackController.kt +++ b/player-core/src/main/kotlin/com/miruplay/tv/player/ExoPlaybackController.kt @@ -4,6 +4,7 @@ package com.miruplay.tv.player import android.content.Context import android.content.Intent +import android.media.session.MediaSession import android.net.Uri import android.util.Log import android.view.View @@ -42,6 +43,10 @@ import com.miruplay.tv.model.defaultToneMappingRuleSet import com.miruplay.tv.model.normalizeSupportedBackend import com.miruplay.tv.model.preferredSubtitleTrackIndex import com.miruplay.tv.repository.PlaybackPreferencesRepository +import com.miruplay.tv.player.ijk.android.MiruIjkAudioTrack +import com.miruplay.tv.player.ijk.android.MiruIjkPlaybackRequest +import com.miruplay.tv.player.ijk.android.MiruIjkPlayerListener +import com.miruplay.tv.player.ijk.android.MiruIjkSurfaceView import `is`.xyz.mpv.MiruMpvSurfaceView import dagger.hilt.android.qualifiers.ApplicationContext import java.io.File @@ -82,6 +87,7 @@ class ExoPlaybackController @Inject constructor( private val config: PlaybackConfig = PlaybackConfig(), ) : PlaybackController { private val controllerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private var remoteControlSession: MediaSession? = null private val _state = MutableStateFlow(PlaybackState.Idle) override val state: StateFlow = _state.asStateFlow() @@ -128,6 +134,17 @@ class ExoPlaybackController @Inject constructor( private var embeddedMpvView: MiruMpvSurfaceView? = null private var embeddedMpvPendingLoad: Boolean = false private var embeddedMpvPlaybackSpeed: Float = 1.0f + private var ijkPlaying: Boolean = false + private var ijkPositionMs: Long = 0L + private var ijkDurationMs: Long = 0L + private var ijkSource: PlaybackSource? = null + private var ijkHostView: ViewGroup? = null + private var ijkView: MiruIjkSurfaceView? = null + private var ijkPendingLoad: Boolean = false + private var ijkPlaybackSpeed: Float = 1.0f + private var ijkAndroidIo: IjkPlaybackAndroidIo? = null + private var ijkRequestHeaders: Map = emptyMap() + private val ijkAudioRawStreamIds = mutableListOf() // ponytail: copy-on-write 避免跨线程锁;写者基本只有 mpv 回调线程,CAS 无竞争。 private val playbackClockSamples = AtomicReference>(emptyList()) @@ -194,6 +211,7 @@ class ExoPlaybackController @Inject constructor( ) withContext(Dispatchers.Main) { currentSource = source + refreshRuntimeConfig(_currentVideoSignalDescriptor.value) dataSourceFactory.setHttpConfig(httpConfig) _state.value = PlaybackState.Loading(source) MiruLog.i( @@ -208,7 +226,17 @@ class ExoPlaybackController @Inject constructor( ) try { - ensureMediaSessionService() + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) { + activateRemoteControlSession() + playWithIjk(source, httpConfig) + return@withContext + } + if (_activeRenderBackend.value == PlaybackRenderBackend.STANDARD_EXO) { + remoteControlSession?.isActive = false + ensureMediaSessionService() + } else { + activateRemoteControlSession() + } applyVideoEffectsForCurrentConfig() if ( _activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED && @@ -262,6 +290,13 @@ class ExoPlaybackController @Inject constructor( override suspend fun pause() { withContext(Dispatchers.Main) { + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) { + ijkPlaying = false + ijkPositionMs = ijkView?.currentPositionMs() ?: ijkPositionMs + ijkView?.pausePlayback() + ijkSource?.let { _state.value = PlaybackState.Paused(it, ijkPositionMs) } + return@withContext + } if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID) { externalMpvPlaying = false val source = externalMpvSource @@ -281,10 +316,17 @@ class ExoPlaybackController @Inject constructor( } activeExoPlayer().playWhenReady = false } + updateRemoteControlPlaybackState() } override suspend fun resume() { withContext(Dispatchers.Main) { + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) { + ijkPlaying = true + ijkView?.resumePlayback() + ijkSource?.let { _state.value = PlaybackState.Playing(it, ijkPositionMs) } + return@withContext + } if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID) { externalMpvPlaying = true val source = externalMpvSource @@ -304,10 +346,23 @@ class ExoPlaybackController @Inject constructor( } activeExoPlayer().playWhenReady = true } + updateRemoteControlPlaybackState() } override suspend fun seekTo(positionMs: Long) { withContext(Dispatchers.Main) { + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) { + ijkPositionMs = positionMs.coerceAtLeast(0L) + ijkView?.seekTo(ijkPositionMs) + ijkSource?.let { source -> + _state.value = if (ijkPlaying) { + PlaybackState.Playing(source, ijkPositionMs) + } else { + PlaybackState.Paused(source, ijkPositionMs) + } + } + return@withContext + } if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID) { externalMpvPositionMs = positionMs.coerceAtLeast(0L) val source = externalMpvSource @@ -356,6 +411,8 @@ class ExoPlaybackController @Inject constructor( val currentBackend = _activeRenderBackend.value val player = activeExoPlayerOrNull() val stopPositionMs = when (currentBackend) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> + ijkView?.currentPositionMs() ?: ijkPositionMs PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> externalMpvPositionMs PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> embeddedMpvPositionMs else -> player?.currentPosition ?: 0L @@ -383,6 +440,21 @@ class ExoPlaybackController @Inject constructor( embeddedMpvPlaybackUri = null embeddedMpvPendingLoad = false embeddedMpvPlaybackSpeed = 1.0f + ijkView?.let { view -> + view.releasePlayer() + (view.parent as? ViewGroup)?.removeView(view) + } + ijkView = null + ijkPlaying = false + ijkPositionMs = 0L + ijkDurationMs = 0L + ijkSource = null + ijkPendingLoad = false + ijkPlaybackSpeed = 1.0f + runCatching { ijkAndroidIo?.close() } + ijkAndroidIo = null + ijkRequestHeaders = emptyMap() + ijkAudioRawStreamIds.clear() playbackClockSamples.set(emptyList()) dataSourceFactory.clearHttpConfig() currentSource = null @@ -405,11 +477,17 @@ class ExoPlaybackController @Inject constructor( signalProbeCompletionJob = null refreshRuntimeConfig(null) _state.value = PlaybackState.Idle + remoteControlSession?.isActive = false } } override suspend fun setPlaybackSpeed(speed: Float) { withContext(Dispatchers.Main) { + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) { + ijkPlaybackSpeed = speed.coerceIn(0.25f, 3.0f) + ijkView?.setPlaybackSpeed(ijkPlaybackSpeed) + return@withContext + } if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID) { return@withContext } @@ -424,6 +502,7 @@ class ExoPlaybackController @Inject constructor( override suspend fun setSubtitleTrack(trackIndex: Int?) { when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> Unit PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> withContext(Dispatchers.Main) { val nativeTrackId = when (trackIndex) { null -> null @@ -443,7 +522,15 @@ class ExoPlaybackController @Inject constructor( } override suspend fun setAudioTrack(trackIndex: Int) { - selectExoTrack(C.TRACK_TYPE_AUDIO, trackIndex) + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) { + withContext(Dispatchers.Main) { + val rawStreamIndex = ijkAudioRawStreamIds.getOrNull(trackIndex) ?: return@withContext + ijkView?.selectAudioRawStream(rawStreamIndex) + selectedAudioTrackIndex = trackIndex + } + } else { + selectExoTrack(C.TRACK_TYPE_AUDIO, trackIndex) + } } override fun getAvailableSubtitles(): List = availableSubtitles.toList() @@ -456,6 +543,10 @@ class ExoPlaybackController @Inject constructor( override suspend fun getCurrentPosition(): Long = withContext(Dispatchers.Main) { when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> { + ijkPositionMs = ijkView?.currentPositionMs() ?: ijkPositionMs + ijkPositionMs + } PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> externalMpvPositionMs PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> embeddedMpvPositionMs else -> activeExoPlayer().currentPosition @@ -464,6 +555,10 @@ class ExoPlaybackController @Inject constructor( override suspend fun getDuration(): Long = withContext(Dispatchers.Main) { when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> { + ijkDurationMs = ijkView?.durationMs() ?: ijkDurationMs + ijkDurationMs + } PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> 0L PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> embeddedMpvDurationMs else -> activeExoPlayer().duration @@ -472,6 +567,7 @@ class ExoPlaybackController @Inject constructor( override fun isPlaying(): Boolean = when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> ijkView?.isPlaybackActive() ?: ijkPlaying PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> externalMpvPlaying PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> embeddedMpvPlaying else -> activeExoPlayer().isPlaying @@ -479,17 +575,31 @@ class ExoPlaybackController @Inject constructor( override fun getPlayer(): Player? = when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID, PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> null else -> activeExoPlayer() } override fun usesVlcVideoLayout(): Boolean = - _activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED || + _activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER || + _requestedRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER || + _activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED || _requestedRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED override fun bindVlcVideoHost(hostView: View) { val container = hostView as? ViewGroup ?: return + if ( + _activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER || + _requestedRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER + ) { + ijkHostView = container + val view = ensureIjkView(container) + if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER && ijkPendingLoad) { + ijkSource?.let { loadIjkSource(view, it) } + } + return + } embeddedMpvHostView = container val mpvView = ensureEmbeddedMpvView(container) if (_activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED) { @@ -515,10 +625,20 @@ class ExoPlaybackController @Inject constructor( } override fun needsVlcVideoHostBinding(): Boolean = - _activeRenderBackend.value == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED && - (embeddedMpvPendingLoad || embeddedMpvHostView == null) + when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> + ijkPendingLoad || ijkHostView == null + PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> + embeddedMpvPendingLoad || embeddedMpvHostView == null + else -> false + } override fun unbindVlcVideoHost() { + ijkView?.let { view -> + (view.parent as? ViewGroup)?.removeView(view) + } + ijkHostView = null + if (ijkView == null) ijkPendingLoad = ijkSource != null embeddedMpvView?.let { view -> (view.parent as? ViewGroup)?.removeView(view) } @@ -533,6 +653,8 @@ class ExoPlaybackController @Inject constructor( val previousActiveBackend = _activeRenderBackend.value val currentPlaybackSource = currentSource val currentPlaybackPosition = when (previousActiveBackend) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> + ijkView?.currentPositionMs() ?: ijkPositionMs PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> externalMpvPositionMs PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> embeddedMpvPositionMs else -> activeExoPlayerOrNull()?.currentPosition ?: 0L @@ -597,6 +719,12 @@ class ExoPlaybackController @Inject constructor( } fun release() { + ijkView?.releasePlayer() + ijkView = null + ijkHostView = null + runCatching { ijkAndroidIo?.close() } + ijkAndroidIo = null + ijkRequestHeaders = emptyMap() embeddedMpvView?.releaseMpv() embeddedMpvView = null embeddedMpvHostView = null @@ -610,6 +738,8 @@ class ExoPlaybackController @Inject constructor( experimentalAnalyticsListener?.let(player::removeAnalyticsListener) player.release() } + remoteControlSession?.release() + remoteControlSession = null dataSourceFactory.clearHttpConfig() standardExoPlayer = null experimentalExoPlayer = null @@ -905,12 +1035,70 @@ class ExoPlaybackController @Inject constructor( } } + private fun activateRemoteControlSession() { + val session = remoteControlSession ?: MediaSession(context, "MiruPlay").also { created -> + created.setCallback(object : MediaSession.Callback() { + override fun onPlay() { + controllerScope.launch { resume() } + } + + override fun onPause() { + controllerScope.launch { pause() } + } + + override fun onFastForward() { + controllerScope.launch { seekTo(getCurrentPosition() + REMOTE_FAST_FORWARD_MS) } + } + + override fun onRewind() { + controllerScope.launch { seekTo((getCurrentPosition() - REMOTE_REWIND_MS).coerceAtLeast(0L)) } + } + }) + remoteControlSession = created + } + session.isActive = true + updateRemoteControlPlaybackState() + } + + private fun updateRemoteControlPlaybackState() { + val positionMs = when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER -> + (ijkView?.currentPositionMs() ?: ijkPositionMs).also { ijkPositionMs = it } + PlaybackRenderBackend.EXPERIMENTAL_MPV_ANDROID -> externalMpvPositionMs + PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED -> embeddedMpvPositionMs + else -> 0L + }.coerceAtLeast(0L) + remoteControlSession?.setPlaybackState( + android.media.session.PlaybackState.Builder() + .setState( + if (isPlaying()) { + android.media.session.PlaybackState.STATE_PLAYING + } else { + android.media.session.PlaybackState.STATE_PAUSED + }, + positionMs, + 1f, + ).setActions( + android.media.session.PlaybackState.ACTION_PLAY or + android.media.session.PlaybackState.ACTION_PAUSE or + android.media.session.PlaybackState.ACTION_FAST_FORWARD or + android.media.session.PlaybackState.ACTION_REWIND, + ).build(), + ) + } + private fun ensureMediaSessionService() { runCatching { context.startService(Intent(context, MiruPlayMediaService::class.java)) } } + private fun stopMediaSessionService() { + runCatching { + context.stopService(Intent(context, MiruPlayMediaService::class.java)) + } + } + private suspend fun selectExoTrack( trackType: Int, trackIndex: Int?, @@ -1031,12 +1219,23 @@ class ExoPlaybackController @Inject constructor( val descriptor = signalDescriptor ?: playbackDebugOverrides.forcedVideoSignalDescriptor ?: VideoSignalDescriptor() - val config = resolveToneMappingRuntimeConfig( + val baseConfig = resolveToneMappingRuntimeConfig( preferences = playbackPreferences.normalized(), sessionRuleOverrides = _sessionRuleOverrides.value, signalDescriptor = descriptor, requestedBackendOverride = _requestedRenderBackend.value, ) + val config = if ( + baseConfig.activeBackend == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER && + currentSource?.subtitleTracks?.isNotEmpty() == true + ) { + baseConfig.copy( + activeBackend = PlaybackRenderBackend.STANDARD_EXO, + fallbackReason = "ijkplayer 不支持外挂字幕,已回退到标准 Exo", + ) + } else { + baseConfig + } PlaybackCodecSelectionState.decoderPreference = when { config.activeBackend == PlaybackRenderBackend.EXPERIMENTAL_GL && shouldUseDedicatedExperimentalGlSurface(deviceGlEsMajorVersion) && @@ -1061,6 +1260,9 @@ class ExoPlaybackController @Inject constructor( _currentToneMappingRuleSet.value = config.appliedRuleSet _activeRenderBackend.value = config.activeBackend _fallbackReason.value = config.fallbackReason + if (config.activeBackend != PlaybackRenderBackend.STANDARD_EXO) { + stopMediaSessionService() + } if (config.activeBackend == PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED) { embeddedMpvView?.let { view -> applyEmbeddedMpvSessionOptions(view, speed = embeddedMpvPlaybackSpeed) @@ -1215,6 +1417,143 @@ class ExoPlaybackController @Inject constructor( } } + private fun playWithIjk( + source: PlaybackSource, + httpConfig: PlaybackHttpRequestConfig, + ) { + currentSource = source + ijkSource = source + ijkPositionMs = source.startPosition.coerceAtLeast(0L) + ijkDurationMs = 0L + ijkPlaying = false + ijkPendingLoad = true + ijkPlaybackSpeed = 1.0f + availableSubtitles.clear() + availableAudioTracks.clear() + ijkAudioRawStreamIds.clear() + selectedSubtitleTrackIndex = null + selectedAudioTrackIndex = null + runCatching { ijkAndroidIo?.close() } + ijkRequestHeaders = httpConfig.headersFor(source.uri) + ijkAndroidIo = IjkPlaybackAndroidIo( + dataSourceFactory = dataSourceFactory, + requestHeaders = ijkRequestHeaders, + ) + _state.value = PlaybackState.Loading(source) + ijkHostView?.let { host -> + loadIjkSource(ensureIjkView(host), source) + } + } + + private fun loadIjkSource(view: MiruIjkSurfaceView, source: PlaybackSource) { + ijkPendingLoad = false + view.load( + MiruIjkPlaybackRequest( + uri = source.uri, + startPositionMs = ijkPositionMs, + headers = ijkRequestHeaders, + androidIo = ijkAndroidIo, + hardwareDecode = true, + ), + ) + view.setPlaybackSpeed(ijkPlaybackSpeed) + } + + private fun ensureIjkView(container: ViewGroup): MiruIjkSurfaceView { + val existing = ijkView + if (existing != null) { + if (existing.parent !== container) { + (existing.parent as? ViewGroup)?.removeView(existing) + container.addView( + existing, + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ), + ) + } + return existing + } + return MiruIjkSurfaceView(context).also { view -> + view.listener = object : MiruIjkPlayerListener { + override fun onPrepared(durationMs: Long, width: Int, height: Int) { + val activeSource = ijkSource ?: return + ijkDurationMs = durationMs.coerceAtLeast(0L) + ijkPositionMs = view.currentPositionMs() + ijkPlaying = true + _state.value = PlaybackState.Playing(activeSource, ijkPositionMs) + updateRemoteControlPlaybackState() + MiruLog.i( + "IjkPlayback", + "IJK player prepared", + mapOf( + "duration_ms" to ijkDurationMs.toString(), + "width" to width.toString(), + "height" to height.toString(), + ), + ) + } + + override fun onBufferingChanged(buffering: Boolean) { + val activeSource = ijkSource ?: return + ijkPositionMs = view.currentPositionMs() + _state.value = if (buffering) { + PlaybackState.Buffering(activeSource, ijkPositionMs) + } else if (ijkPlaying) { + PlaybackState.Playing(activeSource, ijkPositionMs) + } else { + PlaybackState.Paused(activeSource, ijkPositionMs) + } + } + + override fun onCompletion() { + val activeSource = ijkSource ?: return + ijkPlaying = false + ijkPositionMs = view.currentPositionMs() + _state.value = PlaybackState.Ended(activeSource) + updateRemoteControlPlaybackState() + } + + override fun onError(code: Int, extra: Int) { + val activeSource = ijkSource + ijkPlaying = false + _state.value = PlaybackState.Error( + activeSource, + "ijkplayer 播放失败 ($code/$extra)", + ) + updateRemoteControlPlaybackState() + } + + override fun onAudioTracksChanged( + tracks: List, + selectedRawStreamIndex: Int?, + ) { + availableAudioTracks.clear() + ijkAudioRawStreamIds.clear() + tracks.forEachIndexed { index, track -> + ijkAudioRawStreamIds += track.rawStreamIndex + availableAudioTracks += AudioTrack( + index = index, + language = track.language, + title = track.details, + codec = null, + ) + } + selectedAudioTrackIndex = selectedRawStreamIndex?.let(ijkAudioRawStreamIds::indexOf) + ?.takeIf { it >= 0 } + } + } + ijkView = view + container.addView( + view, + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ), + ) + } + } + private fun playWithEmbeddedMpv( source: PlaybackSource, httpConfig: PlaybackHttpRequestConfig, @@ -1460,7 +1799,12 @@ class ExoPlaybackController @Inject constructor( standardPlayerOrNull() } - private fun isCurrentPlayer(player: ExoPlayer): Boolean = player === activeExoPlayer() + private fun isCurrentPlayer(player: ExoPlayer): Boolean = + when (_activeRenderBackend.value) { + PlaybackRenderBackend.EXPERIMENTAL_GL -> player === experimentalPlayerOrNull() + PlaybackRenderBackend.STANDARD_EXO -> player === standardPlayerOrNull() + else -> false + } private fun stopInactivePlayers(activePlayer: ExoPlayer) { standardPlayerOrNull()?.let { player -> @@ -1591,6 +1935,8 @@ internal fun mediaTrackTypeLabel(trackType: Int): String = when (trackType) { else -> trackType.toString() } +private const val REMOTE_FAST_FORWARD_MS = 30_000L +private const val REMOTE_REWIND_MS = 10_000L private const val MAX_PLAYBACK_CLOCK_SAMPLES = 240 typealias Tracks = androidx.media3.common.Tracks diff --git a/player-core/src/main/kotlin/com/miruplay/tv/player/IjkPlaybackAndroidIo.kt b/player-core/src/main/kotlin/com/miruplay/tv/player/IjkPlaybackAndroidIo.kt new file mode 100644 index 00000000..7edc0186 --- /dev/null +++ b/player-core/src/main/kotlin/com/miruplay/tv/player/IjkPlaybackAndroidIo.kt @@ -0,0 +1,95 @@ +package com.miruplay.tv.player + +import android.net.Uri +import androidx.media3.common.C +import androidx.media3.common.util.UnstableApi +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.DataSpec +import com.miruplay.tv.player.ijk.android.MiruIjkAndroidIo +import java.io.IOException + +@UnstableApi +internal class IjkPlaybackAndroidIo( + private val dataSourceFactory: DataSource.Factory, + private val requestHeaders: Map = emptyMap(), +) : MiruIjkAndroidIo { + private var dataSource: DataSource? = null + private var uri: Uri? = null + private var position = 0L + private var totalLength = C.LENGTH_UNSET.toLong() + + @Synchronized + override fun open(url: String): Int { + close() + uri = Uri.parse(url) + position = 0L + openAt(position) + return 0 + } + + @Synchronized + override fun read(buffer: ByteArray, size: Int): Int { + val source = dataSource ?: throw IOException("IJK data source is not open") + val read = source.read(buffer, 0, size.coerceIn(0, buffer.size)) + if (read > 0) position += read + return read + } + + @Synchronized + override fun seek(offset: Long, whence: Int): Long { + if (whence and AVSEEK_SIZE != 0) return totalLength + val target = when (whence and SEEK_MODE_MASK) { + SEEK_SET -> offset + SEEK_CUR -> position + offset + SEEK_END -> { + if (totalLength == C.LENGTH_UNSET.toLong()) return -1L + totalLength + offset + } + else -> return -1L + }.coerceAtLeast(0L) + if (target == position) return position + openAt(target) + return position + } + + @Synchronized + override fun close(): Int { + dataSource?.close() + dataSource = null + uri = null + position = 0L + totalLength = C.LENGTH_UNSET.toLong() + return 0 + } + + private fun openAt(targetPosition: Long) { + val sourceUri = uri ?: throw IOException("IJK data source URI is missing") + dataSource?.close() + val next = dataSourceFactory.createDataSource() + try { + val remainingLength = next.open( + DataSpec.Builder() + .setUri(sourceUri) + .setPosition(targetPosition) + .setHttpRequestHeaders(requestHeaders) + .build(), + ) + dataSource = next + position = targetPosition + if (remainingLength != C.LENGTH_UNSET.toLong()) { + totalLength = targetPosition + remainingLength + } + } catch (error: Throwable) { + runCatching { next.close() } + throw IOException("Failed to open IJK data source", error) + } + } + + private companion object { + const val SEEK_SET = 0 + const val SEEK_CUR = 1 + const val SEEK_END = 2 + const val SEEK_MODE_MASK = 0xFFFF + const val AVSEEK_SIZE = 0x10000 + } +} diff --git a/player-core/src/main/kotlin/com/miruplay/tv/player/MiruPlayMediaService.kt b/player-core/src/main/kotlin/com/miruplay/tv/player/MiruPlayMediaService.kt index 10b747a9..adbb87b0 100644 --- a/player-core/src/main/kotlin/com/miruplay/tv/player/MiruPlayMediaService.kt +++ b/player-core/src/main/kotlin/com/miruplay/tv/player/MiruPlayMediaService.kt @@ -76,10 +76,10 @@ class MiruPlayMediaService : MediaSessionService() { override fun onDestroy() { MiruLog.i("MiruPlayMediaService", "Media service destroying") mediaSession?.run { - player.release() release() mediaSession = null } + exoPlayer?.removeListener(playerListener) exoPlayer = null super.onDestroy() } diff --git a/player-core/src/main/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolver.kt b/player-core/src/main/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolver.kt index 67a7a5ab..ae16f5ab 100644 --- a/player-core/src/main/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolver.kt +++ b/player-core/src/main/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolver.kt @@ -32,7 +32,11 @@ fun resolveToneMappingRuntimeConfig( ruleKey = ruleKey, signalDescriptor = signalDescriptor, ) - val activeBackend = requestedBackend + val activeBackend = when { + requestedBackend == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER && signalDescriptor.isHdr -> + PlaybackRenderBackend.STANDARD_EXO + else -> requestedBackend + } return ToneMappingRuntimeConfig( ruleKey = ruleKey, appliedRuleSet = appliedRuleSet, @@ -50,5 +54,8 @@ private fun backendStatusMessage( if (requestedBackend == PlaybackRenderBackend.STANDARD_EXO) { return null } + if (requestedBackend == PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER && signalDescriptor.isHdr) { + return "ijkplayer 尚未验证 HDR,已回退到标准 Exo" + } return null } diff --git a/player-core/src/test/kotlin/com/miruplay/tv/player/ExoPlaybackControllerLazyInitTest.kt b/player-core/src/test/kotlin/com/miruplay/tv/player/ExoPlaybackControllerLazyInitTest.kt index 84c7a051..34d8be0e 100644 --- a/player-core/src/test/kotlin/com/miruplay/tv/player/ExoPlaybackControllerLazyInitTest.kt +++ b/player-core/src/test/kotlin/com/miruplay/tv/player/ExoPlaybackControllerLazyInitTest.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Before import org.junit.Test @@ -87,6 +88,22 @@ class ExoPlaybackControllerLazyInitTest { assertEquals(1, experimentalProvider.getCallCount) } + @Test + fun `ijk backend does not initialize either exo player`() = runBlocking { + val standardProvider = CountingProvider { mockk(relaxed = true) } + val experimentalProvider = CountingProvider { mockk(relaxed = true) } + val controller = createController( + standardProvider = standardProvider, + experimentalProvider = experimentalProvider, + ) + + controller.setRequestedRenderBackend(PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER) + + assertNull(controller.getPlayer()) + assertEquals(0, standardProvider.getCallCount) + assertEquals(0, experimentalProvider.getCallCount) + } + @Test fun `refreshing runtime config for standard backend does not initialize experimental exo player`() = runBlocking { val standardPlayer = mockk(relaxed = true) diff --git a/player-core/src/test/kotlin/com/miruplay/tv/player/IjkPlaybackAndroidIoTest.kt b/player-core/src/test/kotlin/com/miruplay/tv/player/IjkPlaybackAndroidIoTest.kt new file mode 100644 index 00000000..1bc959eb --- /dev/null +++ b/player-core/src/test/kotlin/com/miruplay/tv/player/IjkPlaybackAndroidIoTest.kt @@ -0,0 +1,69 @@ +package com.miruplay.tv.player + +import android.net.Uri +import androidx.media3.common.C +import androidx.media3.datasource.ByteArrayDataSource +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.DataSpec +import androidx.media3.datasource.TransferListener +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class IjkPlaybackAndroidIoTest { + @Test + fun `bridge reopens Media3 data source for absolute seeks`() { + val bytes = "0123456789".encodeToByteArray() + val bridge = IjkPlaybackAndroidIo(DataSource.Factory { ByteArrayDataSource(bytes) }) + val buffer = ByteArray(4) + + assertEquals(0, bridge.open("memory://episode")) + assertEquals(10L, bridge.seek(0L, AVSEEK_SIZE)) + assertEquals(4, bridge.read(buffer, buffer.size)) + assertArrayEquals("0123".encodeToByteArray(), buffer) + assertEquals(7L, bridge.seek(7L, SEEK_SET)) + assertEquals(3, bridge.read(buffer, buffer.size)) + assertArrayEquals("7893".encodeToByteArray(), buffer) + assertEquals(0, bridge.close()) + } + + @Test + fun `bridge forwards request headers to every Media3 open`() { + val source = CapturingDataSource() + val bridge = IjkPlaybackAndroidIo( + dataSourceFactory = DataSource.Factory { source }, + requestHeaders = mapOf("X-Test-Header" to "expected"), + ) + + assertEquals(0, bridge.open("https://play.example/episode.mkv")) + assertEquals("expected", source.openedDataSpec?.httpRequestHeaders?.get("X-Test-Header")) + assertEquals(0, bridge.close()) + } + + private class CapturingDataSource : DataSource { + var openedDataSpec: DataSpec? = null + + override fun addTransferListener(transferListener: TransferListener) = Unit + + override fun open(dataSpec: DataSpec): Long { + openedDataSpec = dataSpec + return 0L + } + + override fun read(buffer: ByteArray, offset: Int, length: Int): Int = C.RESULT_END_OF_INPUT + + override fun getUri(): Uri? = openedDataSpec?.uri + + override fun close() = Unit + } + + private companion object { + const val SEEK_SET = 0 + const val AVSEEK_SIZE = 0x10000 + } +} diff --git a/player-core/src/test/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolverTest.kt b/player-core/src/test/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolverTest.kt index 6855741f..ee76beae 100644 --- a/player-core/src/test/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolverTest.kt +++ b/player-core/src/test/kotlin/com/miruplay/tv/player/ToneMappingRuntimeConfigResolverTest.kt @@ -76,6 +76,34 @@ class ToneMappingRuntimeConfigResolverTest { assertNull(config.fallbackReason) } + @Test + fun `resolver keeps ijkplayer active for SDR`() { + val config = resolveToneMappingRuntimeConfig( + preferences = FormatAwareToneMappingPreferences(), + sessionRuleOverrides = emptyMap(), + signalDescriptor = VideoSignalDescriptor(signalKind = VideoSignalKind.SDR), + requestedBackendOverride = PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, + ) + + assertEquals(PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, config.requestedBackend) + assertEquals(PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, config.activeBackend) + assertNull(config.fallbackReason) + } + + @Test + fun `resolver falls back from ijkplayer for unverified HDR`() { + val config = resolveToneMappingRuntimeConfig( + preferences = FormatAwareToneMappingPreferences(), + sessionRuleOverrides = emptyMap(), + signalDescriptor = VideoSignalDescriptor(signalKind = VideoSignalKind.HDR10), + requestedBackendOverride = PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, + ) + + assertEquals(PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, config.requestedBackend) + assertEquals(PlaybackRenderBackend.STANDARD_EXO, config.activeBackend) + assertEquals("ijkplayer 尚未验证 HDR,已回退到标准 Exo", config.fallbackReason) + } + @Test fun `resolver respects explicit backend override for current session`() { val preferences = FormatAwareToneMappingPreferences( diff --git a/player-ijkplayer-android/build.gradle.kts b/player-ijkplayer-android/build.gradle.kts new file mode 100644 index 00000000..f3ff6e62 --- /dev/null +++ b/player-ijkplayer-android/build.gradle.kts @@ -0,0 +1,30 @@ +plugins { + id("com.android.library") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.miruplay.tv.player.ijk.android" + compileSdk = 35 + + defaultConfig { + minSdk = 28 + consumerProguardFiles("consumer-rules.pro") + } + + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } + + buildFeatures { + buildConfig = false + } +} + +dependencies { + implementation(files("libs/ijkplayer-classes.jar")) + implementation(libs.androidx.core) + testImplementation(libs.junit) +} diff --git a/player-ijkplayer-android/consumer-rules.pro b/player-ijkplayer-android/consumer-rules.pro new file mode 100644 index 00000000..7660d2fe --- /dev/null +++ b/player-ijkplayer-android/consumer-rules.pro @@ -0,0 +1,3 @@ +# Keep the upstream JNI entry points and Java API used by native registration. +-keep class tv.danmaku.ijk.media.player.** { *; } +-keep class tv.danmaku.ijk.media.player.misc.** { *; } diff --git a/player-ijkplayer-android/libs/ijkplayer-classes.jar b/player-ijkplayer-android/libs/ijkplayer-classes.jar new file mode 100644 index 00000000..132a4d38 Binary files /dev/null and b/player-ijkplayer-android/libs/ijkplayer-classes.jar differ diff --git a/player-ijkplayer-android/src/main/AndroidManifest.xml b/player-ijkplayer-android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..cc947c56 --- /dev/null +++ b/player-ijkplayer-android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/player-ijkplayer-android/src/main/jniLibs/arm64-v8a/libijkplayer.so b/player-ijkplayer-android/src/main/jniLibs/arm64-v8a/libijkplayer.so new file mode 100644 index 00000000..fedce90a Binary files /dev/null and b/player-ijkplayer-android/src/main/jniLibs/arm64-v8a/libijkplayer.so differ diff --git a/player-ijkplayer-android/src/main/jniLibs/armeabi-v7a/libijkplayer.so b/player-ijkplayer-android/src/main/jniLibs/armeabi-v7a/libijkplayer.so new file mode 100644 index 00000000..ff05691c Binary files /dev/null and b/player-ijkplayer-android/src/main/jniLibs/armeabi-v7a/libijkplayer.so differ diff --git a/player-ijkplayer-android/src/main/kotlin/com/miruplay/tv/player/ijk/android/MiruIjkSurfaceView.kt b/player-ijkplayer-android/src/main/kotlin/com/miruplay/tv/player/ijk/android/MiruIjkSurfaceView.kt new file mode 100644 index 00000000..508478f5 --- /dev/null +++ b/player-ijkplayer-android/src/main/kotlin/com/miruplay/tv/player/ijk/android/MiruIjkSurfaceView.kt @@ -0,0 +1,195 @@ +package com.miruplay.tv.player.ijk.android + +import android.content.Context +import android.net.Uri +import android.util.AttributeSet +import android.view.SurfaceHolder +import android.view.SurfaceView +import java.io.IOException +import tv.danmaku.ijk.media.player.IjkMediaPlayer +import tv.danmaku.ijk.media.player.IMediaPlayer +import tv.danmaku.ijk.media.player.misc.IAndroidIO +import tv.danmaku.ijk.media.player.misc.ITrackInfo + +interface MiruIjkAndroidIo { + @Throws(IOException::class) + fun open(url: String): Int + + @Throws(IOException::class) + fun read(buffer: ByteArray, size: Int): Int + + @Throws(IOException::class) + fun seek(offset: Long, whence: Int): Long + + @Throws(IOException::class) + fun close(): Int +} + +data class MiruIjkPlaybackRequest( + val uri: String, + val startPositionMs: Long = 0L, + val headers: Map = emptyMap(), + val androidIo: MiruIjkAndroidIo? = null, + val hardwareDecode: Boolean = true, +) + +data class MiruIjkAudioTrack( + val rawStreamIndex: Int, + val language: String, + val details: String, +) + +interface MiruIjkPlayerListener { + fun onPrepared(durationMs: Long, width: Int, height: Int) + fun onBufferingChanged(buffering: Boolean) + fun onCompletion() + fun onError(code: Int, extra: Int) + fun onAudioTracksChanged(tracks: List, selectedRawStreamIndex: Int?) +} + +class MiruIjkSurfaceView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : SurfaceView(context, attrs), SurfaceHolder.Callback { + var listener: MiruIjkPlayerListener? = null + + private var player: IjkMediaPlayer? = null + private var request: MiruIjkPlaybackRequest? = null + private var androidIoAdapter: IAndroidIO? = null + private var surfaceReady = false + + init { + holder.addCallback(this) + isFocusable = false + isFocusableInTouchMode = false + } + + fun load(request: MiruIjkPlaybackRequest) { + releasePlayer() + this.request = request + if (surfaceReady) prepare(request) + } + + fun pausePlayback() { + player?.takeIf(IjkMediaPlayer::isPlaying)?.pause() + } + + fun resumePlayback() { + player?.start() + } + + fun seekTo(positionMs: Long) { + player?.seekTo(positionMs.coerceAtLeast(0L)) + } + + fun setPlaybackSpeed(speed: Float) { + player?.setSpeed(speed.coerceIn(0.25f, 3.0f)) + } + + fun currentPositionMs(): Long = player?.currentPosition?.coerceAtLeast(0L) ?: 0L + + fun durationMs(): Long = player?.duration?.coerceAtLeast(0L) ?: 0L + + fun isPlaybackActive(): Boolean = player?.isPlaying == true + + fun selectedAudioRawStreamIndex(): Int? = + player?.getSelectedTrack(ITrackInfo.MEDIA_TRACK_TYPE_AUDIO)?.takeIf { it >= 0 } + + fun audioTracks(): List = + player?.trackInfo.orEmpty().mapIndexedNotNull { rawIndex, track -> + if (track.trackType != ITrackInfo.MEDIA_TRACK_TYPE_AUDIO) return@mapIndexedNotNull null + MiruIjkAudioTrack( + rawStreamIndex = rawIndex, + language = track.language ?: "und", + details = track.infoInline.orEmpty(), + ) + } + + fun selectAudioRawStream(rawStreamIndex: Int) { + val mediaPlayer = player ?: return + val previous = selectedAudioRawStreamIndex() + if (previous != null && previous != rawStreamIndex) mediaPlayer.deselectTrack(previous) + mediaPlayer.selectTrack(rawStreamIndex) + publishAudioTracks() + } + + fun releasePlayer() { + request = null + androidIoAdapter = null + player?.runCatching { + setDisplay(null) + release() + } + player = null + } + + override fun surfaceCreated(holder: SurfaceHolder) { + surfaceReady = true + val activePlayer = player + if (activePlayer != null) { + activePlayer.setDisplay(holder) + } else { + request?.let(::prepare) + } + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit + + override fun surfaceDestroyed(holder: SurfaceHolder) { + surfaceReady = false + player?.setDisplay(null) + } + + private fun prepare(request: MiruIjkPlaybackRequest) { + val mediaPlayer = IjkMediaPlayer().also { player = it } + mediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", if (request.hardwareDecode) 1L else 0L) + mediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1L) + mediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1L) + mediaPlayer.setScreenOnWhilePlaying(true) + mediaPlayer.setDisplay(holder) + mediaPlayer.setOnPreparedListener { prepared -> + if (request.startPositionMs > 0L) prepared.seekTo(request.startPositionMs) + prepared.start() + listener?.onPrepared(prepared.duration, prepared.videoWidth, prepared.videoHeight) + publishAudioTracks() + } + mediaPlayer.setOnCompletionListener { listener?.onCompletion() } + mediaPlayer.setOnInfoListener { _, what, _ -> + when (what) { + IMediaPlayer.MEDIA_INFO_BUFFERING_START -> listener?.onBufferingChanged(true) + IMediaPlayer.MEDIA_INFO_BUFFERING_END -> listener?.onBufferingChanged(false) + } + false + } + mediaPlayer.setOnErrorListener { _, what, extra -> + listener?.onError(what, extra) + true + } + request.androidIo?.let { bridge -> + androidIoAdapter = object : IAndroidIO { + override fun open(url: String): Int = bridge.open(url) + override fun read(buffer: ByteArray, size: Int): Int = bridge.read(buffer, size) + override fun seek(offset: Long, whence: Int): Long = bridge.seek(offset, whence) + override fun close(): Int = bridge.close() + } + mediaPlayer.setAndroidIOCallback(androidIoAdapter) + mediaPlayer.setDataSource("ijkio:androidio:${request.uri}") + } ?: run { + val parsed = Uri.parse(request.uri) + if (parsed.scheme.equals("content", ignoreCase = true) || + parsed.scheme.equals("file", ignoreCase = true) + ) { + mediaPlayer.setDataSource(context, parsed, request.headers) + } else if (parsed.scheme.isNullOrBlank()) { + mediaPlayer.setDataSource(request.uri) + } else { + mediaPlayer.setDataSource(request.uri, request.headers) + } + } + mediaPlayer.prepareAsync() + } + + private fun publishAudioTracks() { + listener?.onAudioTracksChanged(audioTracks(), selectedAudioRawStreamIndex()) + } +} diff --git a/repository-api/src/main/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolver.kt b/repository-api/src/main/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolver.kt index 2003ecdf..38f4dfd3 100644 --- a/repository-api/src/main/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolver.kt +++ b/repository-api/src/main/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolver.kt @@ -31,13 +31,22 @@ class NextPlaybackSourceResolver( LibraryAnimeResolver(mediaSources, metadata, it, mergeSameAnimeEnabled) } - suspend fun build(currentSource: PlaybackSource): PlaybackSource? { + suspend fun build(currentSource: PlaybackSource): PlaybackSource? = + buildAdjacent(currentSource, nextEpisode(currentSource)) + + suspend fun buildPrevious(currentSource: PlaybackSource): PlaybackSource? = + buildAdjacent(currentSource, previousEpisode(currentSource)) + + private suspend fun buildAdjacent( + currentSource: PlaybackSource, + episode: Episode?, + ): PlaybackSource? { val currentPath = currentSource.episodeId ?.let { loadEpisode(it)?.filePath } ?: currentSource.uri - val nextEpisode = nextEpisode(currentSource) ?: return null - val version = nextEpisode.availableVersions().nearestTo(currentPath) ?: return null - return build(nextEpisode, version) + val adjacentEpisode = episode ?: return null + val version = adjacentEpisode.availableVersions().nearestTo(currentPath) ?: return null + return build(adjacentEpisode, version) } suspend fun build(currentEpisodeId: String?): PlaybackSource? { @@ -54,10 +63,21 @@ class NextPlaybackSourceResolver( } suspend fun nextEpisode(currentSource: PlaybackSource): Episode? = - findNextLogicalEpisode( + findAdjacentLogicalEpisode( currentEpisodeId = currentSource.episodeId, currentProgressId = currentSource.progressId, currentAnimeId = currentSource.mediaSourceId, + offset = 1, + loadCurrentEpisode = ::loadEpisode, + loadEpisodes = ::loadEpisodes, + ) + + suspend fun previousEpisode(currentSource: PlaybackSource): Episode? = + findAdjacentLogicalEpisode( + currentEpisodeId = currentSource.episodeId, + currentProgressId = currentSource.progressId, + currentAnimeId = currentSource.mediaSourceId, + offset = -1, loadCurrentEpisode = ::loadEpisode, loadEpisodes = ::loadEpisodes, ) @@ -132,6 +152,23 @@ private suspend fun findNextLogicalEpisode( currentAnimeId: String? = null, loadCurrentEpisode: suspend (String) -> Episode?, loadEpisodes: suspend (String) -> List, +): Episode? = + findAdjacentLogicalEpisode( + currentEpisodeId = currentEpisodeId, + currentProgressId = currentProgressId, + currentAnimeId = currentAnimeId, + offset = 1, + loadCurrentEpisode = loadCurrentEpisode, + loadEpisodes = loadEpisodes, + ) + +private suspend fun findAdjacentLogicalEpisode( + currentEpisodeId: String?, + currentProgressId: String?, + currentAnimeId: String? = null, + offset: Int, + loadCurrentEpisode: suspend (String) -> Episode?, + loadEpisodes: suspend (String) -> List, ): Episode? { val episodeId = currentEpisodeId ?: return null val currentEpisode = loadCurrentEpisode(episodeId) ?: return null @@ -141,6 +178,7 @@ private suspend fun findNextLogicalEpisode( episode.progressId == currentProgressId || episode.availableVersions().any { it.episodeId == episodeId } } - if (currentIndex < 0 || currentIndex >= episodes.lastIndex) return null - return episodes[currentIndex + 1] + val adjacentIndex = currentIndex + offset + if (currentIndex < 0 || adjacentIndex !in episodes.indices) return null + return episodes[adjacentIndex] } diff --git a/repository-api/src/test/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolverTest.kt b/repository-api/src/test/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolverTest.kt index f67c5bb1..852ec332 100644 --- a/repository-api/src/test/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolverTest.kt +++ b/repository-api/src/test/kotlin/com/miruplay/tv/repository/NextPlaybackSourceResolverTest.kt @@ -306,6 +306,62 @@ class NextPlaybackSourceResolverTest { assertEquals(nextWeb.id, source?.episodeId) } + @Test + fun `resolver builds previous logical episode and keeps nearest version`() = runBlocking { + val previousWeb = episode( + id = "41:/Show/WEB/Episode 01.mkv", + number = 1, + filePath = "/Show/WEB/Episode 01.mkv", + ) + val previousBd = episode( + id = "41:/Show/BD/Episode 01.mkv", + number = 1, + filePath = "/Show/BD/Episode 01.mkv", + ) + val currentWeb = episode( + id = "41:/Show/WEB/Episode 02.mkv", + number = 2, + filePath = "/Show/WEB/Episode 02.mkv", + ) + val resolver = NextPlaybackSourceResolver( + metadata = FakeMetadataRepository( + mapOf("anime-1" to listOf(currentWeb, previousBd, previousWeb)), + ), + progress = FakeProgressRepository(null), + mediaSources = FakeMediaSourceRepository(emptyList()), + playbackUriForEpisode = { it.filePath }, + ) + val currentSource = PlaybackSource( + uri = currentWeb.filePath, + mediaSourceId = currentWeb.animeId, + episodeId = currentWeb.id, + progressId = "anime-1#S1E2", + ) + + assertEquals("anime-1#S1E1", resolver.previousEpisode(currentSource)?.progressId) + assertEquals(previousWeb.id, resolver.buildPrevious(currentSource)?.episodeId) + } + + @Test + fun `resolver has no previous episode at the start of the logical queue`() = runBlocking { + val first = episode(id = "ep1", number = 1) + val second = episode(id = "ep2", number = 2) + val resolver = NextPlaybackSourceResolver( + metadata = FakeMetadataRepository(mapOf("anime-1" to listOf(second, first))), + progress = FakeProgressRepository(null), + mediaSources = FakeMediaSourceRepository(emptyList()), + ) + val source = PlaybackSource( + uri = first.filePath, + mediaSourceId = first.animeId, + episodeId = first.id, + progressId = first.progressId, + ) + + assertNull(resolver.previousEpisode(source)) + assertNull(resolver.buildPrevious(source)) + } + @Test fun `buildNextPlaybackSource returns null without episode id`() = runBlocking { val source = buildNextPlaybackSource( diff --git a/settings.gradle.kts b/settings.gradle.kts index bcf8aae2..c7bca9ac 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -29,6 +29,7 @@ include(":cloud-drive-core") include(":cloud-drive") include(":player-core") include(":player-mpv-android") +include(":player-ijkplayer-android") include(":scanner") include(":metadata-core") include(":metadata") diff --git a/third_party/ijkplayer/COPYING.LGPLv2.1 b/third_party/ijkplayer/COPYING.LGPLv2.1 new file mode 100644 index 00000000..58af0d37 --- /dev/null +++ b/third_party/ijkplayer/COPYING.LGPLv2.1 @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/third_party/ijkplayer/LICENSE.OpenSSL-1.1.1w b/third_party/ijkplayer/LICENSE.OpenSSL-1.1.1w new file mode 100644 index 00000000..5b5ccdc9 --- /dev/null +++ b/third_party/ijkplayer/LICENSE.OpenSSL-1.1.1w @@ -0,0 +1,124 @@ + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a double license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2019 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ diff --git a/third_party/ijkplayer/LICENSE.libyuv b/third_party/ijkplayer/LICENSE.libyuv new file mode 100644 index 00000000..c911747a --- /dev/null +++ b/third_party/ijkplayer/LICENSE.libyuv @@ -0,0 +1,29 @@ +Copyright 2011 The LibYuv Project Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/ijkplayer/NOTICE b/third_party/ijkplayer/NOTICE new file mode 100644 index 00000000..f7bd78d2 --- /dev/null +++ b/third_party/ijkplayer/NOTICE @@ -0,0 +1,189 @@ + + Copyright (c) 2005-2008, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/third_party/ijkplayer/README.md b/third_party/ijkplayer/README.md new file mode 100644 index 00000000..5bb6d9b2 --- /dev/null +++ b/third_party/ijkplayer/README.md @@ -0,0 +1,71 @@ +# debugly/ijkplayer Android artifact + +MiruPlay pins the upstream Android release artifact for its experimental ijkplayer backend. + +## Pinned artifact + +- Upstream: https://github.com/debugly/ijkplayer +- Source commit: `2a5114f6b276744159769f17b38bfab1e74ed5ad` +- FFToolChain commit: `b7847f3b362f605085e38a0169f870bf98d0845f` +- Release tag: `k0.8.9-beta-260526101841` +- Artifact URL: https://github.com/debugly/ijkplayer/releases/download/k0.8.9-beta-260526101841/ijkplayer-cmake-release.aar +- Artifact SHA-256: `5e6c3287a361ee0be54df0eb8db0af7d6488f92f5711776ac1fc09027b997e60` +- Upstream Android POM license: LGPL-2.1 +- Core source headers: LGPL-2.1-or-later + +The AAR is not nested into another Android library. MiruPlay extracts and pins only the Java classes plus its two shipped ABI payloads: + +- `player-ijkplayer-android/libs/ijkplayer-classes.jar`: `a441dd1f60251dc4f2c6dc5d885d7a446964412be68dd2fb068b7a23d4a90f7a` +- `arm64-v8a/libijkplayer.so`: `d9f16bbcb68c5fd8ba0f56a8b6f788962631a6749e82511f0f18305527e2d10b` +- `armeabi-v7a/libijkplayer.so`: `6070c560264097dfb44e289c61f6b22dd2dacf154ad770358599210430d2318a` + +## Corresponding source and build + +The pinned source and build inputs are available at: + +- https://github.com/debugly/ijkplayer/tree/2a5114f6b276744159769f17b38bfab1e74ed5ad +- https://github.com/debugly/FFToolChain/tree/b7847f3b362f605085e38a0169f870bf98d0845f + +The published AAR is a pinned distribution artifact. Verify it independently before extraction: + +```bash +curl -L \ + https://github.com/debugly/ijkplayer/releases/download/k0.8.9-beta-260526101841/ijkplayer-cmake-release.aar \ + -o ijkplayer-cmake-release.aar +printf '%s %s\n' \ + 5e6c3287a361ee0be54df0eb8db0af7d6488f92f5711776ac1fc09027b997e60 \ + ijkplayer-cmake-release.aar | sha256sum --check +``` + +The upstream artifact workflow runs on the mutable `macos-15` GitHub image and does not pin a JDK or NDK revision. The published native bytes are therefore verified by the recorded SHA-256, not claimed to be bit-reproducible from an incompletely pinned upstream runner. + +The independent corresponding-source audit used Temurin `21.0.11+10`, Android SDK/build-tools `35/35.0.0`, Android NDK `27.0.12077973`, CMake `3.22.1`, Gradle `8.10.2`, Android Gradle Plugin `8.8.0`, and Clang `18.0.1` (`r522817`). With those tools and Git LFS/submodule support: + +```bash +git clone https://github.com/debugly/ijkplayer.git +git -C ijkplayer checkout 2a5114f6b276744159769f17b38bfab1e74ed5ad +git -C ijkplayer submodule update --init --recursive +cd ijkplayer/android +./install-ffmpeg.sh +cd ijkplayer +./gradlew :ijkplayer-cmake:assembleRelease --no-daemon +``` + +The output is `ijkplayer-cmake/build/outputs/aar/ijkplayer-cmake-release.aar`. The source tree uses symbolic links; Windows checkouts must preserve or materialize `ijkmedia` and `third-libs` before configuring CMake. + +That independent build compiled 94 ijkplayer C/C++ translation units for both shipped ABIs. Its `classes.jar` was byte-identical to the pinned artifact. Both native outputs had identical defined-global-symbol sets, ELF section sets, and dynamic dependencies. Their bytes differ because the upstream macOS NDK compiler carries PGO/LTO metadata and the independent Windows compiler does not; the independent copy also used the release version string where the upstream binary embeds source short hash `2a5114f`. + +## Static dependency audit + +`libijkplayer.so` statically incorporates these pinned FFToolChain products: + +| Component | Source revision | License | Configuration | +| --- | --- | --- | --- | +| FFmpeg fork | `ff4.0--ijk0.8.8--20210426--001` | LGPL-2.1-or-later | `--disable-gpl --disable-nonfree`; selected decoders/demuxers/protocols only | +| OpenSSL | `OpenSSL_1_1_1w` | OpenSSL/SSLeay | Static TLS/crypto dependency of libavformat | +| SoundTouch | `2.4.0` | LGPL-2.1-or-later | Static playback-rate processing | +| libyuv | `f94b8cf7` | BSD-3-Clause | Static pixel conversion | + +The final ARM ELF files dynamically depend only on Android platform libraries: `liblog`, `libandroid`, `libEGL`, `libGLESv2`, `libjnigraphics`, `libOpenSLES`, `libm`, `libz`, `libdl`, and `libc`. + +`COPYING.LGPLv2.1`, `LICENSE.OpenSSL-1.1.1w`, `LICENSE.libyuv`, and `NOTICE` accompany the binary in both this directory and the APK assets. MiruPlay remains GPLv3. diff --git a/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfile.kt b/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfile.kt index b9952073..5c40cdcc 100644 --- a/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfile.kt +++ b/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfile.kt @@ -18,6 +18,13 @@ fun miruPlayKeyInputFromComposeKeyCode(keyCode: Long): MiruPlayKeyInput? = 126L -> MiruPlayKeyInput.MediaPlay 127L -> MiruPlayKeyInput.MediaPause 86L -> MiruPlayKeyInput.MediaStop + 89L -> MiruPlayKeyInput.MediaRewind + 90L -> MiruPlayKeyInput.MediaFastForward + 88L -> MiruPlayKeyInput.MediaPrevious + 87L -> MiruPlayKeyInput.MediaNext + 175L -> MiruPlayKeyInput.Captions + 82L -> MiruPlayKeyInput.Menu + 165L -> MiruPlayKeyInput.Info else -> null } diff --git a/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayInputIntent.kt b/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayInputIntent.kt index 3aed62b3..116be60d 100644 --- a/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayInputIntent.kt +++ b/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayInputIntent.kt @@ -13,6 +13,13 @@ enum class MiruPlayInputIntent { MediaPlay, MediaPause, MediaStop, + MediaRewind, + MediaFastForward, + MediaPrevious, + MediaNext, + Captions, + Menu, + Info, } enum class MiruPlayPlaybackInputAction { @@ -23,6 +30,11 @@ enum class MiruPlayPlaybackInputAction { SeekBack, SeekForward, Stop, + PreviousEpisode, + NextEpisode, + OpenCaptions, + FocusOptions, + ToggleInfo, ShowControls, HideControls, CloseMenu, @@ -58,14 +70,58 @@ fun MiruPlayInputIntent.verticalNavigationDelta(): Int? = fun MiruPlayInputIntent.linearNavigationDelta(): Int? = horizontalNavigationDelta() ?: verticalNavigationDelta() +fun MiruPlayInputIntent.isDedicatedPlayerRemoteIntent(): Boolean = + when (this) { + MiruPlayInputIntent.MediaRewind, + MiruPlayInputIntent.MediaFastForward, + MiruPlayInputIntent.MediaPrevious, + MiruPlayInputIntent.MediaNext, + MiruPlayInputIntent.MediaStop, + MiruPlayInputIntent.Captions, + MiruPlayInputIntent.Menu, + MiruPlayInputIntent.Info, + -> true + else -> false + } + +fun MiruPlayInputIntent.allowsPlayerRemoteRepeat(): Boolean = + this == MiruPlayInputIntent.MediaRewind || + this == MiruPlayInputIntent.MediaFastForward + fun MiruPlayInputIntent.tvPlaybackOverlayAction( controlsVisible: Boolean, hasOpenMenu: Boolean, +): MiruPlayPlaybackInputAction? = + when { + this == MiruPlayInputIntent.Back && hasOpenMenu -> MiruPlayPlaybackInputAction.CloseMenu + hasOpenMenu && ( + this == MiruPlayInputIntent.DirectionLeft || + this == MiruPlayInputIntent.DirectionRight || + this == MiruPlayInputIntent.DirectionUp || + this == MiruPlayInputIntent.DirectionDown + ) -> null + this == MiruPlayInputIntent.MediaRewind -> MiruPlayPlaybackInputAction.SeekBack + this == MiruPlayInputIntent.MediaFastForward -> MiruPlayPlaybackInputAction.SeekForward + this == MiruPlayInputIntent.MediaPrevious -> MiruPlayPlaybackInputAction.PreviousEpisode + this == MiruPlayInputIntent.MediaNext -> MiruPlayPlaybackInputAction.NextEpisode + this == MiruPlayInputIntent.MediaStop -> MiruPlayPlaybackInputAction.Stop + this == MiruPlayInputIntent.Captions -> MiruPlayPlaybackInputAction.OpenCaptions + this == MiruPlayInputIntent.Menu -> MiruPlayPlaybackInputAction.FocusOptions + this == MiruPlayInputIntent.Info -> MiruPlayPlaybackInputAction.ToggleInfo + else -> tvPlaybackOverlayActionForDpadAndTransport( + controlsVisible = controlsVisible, + hasOpenMenu = hasOpenMenu, + ) + } + +private fun MiruPlayInputIntent.tvPlaybackOverlayActionForDpadAndTransport( + controlsVisible: Boolean, + hasOpenMenu: Boolean, ): MiruPlayPlaybackInputAction? = if (controlsVisible) { when (this) { - MiruPlayInputIntent.DirectionLeft -> MiruPlayPlaybackInputAction.SeekBack.takeUnless { hasOpenMenu } - MiruPlayInputIntent.DirectionRight -> MiruPlayPlaybackInputAction.SeekForward.takeUnless { hasOpenMenu } + MiruPlayInputIntent.DirectionLeft, + MiruPlayInputIntent.DirectionRight, MiruPlayInputIntent.DirectionUp, MiruPlayInputIntent.DirectionDown, -> null @@ -102,6 +158,10 @@ fun MiruPlayPlaybackInputAction.shouldRefreshTvPlaybackControls(controlsVisible: MiruPlayPlaybackInputAction.SeekBack, MiruPlayPlaybackInputAction.SeekForward, MiruPlayPlaybackInputAction.ShowControls, + MiruPlayPlaybackInputAction.PreviousEpisode, + MiruPlayPlaybackInputAction.NextEpisode, + MiruPlayPlaybackInputAction.OpenCaptions, + MiruPlayPlaybackInputAction.FocusOptions, -> true MiruPlayPlaybackInputAction.TogglePause, MiruPlayPlaybackInputAction.Resume, diff --git a/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayKeyInput.kt b/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayKeyInput.kt index 7df27b2c..e4e46bda 100644 --- a/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayKeyInput.kt +++ b/ui-design/src/main/kotlin/com/miruplay/tv/design/MiruPlayKeyInput.kt @@ -17,6 +17,13 @@ enum class MiruPlayKeyInput { MediaPlay, MediaPause, MediaStop, + MediaRewind, + MediaFastForward, + MediaPrevious, + MediaNext, + Captions, + Menu, + Info, } fun MiruPlayKeyInput.toMiruPlayInputIntent(): MiruPlayInputIntent? = @@ -39,6 +46,13 @@ fun MiruPlayKeyInput.toMiruPlayInputIntent(): MiruPlayInputIntent? = MiruPlayKeyInput.MediaPlay -> MiruPlayInputIntent.MediaPlay MiruPlayKeyInput.MediaPause -> MiruPlayInputIntent.MediaPause MiruPlayKeyInput.MediaStop -> MiruPlayInputIntent.MediaStop + MiruPlayKeyInput.MediaRewind -> MiruPlayInputIntent.MediaRewind + MiruPlayKeyInput.MediaFastForward -> MiruPlayInputIntent.MediaFastForward + MiruPlayKeyInput.MediaPrevious -> MiruPlayInputIntent.MediaPrevious + MiruPlayKeyInput.MediaNext -> MiruPlayInputIntent.MediaNext + MiruPlayKeyInput.Captions -> MiruPlayInputIntent.Captions + MiruPlayKeyInput.Menu -> MiruPlayInputIntent.Menu + MiruPlayKeyInput.Info -> MiruPlayInputIntent.Info } fun MiruPlayKeyInput.isMiruPlayActivationKey(): Boolean = diff --git a/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfileTest.kt b/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfileTest.kt index 693c7923..1b46fec2 100644 --- a/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfileTest.kt +++ b/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayComposeKeyProfileTest.kt @@ -19,6 +19,14 @@ class MiruPlayComposeKeyProfileTest { assertEquals(MiruPlayKeyInput.MediaPlay, miruPlayKeyInputFromComposeKeyCode(126L)) assertEquals(MiruPlayKeyInput.MediaPause, miruPlayKeyInputFromComposeKeyCode(127L)) assertEquals(MiruPlayKeyInput.MediaStop, miruPlayKeyInputFromComposeKeyCode(86L)) + assertEquals(MiruPlayKeyInput.MediaNext, miruPlayKeyInputFromComposeKeyCode(87L)) + assertEquals(MiruPlayKeyInput.MediaPrevious, miruPlayKeyInputFromComposeKeyCode(88L)) + assertEquals(MiruPlayKeyInput.MediaRewind, miruPlayKeyInputFromComposeKeyCode(89L)) + assertEquals(MiruPlayKeyInput.MediaFastForward, miruPlayKeyInputFromComposeKeyCode(90L)) + assertEquals(MiruPlayKeyInput.Info, miruPlayKeyInputFromComposeKeyCode(165L)) + assertEquals(MiruPlayKeyInput.Captions, miruPlayKeyInputFromComposeKeyCode(175L)) + assertEquals(MiruPlayKeyInput.Menu, miruPlayKeyInputFromComposeKeyCode(82L)) + assertNull(miruPlayKeyInputFromComposeKeyCode(176L)) assertNull(miruPlayKeyInputFromComposeKeyCode(67L)) } @@ -26,6 +34,9 @@ class MiruPlayComposeKeyProfileTest { fun `compose key codes map to shared intents`() { assertEquals(MiruPlayInputIntent.Activate, miruPlayInputIntentFromComposeKeyCode(23L)) assertEquals(MiruPlayInputIntent.Back, miruPlayInputIntentFromComposeKeyCode(4L)) + assertEquals(MiruPlayInputIntent.MediaFastForward, miruPlayInputIntentFromComposeKeyCode(90L)) + assertEquals(MiruPlayInputIntent.Captions, miruPlayInputIntentFromComposeKeyCode(175L)) + assertEquals(MiruPlayInputIntent.Info, miruPlayInputIntentFromComposeKeyCode(165L)) assertNull(miruPlayInputIntentFromComposeKeyCode(111L)) } } diff --git a/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayInputIntentTest.kt b/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayInputIntentTest.kt index bec53eeb..bc72d99e 100644 --- a/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayInputIntentTest.kt +++ b/ui-design/src/test/kotlin/com/miruplay/tv/design/MiruPlayInputIntentTest.kt @@ -74,15 +74,9 @@ class MiruPlayInputIntentTest { } @Test - fun `TV playback overlay action keeps left and right seeking while controls are visible`() { - assertEquals( - MiruPlayPlaybackInputAction.SeekBack, - MiruPlayInputIntent.DirectionLeft.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = false), - ) - assertEquals( - MiruPlayPlaybackInputAction.SeekForward, - MiruPlayInputIntent.DirectionRight.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = false), - ) + fun `TV playback overlay action leaves direction keys to visible focused controls`() { + assertNull(MiruPlayInputIntent.DirectionLeft.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = false)) + assertNull(MiruPlayInputIntent.DirectionRight.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = false)) assertNull(MiruPlayInputIntent.DirectionUp.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = false)) assertNull(MiruPlayInputIntent.DirectionDown.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = false)) } @@ -95,13 +89,51 @@ class MiruPlayInputIntentTest { MiruPlayInputIntent.DirectionUp, MiruPlayInputIntent.DirectionDown, ).forEach { intent -> - assertNull( - intent.tvPlaybackOverlayAction( - controlsVisible = true, - hasOpenMenu = true, + listOf(false, true).forEach { controlsVisible -> + assertNull( + intent.tvPlaybackOverlayAction( + controlsVisible = controlsVisible, + hasOpenMenu = true, + ) ) + } + } + } + + @Test + fun `dedicated player keys resolve independently of chrome focus`() { + val cases = mapOf( + MiruPlayInputIntent.MediaRewind to MiruPlayPlaybackInputAction.SeekBack, + MiruPlayInputIntent.MediaFastForward to MiruPlayPlaybackInputAction.SeekForward, + MiruPlayInputIntent.MediaPrevious to MiruPlayPlaybackInputAction.PreviousEpisode, + MiruPlayInputIntent.MediaNext to MiruPlayPlaybackInputAction.NextEpisode, + MiruPlayInputIntent.MediaStop to MiruPlayPlaybackInputAction.Stop, + MiruPlayInputIntent.Captions to MiruPlayPlaybackInputAction.OpenCaptions, + MiruPlayInputIntent.Menu to MiruPlayPlaybackInputAction.FocusOptions, + MiruPlayInputIntent.Info to MiruPlayPlaybackInputAction.ToggleInfo, + ) + + cases.forEach { (intent, expected) -> + assertTrue(intent.isDedicatedPlayerRemoteIntent()) + assertEquals( + expected, + intent.tvPlaybackOverlayAction(controlsVisible = false, hasOpenMenu = false), + ) + assertEquals( + expected, + intent.tvPlaybackOverlayAction(controlsVisible = true, hasOpenMenu = true), ) } + assertFalse(MiruPlayInputIntent.DirectionLeft.isDedicatedPlayerRemoteIntent()) + } + + @Test + fun `only dedicated seek keys execute on repeat`() { + assertTrue(MiruPlayInputIntent.MediaRewind.allowsPlayerRemoteRepeat()) + assertTrue(MiruPlayInputIntent.MediaFastForward.allowsPlayerRemoteRepeat()) + assertFalse(MiruPlayInputIntent.MediaNext.allowsPlayerRemoteRepeat()) + assertFalse(MiruPlayInputIntent.Captions.allowsPlayerRemoteRepeat()) + assertFalse(MiruPlayInputIntent.Info.allowsPlayerRemoteRepeat()) } @Test diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandling.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandling.kt index daf8bf9f..860f4f40 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandling.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandling.kt @@ -3,104 +3,21 @@ package com.miruplay.tv.ui.player import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType -internal data class PlayerKeyActions( - val skipBackward: () -> Unit, - val skipForward: () -> Unit, - val togglePlayback: () -> Unit, - val resume: () -> Unit, - val pause: () -> Unit, - val showControls: () -> Unit, - val hideControls: () -> Unit, - val closeMenu: () -> Unit, - val navigateBack: () -> Unit -) - -internal fun handlePlayerKey( +internal fun handlePlaybackTimelineKey( key: Key, type: KeyEventType, - controlsVisible: Boolean, - hasOpenMenu: Boolean, - actions: PlayerKeyActions + onSkipBackward: () -> Unit, + onSkipForward: () -> Unit, ): Boolean { if (type != KeyEventType.KeyDown) return false - if (controlsVisible) { - return when (key) { - Key.DirectionLeft -> if (hasOpenMenu) { - false - } else { - actions.showControls() - actions.skipBackward() - true - } - Key.DirectionRight -> if (hasOpenMenu) { - false - } else { - actions.showControls() - actions.skipForward() - true - } - Key.MediaPlayPause -> { - actions.togglePlayback() - true - } - Key.MediaPlay -> { - actions.resume() - true - } - Key.MediaPause -> { - actions.pause() - true - } - Key.Back -> { - if (hasOpenMenu) { - actions.closeMenu() - } else { - actions.hideControls() - } - true - } - else -> false - } - } - return when (key) { Key.DirectionLeft -> { - actions.showControls() - actions.skipBackward() + onSkipBackward() true } Key.DirectionRight -> { - actions.showControls() - actions.skipForward() - true - } - Key.DirectionUp, - Key.DirectionDown -> { - actions.showControls() - true - } - Key.DirectionCenter, - Key.Enter, - Key.NumPadEnter, - Key.Spacebar, - Key.MediaPlayPause -> { - actions.showControls() - actions.togglePlayback() - true - } - Key.MediaPlay -> { - actions.showControls() - actions.resume() - true - } - Key.MediaPause -> { - actions.showControls() - actions.pause() - true - } - Key.Back -> { - actions.navigateBack() + onSkipForward() true } else -> false diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerScreen.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerScreen.kt index 0e2743e1..4ca5a554 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerScreen.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerScreen.kt @@ -5,6 +5,7 @@ package com.miruplay.tv.ui.player import android.app.Activity import android.content.Context import android.content.ContextWrapper +import android.net.Uri import android.os.SystemClock import android.util.Log import android.view.LayoutInflater @@ -37,6 +38,9 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.CircleShape @@ -47,9 +51,12 @@ import androidx.compose.material.icons.filled.Audiotrack import androidx.compose.material.icons.filled.FastForward import androidx.compose.material.icons.filled.FastRewind import androidx.compose.material.icons.filled.GraphicEq +import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Pause import androidx.compose.material.icons.filled.PhotoFilter import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.SkipNext +import androidx.compose.material.icons.filled.SkipPrevious import androidx.compose.material.icons.filled.Speed import androidx.compose.material.icons.filled.Subtitles import androidx.compose.material3.Button @@ -66,12 +73,13 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.scale import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key @@ -81,6 +89,7 @@ import androidx.compose.ui.input.key.type import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp @@ -102,6 +111,7 @@ import com.miruplay.tv.model.PLAYBACK_SEEK_BACK_SECONDS import com.miruplay.tv.model.PLAYBACK_SEEK_FORWARD_SECONDS import com.miruplay.tv.model.PlaybackRenderBackend import com.miruplay.tv.model.SubtitleTrack +import com.miruplay.tv.model.VideoSignalDescriptor import com.miruplay.tv.model.ToneMappingProfilePreset import com.miruplay.tv.model.ToneMappingRuleSet import com.miruplay.tv.model.PlaybackTimingConventions @@ -109,6 +119,7 @@ import com.miruplay.tv.model.formatPlaybackPosition import com.miruplay.tv.model.pictureOsdMenuTitleLabel import com.miruplay.tv.model.pictureSaveDefaultForFormatLabel import com.miruplay.tv.model.pictureSessionOverrideLabel +import com.miruplay.tv.model.playbackBackendLabel import com.miruplay.tv.model.playbackAudioMenuTitle import com.miruplay.tv.model.playbackAudioOptionLabel import com.miruplay.tv.model.playbackAudioTrackCountLabel @@ -131,7 +142,10 @@ import com.miruplay.tv.model.playbackSubtitleOptionLabel import com.miruplay.tv.model.playbackSubtitlesMenuTitle import com.miruplay.tv.model.toneMappingPresetLabel import com.miruplay.tv.model.toneMappingPresetOptions +import com.miruplay.tv.design.MiruPlayInputIntent import com.miruplay.tv.design.MiruPlayPlaybackInputAction +import com.miruplay.tv.design.allowsPlayerRemoteRepeat +import com.miruplay.tv.design.isDedicatedPlayerRemoteIntent import com.miruplay.tv.design.shouldRefreshTvPlaybackControls import com.miruplay.tv.design.tvPlaybackOverlayAction import com.miruplay.tv.ui.components.EpisodeVersionDialog @@ -192,6 +206,8 @@ private fun PlayerScreenContent( val playbackState by viewModel.playbackState.collectAsStateWithLifecycle() val activePlaybackSource by viewModel.activePlaybackSource.collectAsStateWithLifecycle() val pendingNextEpisode by viewModel.pendingNextEpisode.collectAsStateWithLifecycle() + val canPlayPreviousEpisode by viewModel.canPlayPreviousEpisode.collectAsStateWithLifecycle() + val canPlayNextEpisode by viewModel.canPlayNextEpisode.collectAsStateWithLifecycle() val currentPosition by viewModel.currentPosition.collectAsStateWithLifecycle() val duration by viewModel.duration.collectAsStateWithLifecycle() val controlsVisible by viewModel.controlsVisible.collectAsStateWithLifecycle() @@ -217,6 +233,12 @@ private fun PlayerScreenContent( resolveDeviceGlEsMajorVersion(view.context) } val playerFocusRequester = remember { FocusRequester() } + val timelineFocusRequester = remember { FocusRequester() } + val transportFocusRequester = remember { FocusRequester() } + val pictureFocusRequester = remember { FocusRequester() } + val speedFocusRequester = remember { FocusRequester() } + val subtitlesFocusRequester = remember { FocusRequester() } + val audioFocusRequester = remember { FocusRequester() } val currentPlaybackSource = activePlaybackSource ?: playbackSource val pendingDebugCaptureLabel = viewModel.pendingGlFrameCaptureLabel() var preferCapturableTextureView by remember(playbackSource) { @@ -273,6 +295,10 @@ private fun PlayerScreenContent( } val context = LocalContext.current var openMenu by remember { mutableStateOf(null) } + var infoPanelVisible by remember { mutableStateOf(false) } + var infoTab by remember { mutableStateOf(PlayerInfoTab.Information) } + var pressedDedicatedIntent by remember { mutableStateOf(null) } + var pendingChromeFocus by remember { mutableStateOf(null) } var exitConfirmationStartedAt by remember(playbackSource) { mutableStateOf(0L) } var playerViewRef by remember { mutableStateOf(null) } var lastStandardDebugCaptureAttempt by remember(playbackSource) { @@ -300,6 +326,33 @@ private fun PlayerScreenContent( } } + val focusTargetForMenu: (PlayerMenu) -> PlayerChromeFocusTarget = { menu -> + when (menu) { + PlayerMenu.Picture -> PlayerChromeFocusTarget.Picture + PlayerMenu.Speed -> PlayerChromeFocusTarget.Speed + PlayerMenu.Subtitles -> PlayerChromeFocusTarget.Subtitles + PlayerMenu.Audio -> PlayerChromeFocusTarget.Audio + } + } + val closeOpenOverlay = { + if (infoPanelVisible) { + infoPanelVisible = false + } else { + openMenu?.let { pendingChromeFocus = focusTargetForMenu(it) } + openMenu = null + viewModel.showControls() + } + } + val toggleInfoPanel = { + if (infoPanelVisible) { + infoPanelVisible = false + } else { + openMenu = null + viewModel.hideControls() + infoPanelVisible = true + } + } + LaunchedEffect(playbackSource, hasStartedPlayback, screenOwnerToken) { if (!hasStartedPlayback) { hasStartedPlayback = true @@ -319,13 +372,28 @@ private fun PlayerScreenContent( } } - LaunchedEffect(controlsVisible) { - if (!controlsVisible) { + LaunchedEffect(controlsVisible, infoPanelVisible) { + if (!controlsVisible && !infoPanelVisible) { openMenu = null playerFocusRequester.requestFocus() } } + LaunchedEffect(controlsVisible, openMenu, pendingChromeFocus) { + if (controlsVisible && openMenu == null) { + when (pendingChromeFocus) { + PlayerChromeFocusTarget.Picture -> pictureFocusRequester.requestFocus() + PlayerChromeFocusTarget.Speed -> speedFocusRequester.requestFocus() + PlayerChromeFocusTarget.Subtitles -> subtitlesFocusRequester.requestFocus() + PlayerChromeFocusTarget.Audio -> audioFocusRequester.requestFocus() + null, + PlayerChromeFocusTarget.Timeline, + -> timelineFocusRequester.requestFocus() + } + pendingChromeFocus = null + } + } + LaunchedEffect(controlsVisible, controlsInteractionToken, playbackState, openMenu) { if (controlsVisible || openMenu != null) { exitConfirmationStartedAt = 0L @@ -417,21 +485,55 @@ private fun PlayerScreenContent( .focusRequester(playerFocusRequester) .focusable() .onPreviewKeyEvent { event -> - handlePlayerKey( + val intent = event.key.toMiruPlayInputIntent() + val repeatsDedicatedCommand = + event.type == KeyEventType.KeyDown && + intent?.isDedicatedPlayerRemoteIntent() == true && + pressedDedicatedIntent == intent + val consumed = handlePlayerKey( event = event, + repeatsDedicatedCommand = repeatsDedicatedCommand, controlsVisible = controlsVisible, - hasOpenMenu = openMenu != null, + hasOpenMenu = openMenu != null || infoPanelVisible, + hasSubtitles = availableSubtitles.isNotEmpty(), + canPlayPreviousEpisode = canPlayPreviousEpisode, + canPlayNextEpisode = canPlayNextEpisode, viewModel = viewModel, - onCloseMenu = { - openMenu = null - viewModel.showControls() - }, + onCloseMenu = closeOpenOverlay, onHideControls = { openMenu = null viewModel.hideControls() }, - onNavigateBack = requestExit + onOpenCaptions = { + infoPanelVisible = false + if (openMenu == PlayerMenu.Subtitles) { + pendingChromeFocus = PlayerChromeFocusTarget.Subtitles + openMenu = null + } else { + viewModel.showControls() + openMenu = PlayerMenu.Subtitles + } + }, + onFocusOptions = { + infoPanelVisible = false + openMenu = null + pendingChromeFocus = PlayerChromeFocusTarget.Picture + viewModel.showControls() + }, + onToggleInfo = toggleInfoPanel, + onStop = navigateBack, + onNavigateBack = requestExit, ) + if (intent?.isDedicatedPlayerRemoteIntent() == true) { + when (event.type) { + KeyEventType.KeyDown -> pressedDedicatedIntent = intent + KeyEventType.KeyUp -> if (pressedDedicatedIntent == intent) { + pressedDedicatedIntent = null + } + else -> Unit + } + } + consumed } .pointerInput(Unit) { detectTapGestures { @@ -574,11 +676,22 @@ private fun PlayerScreenContent( playbackSpeed = playbackSpeed, signalFormatLabel = currentVideoSignalDescriptor?.displayLabel().orEmpty(), currentPicturePreset = viewModel.currentToneMappingPreset(), + timelineFocusRequester = timelineFocusRequester, + transportFocusRequester = transportFocusRequester, + pictureFocusRequester = pictureFocusRequester, + speedFocusRequester = speedFocusRequester, + subtitlesFocusRequester = subtitlesFocusRequester, + audioFocusRequester = audioFocusRequester, + canPlayPreviousEpisode = canPlayPreviousEpisode, + canPlayNextEpisode = canPlayNextEpisode, onBack = navigateBack, + onInfo = toggleInfoPanel, onTogglePlayback = { viewModel.togglePlayback() viewModel.showControls() }, + onPreviousEpisode = viewModel::playPreviousEpisode, + onNextEpisode = viewModel::playNextEpisode, onSkipBackward = { viewModel.skipBackward() viewModel.showControls() @@ -612,7 +725,41 @@ private fun PlayerScreenContent( viewModel.showControls() }, openMenu = openMenu, - onOpenMenuChange = { openMenu = it } + onOpenMenuChange = { menu -> + if (openMenu == menu) { + pendingChromeFocus = focusTargetForMenu(menu) + openMenu = null + } else { + openMenu = menu + } + }, + ) + } + + AnimatedVisibility( + visible = infoPanelVisible, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier.align(Alignment.CenterEnd), + ) { + PlayerInfoPanel( + tab = infoTab, + onTabChange = { infoTab = it }, + title = displayTitle.ifBlank { currentPlaybackSource.mediaSourceId }, + sourceLabel = displaySubtitle.ifBlank { currentPlaybackSource.mediaSourceId }, + source = currentPlaybackSource, + playbackState = playbackState, + currentPosition = currentPosition, + duration = duration, + playbackSpeed = playbackSpeed, + signal = currentVideoSignalDescriptor, + requestedBackend = currentRequestedBackend, + activeBackend = currentActiveBackend, + fallbackReason = fallbackReason, + subtitles = availableSubtitles, + audioTracks = availableAudioTracks, + selectedSubtitleTrackIndex = selectedSubtitleTrackIndex, + selectedAudioTrackIndex = selectedAudioTrackIndex, ) } @@ -730,8 +877,19 @@ private fun PlayerChrome( playbackSpeed: Float, signalFormatLabel: String, currentPicturePreset: ToneMappingProfilePreset, + timelineFocusRequester: FocusRequester, + transportFocusRequester: FocusRequester, + pictureFocusRequester: FocusRequester, + speedFocusRequester: FocusRequester, + subtitlesFocusRequester: FocusRequester, + audioFocusRequester: FocusRequester, + canPlayPreviousEpisode: Boolean, + canPlayNextEpisode: Boolean, onBack: () -> Unit, + onInfo: () -> Unit, onTogglePlayback: () -> Unit, + onPreviousEpisode: () -> Unit, + onNextEpisode: () -> Unit, onSkipBackward: () -> Unit, onSkipForward: () -> Unit, onSelectSubtitle: (Int?) -> Unit, @@ -741,7 +899,7 @@ private fun PlayerChrome( onSavePictureDefault: () -> Unit, onResetPictureSession: () -> Unit, openMenu: PlayerMenu?, - onOpenMenuChange: (PlayerMenu?) -> Unit + onOpenMenuChange: (PlayerMenu) -> Unit ) { Box( modifier = Modifier @@ -749,9 +907,9 @@ private fun PlayerChrome( .background( Brush.verticalGradient( colors = listOf( - Color.Black.copy(alpha = 0.78f), - Color.Black.copy(alpha = 0.10f), - Color.Black.copy(alpha = 0.88f) + Color.Black.copy(alpha = 0.54f), + Color.Black.copy(alpha = 0.02f), + Color.Black.copy(alpha = 0.64f) ) ) ) @@ -760,12 +918,18 @@ private fun PlayerChrome( title = title, sourceLabel = sourceLabel, onBack = onBack, + onInfo = onInfo, modifier = Modifier.align(Alignment.TopCenter) ) TransportControls( isPlaying = playbackState is PlaybackState.Playing, isLoading = playbackState is PlaybackState.Loading || playbackState is PlaybackState.Buffering, + canPlayPreviousEpisode = canPlayPreviousEpisode, + canPlayNextEpisode = canPlayNextEpisode, + focusRequester = transportFocusRequester, + onPreviousEpisode = onPreviousEpisode, + onNextEpisode = onNextEpisode, onTogglePlayback = onTogglePlayback, onSkipBackward = onSkipBackward, onSkipForward = onSkipForward, @@ -803,8 +967,16 @@ private fun PlayerChrome( playbackSpeed = playbackSpeed, signalFormatLabel = signalFormatLabel, openMenu = openMenu, + timelineFocusRequester = timelineFocusRequester, + transportFocusRequester = transportFocusRequester, + pictureFocusRequester = pictureFocusRequester, + speedFocusRequester = speedFocusRequester, + subtitlesFocusRequester = subtitlesFocusRequester, + audioFocusRequester = audioFocusRequester, + onSkipBackward = onSkipBackward, + onSkipForward = onSkipForward, onOpenMenu = { menu -> - onOpenMenuChange(if (openMenu == menu) null else menu) + onOpenMenuChange(menu) }, modifier = Modifier.align(Alignment.BottomCenter) ) @@ -816,6 +988,7 @@ private fun PlayerTopBar( title: String, sourceLabel: String, onBack: () -> Unit, + onInfo: () -> Unit, modifier: Modifier = Modifier ) { Row( @@ -847,6 +1020,12 @@ private fun PlayerTopBar( overflow = TextOverflow.Ellipsis ) } + PlayerIconButton( + icon = Icons.Filled.Info, + label = "播放信息", + onClick = onInfo, + size = 54.dp, + ) } } @@ -854,26 +1033,32 @@ private fun PlayerTopBar( private fun TransportControls( isPlaying: Boolean, isLoading: Boolean, + canPlayPreviousEpisode: Boolean, + canPlayNextEpisode: Boolean, + focusRequester: FocusRequester, + onPreviousEpisode: () -> Unit, + onNextEpisode: () -> Unit, onTogglePlayback: () -> Unit, onSkipBackward: () -> Unit, onSkipForward: () -> Unit, modifier: Modifier = Modifier ) { - val playFocusRequester = remember { FocusRequester() } - - LaunchedEffect(Unit) { - playFocusRequester.requestFocus() - } - Row( modifier = modifier .clip(RoundedCornerShape(8.dp)) - .background(Color.Black.copy(alpha = 0.38f)) + .background(Color.Black.copy(alpha = 0.24f)) .border(1.dp, Color.White.copy(alpha = 0.12f), RoundedCornerShape(8.dp)) .padding(horizontal = 18.dp, vertical = 14.dp), horizontalArrangement = Arrangement.spacedBy(24.dp), verticalAlignment = Alignment.CenterVertically ) { + PlayerIconButton( + icon = Icons.Filled.SkipPrevious, + label = "上一集", + onClick = onPreviousEpisode, + size = 54.dp, + enabled = canPlayPreviousEpisode, + ) PlayerIconButton( icon = Icons.Filled.FastRewind, label = playbackSeekBackLabel(PLAYBACK_SEEK_BACK_SECONDS), @@ -885,7 +1070,7 @@ private fun TransportControls( label = if (isPlaying) playbackPauseLabel() else playbackPlayLabel(), onClick = onTogglePlayback, size = 82.dp, - modifier = Modifier.focusRequester(playFocusRequester), + modifier = Modifier.focusRequester(focusRequester), prominent = true, enabled = !isLoading ) @@ -895,12 +1080,19 @@ private fun TransportControls( onClick = onSkipForward, size = 62.dp ) + PlayerIconButton( + icon = Icons.Filled.SkipNext, + label = "下一集", + onClick = onNextEpisode, + size = 54.dp, + enabled = canPlayNextEpisode, + ) } } @OptIn(ExperimentalLayoutApi::class) @Composable -private fun PlayerBottomBar( +internal fun PlayerBottomBar( currentPosition: Long, duration: Long, subtitles: List, @@ -910,13 +1102,21 @@ private fun PlayerBottomBar( playbackSpeed: Float, signalFormatLabel: String, openMenu: PlayerMenu?, + timelineFocusRequester: FocusRequester, + transportFocusRequester: FocusRequester, + pictureFocusRequester: FocusRequester, + speedFocusRequester: FocusRequester, + subtitlesFocusRequester: FocusRequester, + audioFocusRequester: FocusRequester, + onSkipBackward: () -> Unit, + onSkipForward: () -> Unit, onOpenMenu: (PlayerMenu) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier .fillMaxWidth() - .background(Color.Black.copy(alpha = 0.62f)) + .background(Color.Black.copy(alpha = 0.44f)) .padding(start = 52.dp, end = 52.dp, top = 22.dp, bottom = 36.dp) ) { Row( @@ -926,6 +1126,15 @@ private fun PlayerBottomBar( TimeText(formatPlaybackPosition(currentPosition)) PlaybackTimeline( progress = PlaybackTimingConventions.playbackProgressFraction(currentPosition, duration), + focusRequester = timelineFocusRequester, + upFocusRequester = transportFocusRequester, + downFocusRequester = when { + audioTracks.isNotEmpty() -> audioFocusRequester + subtitles.isNotEmpty() -> subtitlesFocusRequester + else -> speedFocusRequester + }, + onSkipBackward = onSkipBackward, + onSkipForward = onSkipForward, modifier = Modifier .weight(1f) .padding(horizontal = 18.dp) @@ -949,13 +1158,23 @@ private fun PlayerBottomBar( icon = Icons.Filled.PhotoFilter, text = pictureOsdMenuTitleLabel(), selected = openMenu == PlayerMenu.Picture, - onClick = { onOpenMenu(PlayerMenu.Picture) } + onClick = { onOpenMenu(PlayerMenu.Picture) }, + modifier = Modifier + .focusRequester(pictureFocusRequester) + .focusProperties { + if (openMenu == null) up = timelineFocusRequester + }, ) PlayerActionChip( icon = Icons.Filled.Speed, text = playbackSpeedChipLabel(playbackSpeed), selected = openMenu == PlayerMenu.Speed, - onClick = { onOpenMenu(PlayerMenu.Speed) } + onClick = { onOpenMenu(PlayerMenu.Speed) }, + modifier = Modifier + .focusRequester(speedFocusRequester) + .focusProperties { + if (openMenu == null) up = timelineFocusRequester + }, ) PlayerActionChip( icon = Icons.Filled.Subtitles, @@ -964,7 +1183,12 @@ private fun PlayerBottomBar( ?: playbackSubtitleCountLabel(subtitles.size), selected = openMenu == PlayerMenu.Subtitles, enabled = subtitles.isNotEmpty(), - onClick = { onOpenMenu(PlayerMenu.Subtitles) } + onClick = { onOpenMenu(PlayerMenu.Subtitles) }, + modifier = Modifier + .focusRequester(subtitlesFocusRequester) + .focusProperties { + if (openMenu == null) up = timelineFocusRequester + }, ) PlayerActionChip( icon = Icons.Filled.Audiotrack, @@ -977,28 +1201,62 @@ private fun PlayerBottomBar( ?: playbackAudioTrackCountLabel(audioTracks.size), selected = openMenu == PlayerMenu.Audio, enabled = audioTracks.isNotEmpty(), - onClick = { onOpenMenu(PlayerMenu.Audio) } + onClick = { onOpenMenu(PlayerMenu.Audio) }, + modifier = Modifier + .focusRequester(audioFocusRequester) + .focusProperties { + if (openMenu == null) up = timelineFocusRequester + }, ) } } } @Composable -private fun PlaybackTimeline( +internal fun PlaybackTimeline( progress: Float, + focusRequester: FocusRequester, + upFocusRequester: FocusRequester, + downFocusRequester: FocusRequester, + onSkipBackward: () -> Unit, + onSkipForward: () -> Unit, modifier: Modifier = Modifier ) { + val interactionSource = remember { MutableInteractionSource() } + val isFocused by interactionSource.collectIsFocusedAsState() + val shape = RoundedCornerShape(8.dp) + Box( modifier = modifier - .height(8.dp) - .clip(RoundedCornerShape(8.dp)) - .background(Color.White.copy(alpha = 0.20f)) + .height(18.dp) + .focusRequester(focusRequester) + .focusProperties { + up = upFocusRequester + down = downFocusRequester + } + .testTag(PLAYER_TIMELINE_TEST_TAG) + .clip(shape) + .background(Color.White.copy(alpha = if (isFocused) 0.30f else 0.20f)) + .border( + width = if (isFocused) 3.dp else 1.dp, + color = if (isFocused) Color.White else Color.White.copy(alpha = 0.14f), + shape = shape, + ) + .onPreviewKeyEvent { event -> + handlePlaybackTimelineKey( + key = event.key, + type = event.type, + onSkipBackward = onSkipBackward, + onSkipForward = onSkipForward, + ) + } + .focusable(interactionSource = interactionSource) ) { Box( modifier = Modifier .fillMaxHeight() .fillMaxWidth(progress.coerceIn(0f, 1f)) - .clip(RoundedCornerShape(8.dp)) + .clip(shape) .background(AnimeRed) ) } @@ -1035,12 +1293,13 @@ private fun PlayerIconButton( Box( modifier = modifier + .scale(if (isFocused) 1.08f else 1f) .size(size) .clip(CircleShape) .background(background) .border( - width = if (isFocused) 2.dp else 1.dp, - color = if (isFocused) FocusBorder else Color.White.copy(alpha = 0.20f), + width = if (isFocused) 3.dp else 1.dp, + color = if (isFocused) Color.White else Color.White.copy(alpha = 0.20f), shape = CircleShape ) .clickable( @@ -1103,7 +1362,8 @@ private fun PlayerActionChip( text: String, selected: Boolean, onClick: () -> Unit, - enabled: Boolean = true + modifier: Modifier = Modifier, + enabled: Boolean = true, ) { val interactionSource = remember { MutableInteractionSource() } val isFocused by interactionSource.collectIsFocusedAsState() @@ -1119,7 +1379,8 @@ private fun PlayerActionChip( onClick = onClick, enabled = enabled, interactionSource = interactionSource, - modifier = Modifier + modifier = modifier + .scale(if (isFocused) 1.04f else 1f) .height(48.dp) .clip(RoundedCornerShape(8.dp)) .onPreviewKeyEvent { event -> @@ -1131,8 +1392,12 @@ private fun PlayerActionChip( ) } .border( - width = if (isFocused || selected) 2.dp else 1.dp, - color = if (isFocused) FocusBorder else Color.White.copy(alpha = 0.14f), + width = when { + isFocused -> 3.dp + selected -> 2.dp + else -> 1.dp + }, + color = if (isFocused) Color.White else Color.White.copy(alpha = 0.14f), shape = RoundedCornerShape(8.dp) ), shape = RoundedCornerShape(8.dp), @@ -1185,14 +1450,30 @@ internal fun PlayerOptionsPanel( val initialFocusHandle = rememberInitialFocusHandle(key = menu) val speeds = remember { playbackSpeedOptions() } val picturePresets = remember { toneMappingPresetOptions() } + val initialSpeedIndex = speeds.indexOf(playbackSpeed).takeIf { it >= 0 } ?: 0 + val initialPictureIndex = picturePresets.indexOf(currentPicturePreset).takeIf { it >= 0 } ?: 0 + val initialSubtitleItemIndex = selectedSubtitleTrackIndex?.plus(1) ?: 0 + val initialAudioIndex = selectedAudioTrackIndex?.takeIf { it in audioTracks.indices } ?: 0 + val subtitleListState = rememberLazyListState() + val audioListState = rememberLazyListState() val scrollState = rememberScrollState() + LaunchedEffect(menu, initialSubtitleItemIndex, initialAudioIndex) { + when (menu) { + PlayerMenu.Subtitles -> subtitleListState.scrollToItem(initialSubtitleItemIndex) + PlayerMenu.Audio -> if (audioTracks.isNotEmpty()) { + audioListState.scrollToItem(initialAudioIndex) + } + else -> Unit + } + } + Column( modifier = modifier .fillMaxWidth() .heightIn(max = 420.dp) .clip(RoundedCornerShape(8.dp)) - .background(Color.Black.copy(alpha = 0.72f)) + .background(Color.Black.copy(alpha = 0.58f)) .border(1.dp, Color.White.copy(alpha = 0.16f), RoundedCornerShape(8.dp)) .padding(18.dp) .verticalScroll(scrollState) @@ -1219,7 +1500,7 @@ internal fun PlayerOptionsPanel( text = playbackSpeedValueLabel(speed), selected = speed == playbackSpeed, onClick = { onSelectSpeed(speed) }, - modifier = if (index == 0) { + modifier = if (index == initialSpeedIndex) { Modifier.then(initialFocusHandle.modifier()) } else { Modifier @@ -1227,31 +1508,40 @@ internal fun PlayerOptionsPanel( ) } } - PlayerMenu.Subtitles -> FlowRow( + PlayerMenu.Subtitles -> LazyRow( + state = subtitleListState, horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), - itemVerticalAlignment = Alignment.CenterVertically, ) { - PlayerOptionButton( - text = playbackSubtitleOffLabel(), - selected = selectedSubtitleTrackIndex == null, - onClick = { onSelectSubtitle(null) }, - modifier = Modifier.then(initialFocusHandle.modifier()), - ) - subtitles.forEachIndexed { index, track -> + item { + PlayerOptionButton( + text = playbackSubtitleOffLabel(), + selected = selectedSubtitleTrackIndex == null, + onClick = { onSelectSubtitle(null) }, + modifier = if (selectedSubtitleTrackIndex == null) { + Modifier.then(initialFocusHandle.modifier()) + } else { + Modifier + }, + ) + } + itemsIndexed(subtitles) { index, track -> PlayerOptionButton( text = playbackSubtitleOptionLabel(track, index), selected = index == selectedSubtitleTrackIndex, onClick = { onSelectSubtitle(index) }, + modifier = if (index == selectedSubtitleTrackIndex) { + Modifier.then(initialFocusHandle.modifier()) + } else { + Modifier + }, ) } } - PlayerMenu.Audio -> FlowRow( + PlayerMenu.Audio -> LazyRow( + state = audioListState, horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), - itemVerticalAlignment = Alignment.CenterVertically, ) { - audioTracks.forEachIndexed { index, track -> + itemsIndexed(audioTracks) { index, track -> PlayerOptionButton( text = playbackAudioOptionLabel( title = track.title, @@ -1260,11 +1550,11 @@ internal fun PlayerOptionsPanel( ), selected = index == selectedAudioTrackIndex, onClick = { onSelectAudioTrack(index) }, - modifier = if (index == 0) { + modifier = if (index == initialAudioIndex) { Modifier.then(initialFocusHandle.modifier()) } else { Modifier - } + }, ) } } @@ -1281,7 +1571,7 @@ internal fun PlayerOptionsPanel( text = "${pictureSessionOverrideLabel()} ${toneMappingPresetLabel(preset)}", selected = preset == currentPicturePreset, onClick = { onSelectPicturePreset(preset) }, - modifier = if (index == 0) { + modifier = if (index == initialPictureIndex) { Modifier.then(initialFocusHandle.modifier()) } else { Modifier @@ -1310,6 +1600,179 @@ internal fun PlayerOptionsPanel( } } +@Composable +private fun PlayerInfoPanel( + tab: PlayerInfoTab, + onTabChange: (PlayerInfoTab) -> Unit, + title: String, + sourceLabel: String, + source: PlaybackSource, + playbackState: PlaybackState, + currentPosition: Long, + duration: Long, + playbackSpeed: Float, + signal: VideoSignalDescriptor?, + requestedBackend: PlaybackRenderBackend, + activeBackend: PlaybackRenderBackend, + fallbackReason: String?, + subtitles: List, + audioTracks: List, + selectedSubtitleTrackIndex: Int?, + selectedAudioTrackIndex: Int?, +) { + val infoInitialFocus = rememberInitialFocusHandle() + val scrollState = rememberScrollState() + val selectedSubtitle = selectedSubtitleTrackIndex + ?.let { index -> subtitles.getOrNull(index)?.let { playbackSubtitleOptionLabel(it, index) } } + ?: playbackSubtitleOffLabel() + val selectedAudio = selectedAudioTrackIndex + ?.let { index -> + audioTracks.getOrNull(index)?.let { + playbackAudioOptionLabel(it.title, it.language, index) + } + } + ?: "—" + + Column( + modifier = Modifier + .width(480.dp) + .fillMaxHeight() + .background(Color.Black.copy(alpha = 0.66f)) + .border(1.dp, Color.White.copy(alpha = 0.14f)) + .padding(horizontal = 26.dp, vertical = 28.dp), + ) { + Text( + text = "播放信息", + style = TvTypography.subtitle, + color = TextPrimary, + ) + Spacer(Modifier.height(18.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + PlayerOptionButton( + text = "信息", + selected = tab == PlayerInfoTab.Information, + onClick = { onTabChange(PlayerInfoTab.Information) }, + modifier = infoInitialFocus.modifier(), + ) + PlayerOptionButton( + text = "播放 / 调试", + selected = tab == PlayerInfoTab.Diagnostics, + onClick = { onTabChange(PlayerInfoTab.Diagnostics) }, + ) + } + Spacer(Modifier.height(18.dp)) + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(scrollState), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + when (tab) { + PlayerInfoTab.Information -> { + PlayerInfoRow("番剧 / 剧集", title) + PlayerInfoRow("元数据", sourceLabel) + PlayerInfoRow("文件", sanitizedPlaybackSourceName(source.uri)) + PlayerInfoRow("来源类型", playbackSourceSchemeLabel(source.uri)) + PlayerInfoRow("时长", formatPlaybackPosition(duration)) + PlayerInfoRow("视频信号", signal?.displayLabel() ?: "—") + PlayerInfoRow("视频编码", signal?.codecId?.takeIf(String::isNotBlank) ?: "—") + PlayerInfoRow("位深", signal?.bitDepth?.let { "$it bit" } ?: "—") + PlayerInfoRow("当前音轨", selectedAudio) + PlayerInfoRow("当前字幕", selectedSubtitle) + } + PlayerInfoTab.Diagnostics -> { + PlayerInfoRow("状态", playbackStateInfoLabel(playbackState)) + PlayerInfoRow("位置", formatPlaybackPosition(currentPosition)) + PlayerInfoRow("总时长", formatPlaybackPosition(duration)) + PlayerInfoRow("速度", playbackSpeedValueLabel(playbackSpeed)) + PlayerInfoRow("请求后端", playbackBackendLabel(requestedBackend)) + PlayerInfoRow("活动后端", playbackBackendLabel(activeBackend)) + PlayerInfoRow("回退原因", fallbackReason?.takeIf(String::isNotBlank) ?: "—") + PlayerInfoRow("传递函数", signal?.transfer?.name ?: "—") + PlayerInfoRow("色彩原色", signal?.colorPrimaries?.name ?: "—") + PlayerInfoRow("HDR 静态元数据", signal?.hasHdrStaticMetadata?.yesNoLabel() ?: "—") + PlayerInfoRow("HDR10+ 元数据", signal?.hasHdr10PlusMetadata?.yesNoLabel() ?: "—") + PlayerInfoRow("字幕轨", subtitles.size.toString()) + PlayerInfoRow("音轨", audioTracks.size.toString()) + } + } + } + } +} + +@Composable +private fun PlayerInfoRow(label: String, value: String) { + val interactionSource = remember { MutableInteractionSource() } + val isFocused by interactionSource.collectIsFocusedAsState() + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(6.dp)) + .background(Color.White.copy(alpha = if (isFocused) 0.14f else 0.04f)) + .border( + width = if (isFocused) 1.dp else 0.dp, + color = if (isFocused) FocusBorder else Color.Transparent, + shape = RoundedCornerShape(6.dp), + ) + .focusable(interactionSource = interactionSource) + .padding(horizontal = 12.dp, vertical = 9.dp), + horizontalArrangement = Arrangement.spacedBy(14.dp), + verticalAlignment = Alignment.Top, + ) { + Text( + text = label, + color = TextSecondary, + style = TvTypography.caption, + modifier = Modifier.width(118.dp), + ) + Text( + text = value.ifBlank { "—" }, + color = TextPrimary, + style = TvTypography.caption.copy(fontWeight = FontWeight.SemiBold), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + } +} + +internal fun sanitizedPlaybackSourceName(uri: String): String = + runCatching { + val rawName = if (uri.isLocalPlaybackPath()) { + uri.substringAfterLast('/').substringAfterLast('\\') + } else { + Uri.parse(uri).lastPathSegment.orEmpty() + } + Uri.decode(rawName).takeIf(String::isNotBlank) + }.getOrNull() ?: "—" + +internal fun playbackSourceSchemeLabel(uri: String): String = + if (uri.isLocalPlaybackPath()) { + "本地文件" + } else { + runCatching { Uri.parse(uri).scheme } + .getOrNull() + ?.takeIf(String::isNotBlank) + ?.uppercase() + ?: "本地文件" + } + +private fun String.isLocalPlaybackPath(): Boolean = + startsWith('/') || matches(Regex("^[A-Za-z]:[\\\\/].*")) + +private fun playbackStateInfoLabel(state: PlaybackState): String = + when (state) { + PlaybackState.Idle -> "空闲" + is PlaybackState.Loading -> "加载中" + is PlaybackState.Playing -> "播放中" + is PlaybackState.Paused -> "已暂停" + is PlaybackState.Buffering -> "缓冲中" + is PlaybackState.Ended -> "已结束" + is PlaybackState.Error -> "错误" + } + +private fun Boolean.yesNoLabel(): String = if (this) "是" else "否" + @Composable private fun PlayerOptionButton( text: String, @@ -1332,6 +1795,7 @@ private fun PlayerOptionButton( enabled = enabled, interactionSource = interactionSource, modifier = modifier + .scale(if (isFocused) 1.04f else 1f) .heightIn(min = 48.dp) .clip(RoundedCornerShape(8.dp)) .onPreviewKeyEvent { event -> @@ -1342,8 +1806,12 @@ private fun PlayerOptionButton( ) } .border( - width = if (isFocused || selected) 2.dp else 1.dp, - color = if (isFocused) FocusBorder else Color.White.copy(alpha = 0.14f), + width = when { + isFocused -> 3.dp + selected -> 2.dp + else -> 1.dp + }, + color = if (isFocused) Color.White else Color.White.copy(alpha = 0.14f), shape = RoundedCornerShape(8.dp) ), shape = RoundedCornerShape(8.dp), @@ -1429,23 +1897,62 @@ internal enum class PlayerMenu { Audio } +internal enum class PlayerInfoTab { + Information, + Diagnostics, +} + +private enum class PlayerChromeFocusTarget { + Timeline, + Picture, + Speed, + Subtitles, + Audio, +} + +internal const val PLAYER_TIMELINE_TEST_TAG = "player-timeline" + private fun handlePlayerKey( event: KeyEvent, + repeatsDedicatedCommand: Boolean, controlsVisible: Boolean, hasOpenMenu: Boolean, + hasSubtitles: Boolean, + canPlayPreviousEpisode: Boolean, + canPlayNextEpisode: Boolean, viewModel: PlayerViewModel, onCloseMenu: () -> Unit, onHideControls: () -> Unit, - onNavigateBack: () -> Unit + onOpenCaptions: () -> Unit, + onFocusOptions: () -> Unit, + onToggleInfo: () -> Unit, + onStop: () -> Unit, + onNavigateBack: () -> Unit, ): Boolean { - if (event.type != KeyEventType.KeyDown) return false + val intent = event.key.toMiruPlayInputIntent() ?: return false + val dedicatedAvailable = when (intent) { + com.miruplay.tv.design.MiruPlayInputIntent.MediaPrevious -> canPlayPreviousEpisode + com.miruplay.tv.design.MiruPlayInputIntent.MediaNext -> canPlayNextEpisode + com.miruplay.tv.design.MiruPlayInputIntent.Captions -> hasSubtitles + else -> true + } + if (!dedicatedAvailable) return false - val action = event.key.toMiruPlayInputIntent() - ?.tvPlaybackOverlayAction( - controlsVisible = controlsVisible, - hasOpenMenu = hasOpenMenu, - ) - ?: return false + if (event.type != KeyEventType.KeyDown) { + return event.type == KeyEventType.KeyUp && intent.isDedicatedPlayerRemoteIntent() + } + if ( + intent.isDedicatedPlayerRemoteIntent() && + repeatsDedicatedCommand && + !intent.allowsPlayerRemoteRepeat() + ) { + return true + } + + val action = intent.tvPlaybackOverlayAction( + controlsVisible = controlsVisible, + hasOpenMenu = hasOpenMenu, + ) ?: return false if (action.shouldRefreshTvPlaybackControls(controlsVisible)) { viewModel.showControls() @@ -1460,6 +1967,26 @@ private fun handlePlayerKey( viewModel.skipForward() true } + MiruPlayPlaybackInputAction.PreviousEpisode -> { + viewModel.playPreviousEpisode() + true + } + MiruPlayPlaybackInputAction.NextEpisode -> { + viewModel.playNextEpisode() + true + } + MiruPlayPlaybackInputAction.OpenCaptions -> { + onOpenCaptions() + true + } + MiruPlayPlaybackInputAction.FocusOptions -> { + onFocusOptions() + true + } + MiruPlayPlaybackInputAction.ToggleInfo -> { + onToggleInfo() + true + } MiruPlayPlaybackInputAction.ShowControls -> true MiruPlayPlaybackInputAction.TogglePause -> { viewModel.togglePlayback() @@ -1473,6 +2000,10 @@ private fun handlePlayerKey( viewModel.pause() true } + MiruPlayPlaybackInputAction.Stop -> { + onStop() + true + } MiruPlayPlaybackInputAction.HideControls -> { onHideControls() true @@ -1485,8 +2016,6 @@ private fun handlePlayerKey( onNavigateBack() true } - MiruPlayPlaybackInputAction.Launch, - MiruPlayPlaybackInputAction.Stop, - -> false + MiruPlayPlaybackInputAction.Launch -> false } } diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerViewModel.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerViewModel.kt index e1c5d9d5..476cf04a 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerViewModel.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/player/PlayerViewModel.kt @@ -159,6 +159,14 @@ class PlayerViewModel @Inject constructor( private val _pendingNextEpisode = MutableStateFlow(null) val pendingNextEpisode: StateFlow = _pendingNextEpisode.asStateFlow() + private val _canPlayPreviousEpisode = MutableStateFlow(false) + val canPlayPreviousEpisode: StateFlow = _canPlayPreviousEpisode.asStateFlow() + + private val _canPlayNextEpisode = MutableStateFlow(false) + val canPlayNextEpisode: StateFlow = _canPlayNextEpisode.asStateFlow() + + private var pendingSelectionExitsPlayback = false + private var progressSaveJob: Job? = null private var positionPollJob: Job? = null private var finishObserverJob: Job? = null @@ -191,7 +199,9 @@ class PlayerViewModel @Inject constructor( activeSource = resolvedSource activeScreenOwnerToken = ownerToken _pendingNextEpisode.value = null + pendingSelectionExitsPlayback = false _activePlaybackSource.value = resolvedSource + refreshAdjacentEpisodeAvailability(resolvedSource) startPresentationResolution(resolvedSource) refreshFormatAwarePreferences() playbackController.play(resolvedSource).also { @@ -246,6 +256,36 @@ class PlayerViewModel @Inject constructor( seekFromControls(seekBasePosition() - PLAYBACK_SEEK_BACK_SECONDS * 1_000L) } + fun playPreviousEpisode() { + viewModelScope.launch { + val source = activeSource ?: return@launch + val episode = nextPlaybackSourceResolver.previousEpisode(source) ?: return@launch + if (shouldChooseEpisodeVersion(episode)) { + pendingSelectionExitsPlayback = false + _pendingNextEpisode.value = episode + } else { + nextPlaybackSourceResolver.buildPrevious(source)?.let { play(it) } + } + } + } + + fun playNextEpisode() { + viewModelScope.launch { + val source = activeSource ?: return@launch + val episode = nextPlaybackSourceResolver.nextEpisode(source) ?: return@launch + if (shouldChooseEpisodeVersion(episode)) { + pendingSelectionExitsPlayback = false + _pendingNextEpisode.value = episode + } else { + nextPlaybackSourceResolver.build(source)?.let { play(it) } + } + } + } + + private suspend fun shouldChooseEpisodeVersion(episode: Episode): Boolean = + episode.availableVersions().size > 1 && + playbackPreferences.getEpisodeVersionSelectionPolicy() == EpisodeVersionSelectionPolicy.MANUAL + fun toggleControls() { if (_controlsVisible.value) { hideControls() @@ -524,11 +564,9 @@ class PlayerViewModel @Inject constructor( if (playbackPreferences.getEndAction() == PlaybackEndAction.PLAY_NEXT_EPISODE) { val nextEpisode = nextPlaybackSourceResolver.nextEpisode(source) - if (nextEpisode != null && - nextEpisode.availableVersions().size > 1 && - playbackPreferences.getEpisodeVersionSelectionPolicy() == EpisodeVersionSelectionPolicy.MANUAL - ) { + if (nextEpisode != null && shouldChooseEpisodeVersion(nextEpisode)) { bangumiSyncEngine.get().markEpisodeWatched(episodeId) + pendingSelectionExitsPlayback = true _pendingNextEpisode.value = nextEpisode return } @@ -555,7 +593,23 @@ class PlayerViewModel @Inject constructor( fun cancelNextVersionSelection() { _pendingNextEpisode.value = null - _finishEvents.tryEmit(PlaybackFinishEvent.NavigateBack) + if (pendingSelectionExitsPlayback) { + pendingSelectionExitsPlayback = false + _finishEvents.tryEmit(PlaybackFinishEvent.NavigateBack) + } + } + + private fun refreshAdjacentEpisodeAvailability(source: PlaybackSource) { + _canPlayPreviousEpisode.value = false + _canPlayNextEpisode.value = false + viewModelScope.launch { + val previous = nextPlaybackSourceResolver.previousEpisode(source) != null + val next = nextPlaybackSourceResolver.nextEpisode(source) != null + if (activeSource == source) { + _canPlayPreviousEpisode.value = previous + _canPlayNextEpisode.value = next + } + } } private suspend fun buildNextPlaybackSource(source: PlaybackSource): PlaybackSource? { @@ -605,6 +659,9 @@ class PlayerViewModel @Inject constructor( activeScreenOwnerToken = null _activePlaybackSource.value = null _pendingNextEpisode.value = null + pendingSelectionExitsPlayback = false + _canPlayPreviousEpisode.value = false + _canPlayNextEpisode.value = false _displayTitle.value = "" _displaySubtitle.value = "" _currentPosition.value = 0L diff --git a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerInfoSanitizationTest.kt b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerInfoSanitizationTest.kt new file mode 100644 index 00000000..37e5c2aa --- /dev/null +++ b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerInfoSanitizationTest.kt @@ -0,0 +1,31 @@ +package com.miruplay.tv.ui.player + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class PlayerInfoSanitizationTest { + @Test + fun `remote source shows only decoded file name and scheme`() { + val source = "https://dav.example/private/Episode%2001.mkv?token=secret" + val name = sanitizedPlaybackSourceName(source) + + assertEquals("Episode 01.mkv", name) + assertEquals("HTTPS", playbackSourceSchemeLabel(source)) + assertFalse(name.contains("secret")) + assertFalse(name.contains("dav.example")) + } + + @Test + fun `windows source is identified as a local file`() { + val source = "D:\\Anime\\Episode 02.mkv" + + assertEquals("Episode 02.mkv", sanitizedPlaybackSourceName(source)) + assertEquals("本地文件", playbackSourceSchemeLabel(source)) + } +} diff --git a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandlingTest.kt b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandlingTest.kt index e6d9cb34..45d77cff 100644 --- a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandlingTest.kt +++ b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerKeyHandlingTest.kt @@ -8,99 +8,55 @@ import org.junit.Assert.assertTrue import org.junit.Test class PlayerKeyHandlingTest { - @Test - fun `direction keys still skip when controls are visible`() { + fun `focused timeline left and right seek on initial and repeated key down`() { val calls = mutableListOf() - val consumed = handlePlayerKey( - key = Key.DirectionRight, + val first = handlePlaybackTimelineKey( + key = Key.DirectionLeft, type = KeyEventType.KeyDown, - controlsVisible = true, - hasOpenMenu = false, - actions = testActions(calls) + onSkipBackward = { calls.add("skipBackward") }, + onSkipForward = { calls.add("skipForward") }, ) - - assertTrue(consumed) - assertEquals(listOf("showControls", "skipForward"), calls) - } - - @Test - fun `direction keys stay with focus when a menu is open`() { - listOf(Key.DirectionLeft, Key.DirectionRight).forEach { key -> - val calls = mutableListOf() - - val consumed = handlePlayerKey( - key = key, - type = KeyEventType.KeyDown, - controlsVisible = true, - hasOpenMenu = true, - actions = testActions(calls) - ) - - assertFalse(consumed) - assertTrue(calls.isEmpty()) - } - } - - @Test - fun `direction keys still skip when controls are hidden`() { - val calls = mutableListOf() - - val consumed = handlePlayerKey( - key = Key.DirectionRight, + val repeated = handlePlaybackTimelineKey( + key = Key.DirectionLeft, type = KeyEventType.KeyDown, - controlsVisible = false, - hasOpenMenu = false, - actions = testActions(calls) + onSkipBackward = { calls.add("skipBackward") }, + onSkipForward = { calls.add("skipForward") }, ) - assertTrue(consumed) - assertEquals(listOf("showControls", "skipForward"), calls) + assertTrue(first) + assertTrue(repeated) + assertEquals(listOf("skipBackward", "skipBackward"), calls) } @Test - fun `back closes the open menu before hiding controls`() { + fun `timeline key up does not seek`() { val calls = mutableListOf() - val consumed = handlePlayerKey( - key = Key.Back, - type = KeyEventType.KeyDown, - controlsVisible = true, - hasOpenMenu = true, - actions = testActions(calls) + val consumed = handlePlaybackTimelineKey( + key = Key.DirectionRight, + type = KeyEventType.KeyUp, + onSkipBackward = { calls.add("skipBackward") }, + onSkipForward = { calls.add("skipForward") }, ) - assertTrue(consumed) - assertEquals(listOf("closeMenu"), calls) + assertFalse(consumed) + assertTrue(calls.isEmpty()) } @Test - fun `back navigates away when controls are hidden`() { + fun `timeline leaves non horizontal keys to focus traversal`() { val calls = mutableListOf() - val consumed = handlePlayerKey( - key = Key.Back, + val consumed = handlePlaybackTimelineKey( + key = Key.DirectionDown, type = KeyEventType.KeyDown, - controlsVisible = false, - hasOpenMenu = false, - actions = testActions(calls) + onSkipBackward = { calls.add("skipBackward") }, + onSkipForward = { calls.add("skipForward") }, ) - assertTrue(consumed) - assertEquals(listOf("navigateBack"), calls) + assertFalse(consumed) + assertTrue(calls.isEmpty()) } - - private fun testActions(calls: MutableList): PlayerKeyActions = - PlayerKeyActions( - skipBackward = { calls.add("skipBackward") }, - skipForward = { calls.add("skipForward") }, - togglePlayback = { calls.add("togglePlayback") }, - resume = { calls.add("resume") }, - pause = { calls.add("pause") }, - showControls = { calls.add("showControls") }, - hideControls = { calls.add("hideControls") }, - closeMenu = { calls.add("closeMenu") }, - navigateBack = { calls.add("navigateBack") } - ) } diff --git a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerOptionsPanelFocusTest.kt b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerOptionsPanelFocusTest.kt index b112fabc..0cf137df 100644 --- a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerOptionsPanelFocusTest.kt +++ b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerOptionsPanelFocusTest.kt @@ -3,7 +3,11 @@ package com.miruplay.tv.ui.player import androidx.compose.ui.test.assertIsFocused import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText +import com.miruplay.tv.model.SubtitleTrack import com.miruplay.tv.model.ToneMappingProfilePreset +import com.miruplay.tv.model.pictureSessionOverrideLabel +import com.miruplay.tv.model.playbackSubtitleOptionLabel +import com.miruplay.tv.model.toneMappingPresetLabel import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -17,7 +21,48 @@ class PlayerOptionsPanelFocusTest { val compose = createComposeRule() @Test - fun `picture menu assigns initial focus to first preset chip`() { + fun `subtitle menu scrolls to and focuses an offscreen selected track`() { + val selectedIndex = 12 + val subtitles = List(18) { index -> + SubtitleTrack( + language = "en", + title = "Subtitle $index", + path = "/subtitle-$index.srt", + ) + } + val selectedLabel = playbackSubtitleOptionLabel(subtitles[selectedIndex], selectedIndex) + compose.setContent { + PlayerOptionsPanel( + menu = PlayerMenu.Subtitles, + subtitles = subtitles, + audioTracks = emptyList(), + selectedSubtitleTrackIndex = selectedIndex, + selectedAudioTrackIndex = null, + playbackSpeed = 1.0f, + currentPicturePreset = ToneMappingProfilePreset.BALANCED, + onSelectSubtitle = {}, + onSelectAudioTrack = {}, + onSelectSpeed = {}, + onSelectPicturePreset = {}, + onSavePictureDefault = {}, + onResetPictureSession = {}, + ) + } + + compose.waitUntil(timeoutMillis = 5_000) { + runCatching { + compose.onNodeWithText(selectedLabel).assertIsFocused() + true + }.getOrDefault(false) + } + + compose.onNodeWithText(selectedLabel).assertIsFocused() + } + + @Test + fun `picture menu assigns initial focus to selected preset`() { + val selectedLabel = + "${pictureSessionOverrideLabel()} ${toneMappingPresetLabel(ToneMappingProfilePreset.BALANCED)}" compose.setContent { PlayerOptionsPanel( menu = PlayerMenu.Picture, @@ -38,11 +83,11 @@ class PlayerOptionsPanelFocusTest { compose.waitUntil(timeoutMillis = 5_000) { runCatching { - compose.onNodeWithText("仅本次播放 直通").assertIsFocused() + compose.onNodeWithText(selectedLabel).assertIsFocused() true }.getOrDefault(false) } - compose.onNodeWithText("仅本次播放 直通").assertIsFocused() + compose.onNodeWithText(selectedLabel).assertIsFocused() } } diff --git a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerTimelineFocusTest.kt b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerTimelineFocusTest.kt new file mode 100644 index 00000000..13237754 --- /dev/null +++ b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/player/PlayerTimelineFocusTest.kt @@ -0,0 +1,107 @@ +package com.miruplay.tv.ui.player + +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.unit.dp +import com.miruplay.tv.model.playbackAudioTrackCountLabel +import com.miruplay.tv.player.AudioTrack +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +@OptIn(ExperimentalTestApi::class) +class PlayerTimelineFocusTest { + @get:Rule + val compose = createComposeRule() + + @Test + fun `controls focus timeline and down follows the nearest enabled action`() { + var controlsVisible by mutableStateOf(false) + + compose.setContent { + val timelineFocusRequester = remember { FocusRequester() } + val transportFocusRequester = remember { FocusRequester() } + val pictureFocusRequester = remember { FocusRequester() } + val speedFocusRequester = remember { FocusRequester() } + val subtitlesFocusRequester = remember { FocusRequester() } + val audioFocusRequester = remember { FocusRequester() } + + LaunchedEffect(controlsVisible) { + if (controlsVisible) { + timelineFocusRequester.requestFocus() + } + } + + Box( + modifier = Modifier + .size(width = 960.dp, height = 540.dp) + .focusable(), + ) { + if (controlsVisible) { + PlayerBottomBar( + currentPosition = 12_000L, + duration = 60_000L, + subtitles = emptyList(), + audioTracks = listOf(AudioTrack(index = 0, language = "jpn")), + selectedSubtitleTrackIndex = null, + selectedAudioTrackIndex = null, + playbackSpeed = 1.0f, + signalFormatLabel = "", + openMenu = null, + timelineFocusRequester = timelineFocusRequester, + transportFocusRequester = transportFocusRequester, + pictureFocusRequester = pictureFocusRequester, + speedFocusRequester = speedFocusRequester, + subtitlesFocusRequester = subtitlesFocusRequester, + audioFocusRequester = audioFocusRequester, + onSkipBackward = { error("Timeline seek was not expected") }, + onSkipForward = { error("Timeline seek was not expected") }, + onOpenMenu = {}, + ) + } + } + } + + compose.runOnIdle { + controlsVisible = true + } + + compose.waitUntil(timeoutMillis = 5_000) { + runCatching { + compose.onNodeWithTag(PLAYER_TIMELINE_TEST_TAG).assertIsFocused() + true + }.getOrDefault(false) + } + compose.onNodeWithTag(PLAYER_TIMELINE_TEST_TAG).assertIsFocused() + compose.onNodeWithTag(PLAYER_TIMELINE_TEST_TAG).performKeyInput { + pressKey(Key.DirectionDown) + } + compose.onNodeWithText(playbackAudioTrackCountLabel(1)).assertIsFocused() + compose.onNodeWithText(playbackAudioTrackCountLabel(1)).performKeyInput { + pressKey(Key.DirectionUp) + } + compose.onNodeWithTag(PLAYER_TIMELINE_TEST_TAG).assertIsFocused() + } + +} diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt index 2d332a32..e8a98fb2 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt @@ -332,12 +332,19 @@ data class ScanSettingsRequest( val currentAppMode: String? = null, ) +@Serializable +data class PlaybackBackendOptionDto( + val value: String, + val label: String, +) + @Serializable data class PlaybackSettingsDto( val endAction: String, val episodeVersionSelectionPolicy: String = "auto_nearest", val preferredSubtitleLanguage: String, val formatAwareToneMapping: FormatAwareToneMappingPreferences, + val backendOptions: List = emptyList(), val endActionOptions: List = listOf("return_to_detail", "play_next_episode"), val episodeVersionSelectionPolicyOptions: List = listOf("auto_nearest", "manual"), val preferredSubtitleLanguageOptions: List = diff --git a/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt index f70b3c10..6924f186 100644 --- a/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt +++ b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt @@ -72,6 +72,8 @@ class WebControlSettingsRouteTest { assertTrue(body.contains("\"preferredSubtitleLanguage\":\"zh_hans\"")) assertTrue(body.contains("\"preferredSubtitleLanguageOptions\"")) assertTrue(body.contains("\"formatAwareToneMapping\"")) + assertTrue(body.contains("\"backendOptions\"")) + assertTrue(body.contains("\"value\":\"EXPERIMENTAL_IJKPLAYER\"")) } @Test @@ -216,6 +218,12 @@ class WebControlSettingsRouteTest { endAction = "return_to_detail", preferredSubtitleLanguage = "zh_hans", formatAwareToneMapping = FormatAwareToneMappingPreferences(), + backendOptions = listOf( + PlaybackBackendOptionDto( + value = "EXPERIMENTAL_IJKPLAYER", + label = "实验 ijkplayer", + ), + ), ) override suspend fun savePlaybackSettings(request: PlaybackSettingsRequest): PlaybackSettingsDto { diff --git a/web-control/frontend/src/App.vue b/web-control/frontend/src/App.vue index 59c59bea..008a4674 100644 --- a/web-control/frontend/src/App.vue +++ b/web-control/frontend/src/App.vue @@ -1099,13 +1099,20 @@ + ({ library: ['片库', '浏览番剧、选择剧集并投到电视端播放。'], @@ -2979,6 +2981,7 @@ function applyPlaybackSettings(data) { playbackSettings.episodeVersionSelectionPolicy = data.episodeVersionSelectionPolicy || 'auto_nearest' playbackSettings.preferredSubtitleLanguage = data.preferredSubtitleLanguage || 'auto' playbackSettings.formatAwareToneMapping = data.formatAwareToneMapping || null + playbackSettings.backendOptions = Array.isArray(data.backendOptions) ? data.backendOptions : [] playbackSettings.endActionOptions = data.endActionOptions || ['return_to_detail', 'play_next_episode'] playbackSettings.episodeVersionSelectionPolicyOptions = data.episodeVersionSelectionPolicyOptions || ['auto_nearest', 'manual'] playbackSettings.preferredSubtitleLanguageOptions = data.preferredSubtitleLanguageOptions || ['auto', 'zh_hans', 'zh_hant', 'zh', 'en', 'ja'] diff --git a/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMapping.kt b/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMapping.kt index efe97c32..0e71cfd4 100644 --- a/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMapping.kt +++ b/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMapping.kt @@ -13,6 +13,7 @@ internal fun playbackRenderBackendFromDebugValue(value: String?): PlaybackRender "experimentalgl", "gl" -> PlaybackRenderBackend.EXPERIMENTAL_GL "experimentalmpvandroid", "mpvandroid" -> PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED "experimentalmpvembedded", "mpvembedded", "embeddedmpv", "libmpv", "mpv" -> PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED + "experimentalijkplayer", "ijkplayer", "ijk" -> PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER "experimentallibvlc", "libvlc", "vlc" -> PlaybackRenderBackend.EXPERIMENTAL_LIBVLC else -> null } diff --git a/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlService.kt b/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlService.kt index cdfc1e69..43898830 100644 --- a/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlService.kt +++ b/web-control/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlService.kt @@ -18,6 +18,8 @@ import com.miruplay.tv.model.PlaybackEndAction import com.miruplay.tv.model.SubtitleLanguagePreference import com.miruplay.tv.model.PlaybackRenderBackend import com.miruplay.tv.model.ScanResult +import com.miruplay.tv.model.playbackBackendLabel +import com.miruplay.tv.model.supportedPlaybackRenderBackends import com.miruplay.tv.model.buildToneMappingPreset import com.miruplay.tv.player.PlaybackController import com.miruplay.tv.player.PlaybackDebugOverrides @@ -716,6 +718,12 @@ class WebControlService @Inject constructor( episodeVersionSelectionPolicy = episodeVersionSelectionPolicy.storageValue, preferredSubtitleLanguage = preferredSubtitleLanguage.storageValue, formatAwareToneMapping = toneMapping, + backendOptions = supportedPlaybackRenderBackends().map { backend -> + PlaybackBackendOptionDto( + value = backend.name, + label = playbackBackendLabel(backend), + ) + }, ) } diff --git a/web-control/src/test/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMappingTest.kt b/web-control/src/test/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMappingTest.kt index b43a90ae..0e07d103 100644 --- a/web-control/src/test/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMappingTest.kt +++ b/web-control/src/test/kotlin/com/miruplay/tv/webcontrol/PlaybackDebugConfigMappingTest.kt @@ -21,6 +21,8 @@ class PlaybackDebugConfigMappingTest { assertEquals(PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED, playbackRenderBackendFromDebugValue("mpvandroid")) assertEquals(PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED, playbackRenderBackendFromDebugValue("libmpv")) assertEquals(PlaybackRenderBackend.EXPERIMENTAL_MPV_EMBEDDED, playbackRenderBackendFromDebugValue("mpv")) + assertEquals(PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, playbackRenderBackendFromDebugValue("ijk")) + assertEquals(PlaybackRenderBackend.EXPERIMENTAL_IJKPLAYER, playbackRenderBackendFromDebugValue("ijkplayer")) assertNull(playbackRenderBackendFromDebugValue("unknown")) }