Open RedPlayer v1.0 modifies

This commit is contained in:
hongdaLL 2023-11-14 10:49:21 +08:00
commit 418a9c3e12
335 changed files with 23948 additions and 0 deletions

12
CONTENTS.md Normal file
View File

@ -0,0 +1,12 @@
<!-- Describe the main content of this issue's open source and the estimated time and content of the next open source -->
# Contents of this open source
- Open source code for playing intermediate layer (including: instance management, interface calls, etc.)
- RedPlayer is open source in the form of SDK this time
# Next open source plan
- Estimated time for next open source: In coming...
- Estimated content for next open source: OpenCore module code and Harmony version

502
COPYING.LGPLv2.1 Normal file
View File

@ -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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

165
COPYING.LGPLv3 Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
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 that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU 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 as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

8
INTERFACES.md Normal file
View File

@ -0,0 +1,8 @@
<!-- Introduction to core Interface -->
# Android Interfaces
* [API Docs](source/android/API.md)<br>The API Docs contain [RedPlayer-SDK](source/android/README.md) and [RedPreload-SDK](source/android/Preload_README.md) all interface description. If you want to get started quickly, please read the [Quick Start](source/android/README.md) section.
# IOS Interfaces
* Quck start for Player SDK: [RedPlayer-SDK](source/ios/README.md)
* Quck start for Preload SDK: [RedPreload-SDK](source/ios/RedPreload_SDK.md)

29
JSON.md Normal file
View File

@ -0,0 +1,29 @@
There is an example of JSON format.
```
{
"stream": { /* Different encoding format streams */
"h264": [{
"width": 720, /* video width */
"height": 1280, /* video height */
"avg_bitrate": 1035154, /* video average bitrate */
"master_url": "http://example_h264_720x1080_master.mp4", /* video URL */
"backup_urls": ["http://example_h264_720x1080_backup1.mp4", "http://example_h264_720x1080_backup2.mp4", "http://example_h264_720x1080_backup3.mp4", "http://example_h264_720x1080_backup4.mp4"] /* Backup URLs used when there is a problem playing the master URL */
}],
/* Multiple streams can exist within the same encoding format */
"h265": [{ /* h265 stream1 */
"width": 720,
"height": 1280,
"avg_bitrate": 687026,
"master_url": "http://example_h265_720x1080_master.mp4",
"backup_urls": ["http://example_h265_720x1080_backup1.mp4", "http://example_h265_720x1080_backup2.mp4", "http://example_h265_720x1080_backup3.mp4", "http://example_h265_720x1080_backup4.mp4"]
}, { /* h265 stream2 */
"width": 1080,
"height": 1920,
"avg_bitrate": 939554,
"master_url": "http://example_h265_1080x1920_master.mp4",
"backup_urls": ["http://example_h265_1080x1920_backup1.mp4", "http://example_h265_1080x1920_backup2.mp4", "http://example_h265_1080x1920_backup3.mp4", "http://example_h265_1080x1920_backup4.mp4"]
}]
}
}
```

0
MODULE_LICENSE_APACHE2 Normal file
View File

10
NEWS.md Normal file
View File

@ -0,0 +1,10 @@
tag v0.0.1:
--------------------------------
- ffmpeg: switch to tag n4.3.1
- ffmpeg: added a new protocol and some methods
- soundtouch: switch to tag 2.3.2
- soundtouch: use integer samples for player
- player: provided a player SDK with basic playback capabilities
- preload: provided a preload SDK with preloading capabilities
- demo: provided playback demos for both Android and iOS platforms

190
NOTICE Normal file
View File

@ -0,0 +1,190 @@
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

135
README.md Normal file
View File

@ -0,0 +1,135 @@
# redplayer
![示例图片](./redplayer.jpg)
![GitHub release (latest by date including pre-releases)](https://img.shields.io/badge/release-v1.0.0-blue)
![GitHub issues](https://img.shields.io/github/issues/badges/RedPlayer/open)
![GitHub pull requests](https://img.shields.io/bitbucket/pr/badge/RedPlayer?label=pull%20requests)
![GitHub license](https://img.shields.io/badge/license-LGPL2.1-blue)
Platform | Build Status
-------- | ------------
Android | Done
iOS | Done
others | In Coming
### Quickstart/Demo
- Android [Quickstart](source/android/README.md)/ [Demo](source/android/app/README.md)
- IOS [Quickstart](source/ios/README.md)/ [Demo](source/ios/RedPlayerDemo)
- In coming...
### Features
Function | Function Description | Current Support Situation | Other Notes
-------- | -------------------- | ------------------------- | -----------
Rich Format | Supports rich audio and video formats such as FLV, HLS, MP4, MP3, and Vorbis | ✅ |
DASH Protocol | Supports standard protocol DASH | ✅ | Optimized version of DASH for on-demand support in the later stage
HDR | Supports multiple HDR formats such as HDR10/HLG. Distribution and playback support are provided according to the model | ✅ |
URL Playback | Supports playback of local and network videos via URL | ✅ |
Log Reporting | Supports reporting player logs and statistics related to playback point information | ✅ |
Abnormal Analysis | Supports obtaining corresponding abnormal information through log analysis | ✅ |
H.264 Playback & Hardware Decoding | Supports H.264 video sources and hardware decoding | ✅ |
H.265 Playback & Hardware Decoding | Supports H.265 video sources and hardware decoding | ✅ | Software decoding capabilities will be supported in the later stage
Automatic switching between software and hardware decoding | Automatically switches to software decoding when the terminal does not support hardware decoding | ✅ |
Playback Control | Supports playback control functions such as start, end, pause, and resume | ✅ |
Accurate Seeking | Supports accurate seeking to a specified position, which can be accurate to the frame level | ✅ |
Dynamic Dropping | Start dynamic dropping when the frame rate exceeds 60 fps | ✅ |
Replay | Supports manually triggered replay after the video ends | ✅ |
Continue playing | Supports setting the continuous playing time point | ✅ |
Loop Playback | Supports automatic replay after video playback ends | ✅ | Parameter configuration is required
Variable Speed Playback | Supports variable speed playback of 0.5-2 times, and the audio实现variable speed without changing the pitch | ✅ |
Definition Adjustment | Supports switching between multiple definitions for on-demand and transcoding | ✅ |
Seeking within the Cache | Supports seeking without clearing the buffer for cached video content | ✅ |
Packing Mode | Supports picture cropping and filling | ✅ |
Private DRM | Supports private DRM encryption schemes | ✅ |
Adaptive Bitrate | When playing HLS/DASH, it supports automatically selecting the definition for playback through bandwidth prediction | ✅ | Currently only supports selection before playback, and does not support abr during playback
Volume Settings | Supports real-time adjustment of system volume and mute operation | ✅ |
Pure Audio Playback | Supports playing audio only | ✅ |
Preload | Supports setting the preload size to reduce the time spent on the first screen | ✅ |
Play While Downloading | Supports playing while caching and downloading subsequent content, and you can set network policies | ✅ |
Playback Callback | Supports playback status callback, first frame callback, playback completion or failure callback | ✅ |
Retry on Playback Failure | Automatically retries on playback failure | ✅ | Only supports retries for non-4XX and 5XX classes
Real-time Download Speed | Supports getting real-time download speed | ❌ | Will be supported in later versions
Encrypted Streaming PlayBack | Support for on-demand transcoding of encrypted streams | ❌ | Need for custom development
Screenshot Function | Support for capturing any frame of the playback picture | ❌ | Will be supported in later versions
Thumbnail Preview | Support for previewing progress bar thumbnails (sprite map) | ❌ | Related to business, not currently supported
Set player size | Support for customizing the width and height of the player | ❌ | Will be supported in later versions
External subtitles | Support for two docking modes of external subtitles: full-link solution and pure client solution | ❌ | Will be supported in later versions
Client super-resolution | The client performs super-resolution enhancement on low-quality videos | ❌ | Will be supported in later versions
H.266 playback | Support for video playback in H.266 encoding format | ❌ | Will be supported in later versions
AV1 playback | Support for video playback in AV1 encoding format | ❌ | Will be supported in later versions
### Open Content
- [CONTENTS.md](CONTENTS.md)
### Usage
- You can directly integrate your project by calling the interface or compile independently.
- [INTERFACES.md](INTERFACES.md)
### Build Environment
- **Install Homebrew & Git**
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install git
```
- **Build Android**
**Using Android SDK**
[Andrioid SDK](https://developer.android.com/studio?hl=en) is android project base dependency. You should download and then config with the following command:
```bash
# add this line to your ~/.bash_profile or ~/.profile, the android sdk will work
export ANDROID_SDK=<your sdk path>
# My build environment:
# macOS 14.0
# Android Studio Flamingo | 2022.2.1 Patch 2
# gradle version: 7.5.0
```
- **Build iOS**
**Using CocoaPods**
[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:
```bash
$ gem install cocoapods
# My build environment:
# macOS 14.0
# Xcode 15.2 (15C500b)
# Cocoapods version: 1.10.2
# Ruby 3.0.6p216
```
### Latest Changes
- [NEWS.md](NEWS.md)
### Support
- Please try to discuss technical issues (https://github.com/RTE-Dev/RedPlayer/issues) publicly on github, and do not inquire privately by email. We will not reply one by one.
### Licence
#### Self Licence
```
Copyright (c) 2024 xiaohongshu
Licensed under LGPLv2.1 or later
```
#### Dependence Licence
- ffmpeg: LGPL v2.1+
- soundtouch: LGPL v2.1
- libcurl: MIT License
- c-ares: MIT License
- glide: MIT License
- Masonry: MIT License
- openssl: Apache License 2.0
- PictureSelector: Apache License 2.0
### Law And Rule
All rights and explanations belong to Xiaohongshuyou should always ask your lawyer for these stuffs before use it in your product.

BIN
redplayer.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 376 KiB

19
source/android/.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
*.iml
.gradle
/.idea/
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
/OpenRedPlayerCore/.idea/
/app/release

378
source/android/API.md Normal file
View File

@ -0,0 +1,378 @@
# API v1.0.0
### 1. Introduction
This API documentation includes two parts: the first part is the API interface documentation of the RedPlayer SDK, and the second part is the API interface documentation of RedPreload SDK.
## 2. RedPlayer API
### 2.1 setOnPreparedListener
- **API Description:** set the mediaplayer prepared listener
#### 2.1.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |OnPreparedListener |listen the mediaplayer prepared state
### 2.2 setOnCompletionListener
- **API Description:** set the mediaplayer play complete listener
#### 2.2.1 input params
Name |Type |Description
|:---- |:--- |:------
listener |OnCompletionListener |listen the mediaplayer play complete event
### 2.3 setOnBufferingUpdateListener
- **API Description:** set the mediaplayer buffering updating listener
#### 2.3.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |OnBufferingUpdateListener |listen the mediaplayer buffering updating event
### 2.4 setOnSeekCompleteListener
- **API Description:** set the mediaplayer seek complete listener
#### 2.4.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |OnSeekCompleteListener |listen the mediaplayer seek complete event
### 2.5 setOnVideoSizeChangedListener
- **API Description:** set the video size changed listener
#### 2.5.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |OnVideoSizeChangedListener |listen the video size change event
### 2.6 setOnErrorListener
- **API Description:** set the mediaplayer error listener
#### 2.6.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |OnErrorListener |listen the mediaplayer error state
### 2.7 setOnInfoListener
- **API Description:** set the mediaplayer info listener
#### 2.7.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |OnInfoListener |listen the mediaplayer info event
#### 2.7.2 output result
Name |Type |Description
|:---- |:--- |:------
what |Integer |event type
args |Bundle |event extra info
### 2.8 setLooping
- **API Description:** set the mediaplayer play loop
#### 2.8.1 input params
Name |Type |Description
|:---- |:--- |:---
looping |Boolean | media player loop play
### 2.9 setSpeed
- **API Description:** set the mediaplayer play speed
#### 2.9.1 input params
Name |Type |Description
|:---- |:--- |:---
speed |Float | media player play speed [0.75,1.0,1.25,1.5,2.0]
### 2.10 setSurface
- **API Description:** set the mediaplayer render surface
#### 2.10.1 input params
Name |Type |Description
|:---- |:--- |:---
surface |Surface | media player render surface
### 2.11 setDisplay
- **API Description:** set the mediaplayer render surface holder
#### 2.11.1 input params
Name |Type |Description
|:---- |:--- |:---
surfaceHolder |SurfaceHolder | media player render surface holder
### 2.12 setEnableMediaCodec
- **API Description:** set the mediaplayer render surface holder
#### 2.12.1 input params
Name |Type |Description
|:---- |:--- |:---
enable |Boolean | media player use media codec
### 2.13 setVideoCacheDir
- **API Description:** set the mediaplayer stream download path
#### 2.13.1 input params
Name |Type |Description
|:---- |:--- |:---
path |String | media player stream download path
### 2.14 setDataSource
- **API Description:** set the mediaplayer data source
#### 2.14.1 input params
Name |Type |Description
|:---- |:--- |:---
json |String | media player play json
path |String | media player play url
header |Map<String, String> | media player play url's header
#### 2.14.2 json style demo
[json demo](JSON.md)
### 2.15 setVolume
- **API Description:** set the mediaplayer left/right volume
#### 2.15.1 input params
Name |Type |Description
|:---- |:--- |:---
leftVolume |Float | media player left volume
rightVolume |Float | media player right volume
### 2.16 prepareAsync
- **API Description:** preapre the mediaplayer in async
### 2.17 start
- **API Description:** start the mediaplayer
### 2.18 pause
- **API Description:** pause the mediaplayer
### 2.19 stop
- **API Description:** stop the mediaplayer
### 2.20 reset
- **API Description:** reset the mediaplayer
### 2.21 release
- **API Description:** release the mediaplayer
### 2.22 seekTo
- **API Description:** set the mediaplayer left/right volume
#### 2.22.1 input params
Name |Type |Description
|:---- |:--- |:---
position |Long | seek the position to play
### 2.23 getAudioCodecInfo
- **API Description:** get the mediaplayer audio codec info
#### 2.23.1 output result
Type |Description
|:--- |:------
|String |the audio codec name
### 2.24 getVideoCodecInfo
- **API Description:** get the mediaplayer video codec info
#### 2.24.1 output result
Type |Description
|:--- |:------
|String | the video codec name
### 2.25 getVideoWidth
- **API Description:** get the video width info
#### 2.25.1 output result
Type |Description
|:--- |:------
|Integer | the video width
### 2.26 getVideoHeight
- **API Description:** get the video height info
#### 2.26.1 output result
Type |Description
|:--- |:------
|Integer | the video height
### 2.27 getCurrentPosition
- **API Description:** get the mediaplayer current play position
#### 2.27.1 output result
Type |Description
|:--- |:------
|Long | the mediaplayer play current position
### 2.28 getDuration
- **API Description:** get the video duration info
#### 2.28.1 output result
Type |Description
|:--- |:------
|Long | the video duration
### 2.29 getSpeed
- **API Description:** get the mediaplayer play speed
#### 2.29.1 output result
Type |Description
|:--- |:------
|Float | the mediaplayer play speed
### 2.30 getPlayUrl
- **API Description:** get the mediaplayer final play url
#### 2.30.1 output result
Type |Description
|:--- |:------
|String | the mediaplayer final play url
### 2.31 getVideoFileFps
- **API Description:** get the video fps
#### 2.31.1 output result
Type |Description
|:--- |:------
|Float | the mediaplayer final play url
### 2.32 getBitRate
- **API Description:** get the video bit rate
#### 2.32.1 output result
Type |Description
|:--- |:------
|Long | the video bit rate
### 2.33 getSeekCostTimeMs
- **API Description:** get the mediaplayer seek time cost
#### 2.33.1 output result
Type |Description
|:--- |:------
|Long | the mediaplayer seek time cost
### 2.34 isPlaying
- **API Description:** get the mediaplayer is in playing state
#### 2.34.1 output result
Type |Description
|:--- |:------
|Boolean | the mediaplayer is in playing state
## 3. RedPreload API
### 3.1 addPreloadCacheListener
- **API Description:** add the media preload state listener
#### 3.1.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |PreloadCacheListener |the media preload state listener
### 3.2 removePreloadCacheListener
- **API Description:** remove the media preload state listener
#### 3.2.1 input params
Name |Type |Description
|:---- |:--- |:---
listener |PreloadCacheListener |the media preload state listener
### 3.3 start
- **API Description:** start the media preload tasks
#### 3.3.1 input params
Name |Type |Description
|:---- |:--- |:---
requests |List<VideoCacheRequest> |the preload all tasks
### 3.4 stop
- **API Description:** stop all media preload tasks
### 3.5 release
- **API Description:** stop all media preload tasks and release preload inner resource
### 3.6 getAllCacheFilePaths
- **API Description:** get the special dir's all preload files
#### 3.6.1 input params
Name |Type |Description
|:---- |:--- |:---
cacheDir |String |the special cache dir
#### 3.6.2 output result
Type |Description
|:--- |:------
|Array<String> | all files in the special cache dir
### 3.7 deleteCacheFile
- **API Description:** delete the special dir's preload file
#### 3.7.1 input params
Name |Type |Description
|:---- |:--- |:---
cacheDir |String |the special cache dir
url |String |the perload task's url
#### 3.7.2 output result
Type |Description
|:--- |:------
|Int | 0: delete success; != 0: error code
### 3.8 getCacheFileRealSize
- **API Description:** get the special preload file real download size
#### 3.8.1 input params
Name |Type |Description
|:---- |:--- |:---
cacheDir |String |the special cache dir
url |String |the perload task's url
#### 3.8.2 output result
Type |Description
|:--- |:------
|Long | the preload file real download size

View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,71 @@
plugins {
id 'com.android.library'
id 'maven-publish'
}
android {
compileSdk 34
defaultConfig {
minSdk 21
targetSdk 28
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
ndk {
abiFilters "arm64-v8a", "armeabi-v7a"
}
}
sourceSets {
main {
jniLibs.srcDirs = ["libs"]
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
composeOptions {
kotlinCompilerExtensionVersion '1.3.2'
}
publishing {
singleVariant('release') {
withSourcesJar()
withJavadocJar()
}
}
}
dependencies {
implementation platform('org.jetbrains.kotlin:kotlin-bom:1.8.0')
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
afterEvaluate {
publishing {
publications {
release(MavenPublication) {
from components.getByName('release')
groupId = project.properties.groupId
artifactId = 'redplayer'
version = project.properties.version
}
}
}
}

View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,26 @@
package com.xingin.openredplayercore;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.xingin.openredplayercore.test", appContext.getPackageName());
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xingin.openredplayercore">
</manifest>

View File

@ -0,0 +1,297 @@
package com.xingin.openredplayercore.core.api;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.Surface;
import android.view.SurfaceHolder;
import java.io.IOException;
import java.util.Map;
import com.xingin.openredplayercore.core.impl.RedPlayerEvent;
/**
* MediaPlayer Core API
*/
public interface IMediaPlayer {
int MEDIA_INFO_UNKNOWN = 1;
int MEDIA_INFO_STARTED_AS_NEXT = 2;
int MEDIA_INFO_VIDEO_RENDERING_START = 3;
int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
int MEDIA_INFO_BUFFERING_START = 701;
int MEDIA_INFO_BUFFERING_END = 702;
int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
int MEDIA_INFO_BAD_INTERLEAVING = 800;
int MEDIA_INFO_NOT_SEEKABLE = 801;
int MEDIA_INFO_METADATA_UPDATE = 802;
int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
int MEDIA_INFO_VIDEO_ROTATION_CHANGED = 10001;
int MEDIA_INFO_AUDIO_RENDERING_START = 10002;
int MEDIA_INFO_AUDIO_DECODED_START = 10003;
int MEDIA_INFO_VIDEO_DECODED_START = 10004;
int MEDIA_INFO_OPEN_INPUT = 10005;
int MEDIA_INFO_FIND_STREAM_INFO = 10006;
int MEDIA_INFO_COMPONENT_OPEN = 10007;
int MEDIA_INFO_VIDEO_SEEK_RENDERING_START = 10008;
int MEDIA_INFO_AUDIO_SEEK_RENDERING_START = 10009;
int MEDIA_INFO_VIDEO_FIRST_PACKET_IN_DECODER = 10010;
int MEDIA_INFO_VIDEO_START_ON_PLAYING = 10011;
int MEDIA_INFO_URL_CHANGE = 10014;
int MEDIA_INFO_MEDIA_ACCURATE_SEEK_COMPLETE = 10100;
int MEDIA_INFO_MEDIA_SEEK_LOOP_COMPLETE = 10101;
int MEDIA_INFO_MEDIA_SEEK_REQ_COMPLETE = 10102;
int MEDIA_ERROR_UNKNOWN = 1;
int MEDIA_ERROR_SERVER_DIED = 100;
int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
int MEDIA_ERROR_IO = -1004;
int MEDIA_ERROR_MALFORMED = -1007;
int MEDIA_ERROR_UNSUPPORTED = -1010;
int MEDIA_ERROR_TIMED_OUT = -110;
int LOG_UNKNOWN = 0;
int LOG_DEFAULT = 1;
int LOG_VERBOSE = 2;
int LOG_DEBUG = 3;
int LOG_INFO = 4;
int LOG_WARN = 5;
int LOG_ERROR = 6;
int LOG_FATAL = 7;
int LOG_SILENT = 8;
int DECODER_UNKNOWN = 0;
int DECODER_AVCODEC = 1;
int DECODER_MEDIACODEC = 2;
// core type
int MEDIA_PLAYER_ANDROID = 0;
int MEDIA_PLAYER_RED = 1;
void setOnPreparedListener(OnPreparedListener listener);
void setOnCompletionListener(OnCompletionListener listener);
void setOnBufferingUpdateListener(OnBufferingUpdateListener listener);
void setOnSeekCompleteListener(OnSeekCompleteListener listener);
void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener);
void setOnErrorListener(OnErrorListener listener);
void setOnInfoListener(OnInfoListener listener);
void setLooping(boolean looping);
void setSpeed(float speed);
void setSurface(Surface surface);
void setDisplay(SurfaceHolder sh);
/**
* enable or disable hardware decoders
*/
void setEnableMediaCodec(boolean enable);
/**
* Set video cache path: storage location for streaming and downloading videos
*/
void setVideoCacheDir(String dir);
void setDataSource(Context context, Uri uri) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
void setDataSource(String path) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
void setDataSource(String path, Map<String, String> headers) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
/**
* set up JSON multi-bitrate data source
*/
void setDataSourceJson(Context context, String jsonStr) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
void setVolume(float leftVolume, float rightVolume);
void setScreenOnWhilePlaying(boolean screenOn);
void setCallbackLogLevel(int level);
void prepareAsync() throws IllegalStateException;
void start() throws IllegalStateException;
void pause() throws IllegalStateException;
void seekTo(long msec) throws IllegalStateException;
void stop() throws IllegalStateException;
void release();
void reset();
/**
* read dns: This method can be used for DNS preheating to speed up the playback start time.
*/
int readDns(String path, String referer);
/**
* get audio codec information
*/
String getAudioCodecInfo();
/**
* get video codec information
*/
String getVideoCodecInfo();
int getVideoWidth();
int getVideoHeight();
/**
* get current playback position
*/
long getCurrentPosition();
/**
* get total duration of media file
*/
long getDuration();
float getSpeed(float speed);
/**
* get the final playback URL
*/
String getPlayUrl() throws IllegalStateException;
int getVideoSarNum();
int getVideoSarDen();
int getVideoDecoder();
/**
* get video file frame rate
*/
float getVideoFileFps();
/**
* get video output frame rate
*/
float getVideoOutputFramesPerSecond();
/**
* get video decoding frame rate
*/
float getVideoDecodeFramesPerSecond();
/**
* et video cached duration
*/
long getVideoCachedSizeMs();
/**
* get audio cached duration
*/
long getAudioCachedSizeMs();
/**
* get video cached byte count
*/
long getVideoCachedSizeBytes();
/**
* get audio cached byte count
*/
long getAudioCachedSizeBytes();
/**
* get video cached packet count
*/
long getVideoCachedSizePackets();
/**
* get audio cached packet count
*/
long getAudioCachedSizePackets();
long getTrafficStatisticByteCount();
long getRealCacheBytes();
/**
* get video file size
*/
long getFileSize();
/**
* get video bit rate
*/
long getBitRate();
/**
* get seek time cost
*/
long getSeekCostTimeMs();
/**
* get frame drop rate
*/
float getDropFrameRate();
/**
* get frame drop rate before decoding
*/
float getDropPacketRateBeforeDecode();
int getPlayerState();
String getDataSource();
int getPlayerCoreType();
boolean isPlaying();
boolean isLooping();
interface OnPreparedListener {
void onPrepared(IMediaPlayer mp, RedPlayerEvent event);
}
interface OnCompletionListener {
void onCompletion(IMediaPlayer mp);
}
interface OnBufferingUpdateListener {
void onBufferingUpdate(IMediaPlayer mp, int percent);
}
interface OnSeekCompleteListener {
void onSeekComplete(IMediaPlayer mp);
}
interface OnStartOrPauseListener {
void onVideoStartOrPause(IMediaPlayer mp, boolean isPlaying, String url);
}
interface OnVideoSizeChangedListener {
void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sar_num, int sar_den);
}
interface OnErrorListener {
boolean onError(IMediaPlayer mp, int what, int extra);
}
interface OnInfoListener {
boolean onInfo(IMediaPlayer mp, int what, int extra, RedPlayerEvent event);
}
}

View File

@ -0,0 +1,99 @@
package com.xingin.openredplayercore.core.impl;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
public abstract class AbstractMediaPlayer implements IMediaPlayer {
private IMediaPlayer.OnPreparedListener mOnPreparedListener;
private IMediaPlayer.OnCompletionListener mOnCompletionListener;
private IMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener;
private IMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener;
private IMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener;
private IMediaPlayer.OnErrorListener mOnErrorListener;
private IMediaPlayer.OnInfoListener mOnInfoListener;
public AbstractMediaPlayer() {
}
@Override
public final void setOnPreparedListener(IMediaPlayer.OnPreparedListener listener) {
this.mOnPreparedListener = listener;
}
@Override
public final void setOnCompletionListener(IMediaPlayer.OnCompletionListener listener) {
this.mOnCompletionListener = listener;
}
@Override
public final void setOnBufferingUpdateListener(IMediaPlayer.OnBufferingUpdateListener listener) {
this.mOnBufferingUpdateListener = listener;
}
@Override
public final void setOnSeekCompleteListener(IMediaPlayer.OnSeekCompleteListener listener) {
this.mOnSeekCompleteListener = listener;
}
@Override
public final void setOnVideoSizeChangedListener(IMediaPlayer.OnVideoSizeChangedListener listener) {
this.mOnVideoSizeChangedListener = listener;
}
@Override
public final void setOnErrorListener(IMediaPlayer.OnErrorListener listener) {
this.mOnErrorListener = listener;
}
@Override
public final void setOnInfoListener(IMediaPlayer.OnInfoListener listener) {
this.mOnInfoListener = listener;
}
public void resetListeners() {
this.mOnPreparedListener = null;
this.mOnBufferingUpdateListener = null;
this.mOnCompletionListener = null;
this.mOnSeekCompleteListener = null;
this.mOnVideoSizeChangedListener = null;
this.mOnErrorListener = null;
this.mOnInfoListener = null;
}
protected final void notifyOnPrepared(RedPlayerEvent event) {
if (this.mOnPreparedListener != null) {
this.mOnPreparedListener.onPrepared(this, event);
}
}
protected final void notifyOnCompletion() {
if (this.mOnCompletionListener != null) {
this.mOnCompletionListener.onCompletion(this);
}
}
protected void notifyOnBufferingUpdate(int percent) {
if (this.mOnBufferingUpdateListener != null) {
this.mOnBufferingUpdateListener.onBufferingUpdate(this, percent);
}
}
protected void notifyOnSeekComplete() {
if (this.mOnSeekCompleteListener != null) {
this.mOnSeekCompleteListener.onSeekComplete(this);
}
}
protected void notifyOnVideoSizeChanged(int width, int height, int sarNum, int sarDen) {
if (this.mOnVideoSizeChangedListener != null) {
this.mOnVideoSizeChangedListener.onVideoSizeChanged(this, width, height, sarNum, sarDen);
}
}
protected boolean notifyOnError(int what, int extra) {
return this.mOnErrorListener != null && this.mOnErrorListener.onError(this, what, extra);
}
protected boolean notifyOnInfo(int what, int extra, RedPlayerEvent obj) {
return mOnInfoListener != null && mOnInfoListener.onInfo(this, what, extra, obj);
}
}

View File

@ -0,0 +1,8 @@
package com.xingin.openredplayercore.core.impl;
public class RedPlayerEvent {
public Object obj;
public long time;
public long tcpCount;
public long mseekPos;
}

View File

@ -0,0 +1,453 @@
package com.xingin.openredplayercore.core.impl.android;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaDataSource;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.xingin.openredplayercore.core.impl.RedPlayerEvent;
import com.xingin.openredplayercore.core.impl.AbstractMediaPlayer;
import com.xingin.openredplayercore.core.impl.android.util.DebugLog;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;
public class AndroidMediaPlayer extends AbstractMediaPlayer {
private final MediaPlayer mInternalMediaPlayer;
private final AndroidMediaPlayerListenerHolder mInternalListenerAdapter;
private String mDataSource;
private MediaDataSource mMediaDataSource;
private final Object mInitLock = new Object();
private boolean mIsReleased;
public AndroidMediaPlayer() {
synchronized (mInitLock) {
mInternalMediaPlayer = new MediaPlayer();
}
mInternalMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mInternalListenerAdapter = new AndroidMediaPlayerListenerHolder(this);
attachInternalListeners();
}
public MediaPlayer getInternalMediaPlayer() {
return mInternalMediaPlayer;
}
@Override
public void setDisplay(SurfaceHolder sh) {
synchronized (mInitLock) {
if (!mIsReleased) {
mInternalMediaPlayer.setDisplay(sh);
}
}
}
@Override
public void setSurface(Surface surface) {
mInternalMediaPlayer.setSurface(surface);
}
@Override
public void setDataSource(Context context, Uri uri)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
mInternalMediaPlayer.setDataSource(context, uri);
}
@Override
public void setDataSource(Context context, Uri uri, Map<String, String> headers)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
mInternalMediaPlayer.setDataSource(context, uri, headers);
}
@Override
public void setDataSource(String path) throws IOException,
IllegalArgumentException, SecurityException, IllegalStateException {
mDataSource = path;
Uri uri = Uri.parse(path);
String scheme = uri.getScheme();
if (!TextUtils.isEmpty(scheme) && scheme.equalsIgnoreCase("file")) {
mInternalMediaPlayer.setDataSource(uri.getPath());
} else {
mInternalMediaPlayer.setDataSource(path);
}
}
@Override
public void setDataSource(String path, Map<String, String> headers) throws IllegalArgumentException, SecurityException, IllegalStateException {
}
@Override
public void setDataSourceJson(Context context, String jsonStr)
throws IllegalArgumentException, SecurityException, IllegalStateException {
}
@Override
public String getDataSource() {
return mDataSource;
}
private void releaseMediaDataSource() {
if (mMediaDataSource != null) {
try {
mMediaDataSource.close();
} catch (IOException e) {
e.printStackTrace();
}
mMediaDataSource = null;
}
}
@Override
public void prepareAsync() throws IllegalStateException {
mInternalMediaPlayer.prepareAsync();
}
@Override
public void start() throws IllegalStateException {
mInternalMediaPlayer.start();
}
@Override
public void stop() throws IllegalStateException {
mInternalMediaPlayer.stop();
}
@Override
public void pause() throws IllegalStateException {
mInternalMediaPlayer.pause();
}
@Override
public void setScreenOnWhilePlaying(boolean screenOn) {
mInternalMediaPlayer.setScreenOnWhilePlaying(screenOn);
}
@Override
public void setEnableMediaCodec(boolean enable) {
}
@Override
public void setVideoCacheDir(String dir) {
}
@Override
public String getAudioCodecInfo() {
return "unknown";
}
@Override
public String getVideoCodecInfo() {
return "unknown";
}
@Override
public float getVideoFileFps() {
return 0.0f;
}
@Override
public int getVideoWidth() {
return mInternalMediaPlayer.getVideoWidth();
}
@Override
public int getVideoHeight() {
return mInternalMediaPlayer.getVideoHeight();
}
@Override
public int getVideoSarNum() {
return 1;
}
@Override
public int getVideoSarDen() {
return 1;
}
@Override
public boolean isPlaying() {
try {
return mInternalMediaPlayer.isPlaying();
} catch (IllegalStateException e) {
DebugLog.printStackTrace(e);
return false;
}
}
@Override
public void seekTo(long msec) throws IllegalStateException {
mInternalMediaPlayer.seekTo((int) msec);
}
@Override
public long getCurrentPosition() {
try {
return mInternalMediaPlayer.getCurrentPosition();
} catch (IllegalStateException e) {
DebugLog.printStackTrace(e);
return 0;
}
}
@Override
public long getDuration() {
try {
return mInternalMediaPlayer.getDuration();
} catch (IllegalStateException e) {
DebugLog.printStackTrace(e);
return 0;
}
}
@Override
public void release() {
mIsReleased = true;
mInternalMediaPlayer.release();
releaseMediaDataSource();
resetListeners();
attachInternalListeners();
}
@Override
public void reset() {
try {
mInternalMediaPlayer.reset();
} catch (IllegalStateException e) {
DebugLog.printStackTrace(e);
}
releaseMediaDataSource();
resetListeners();
attachInternalListeners();
}
@Override
public void setLooping(boolean looping) {
mInternalMediaPlayer.setLooping(looping);
}
@Override
public boolean isLooping() {
return mInternalMediaPlayer.isLooping();
}
@Override
public void setVolume(float leftVolume, float rightVolume) {
mInternalMediaPlayer.setVolume(leftVolume, rightVolume);
}
@Override
public String getPlayUrl() throws IllegalStateException {
return null;
}
private void attachInternalListeners() {
mInternalMediaPlayer.setOnPreparedListener(mInternalListenerAdapter);
mInternalMediaPlayer
.setOnBufferingUpdateListener(mInternalListenerAdapter);
mInternalMediaPlayer.setOnCompletionListener(mInternalListenerAdapter);
mInternalMediaPlayer
.setOnSeekCompleteListener(mInternalListenerAdapter);
mInternalMediaPlayer
.setOnVideoSizeChangedListener(mInternalListenerAdapter);
mInternalMediaPlayer.setOnErrorListener(mInternalListenerAdapter);
mInternalMediaPlayer.setOnInfoListener(mInternalListenerAdapter);
mInternalMediaPlayer.setOnTimedTextListener(mInternalListenerAdapter);
}
private class AndroidMediaPlayerListenerHolder implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
MediaPlayer.OnBufferingUpdateListener,
MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnVideoSizeChangedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener,
MediaPlayer.OnTimedTextListener {
public final WeakReference<AndroidMediaPlayer> mWeakMediaPlayer;
public AndroidMediaPlayerListenerHolder(AndroidMediaPlayer mp) {
mWeakMediaPlayer = new WeakReference<AndroidMediaPlayer>(mp);
}
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
return self != null && notifyOnInfo(what, extra, null);
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
return self != null && notifyOnError(what, extra);
}
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
if (self == null)
return;
notifyOnVideoSizeChanged(width, height, 1, 1);
}
@Override
public void onSeekComplete(MediaPlayer mp) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
if (self == null)
return;
notifyOnSeekComplete();
}
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
if (self == null)
return;
notifyOnBufferingUpdate(percent);
}
@Override
public void onCompletion(MediaPlayer mp) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
if (self == null)
return;
notifyOnCompletion();
}
@Override
public void onPrepared(MediaPlayer mp) {
AndroidMediaPlayer self = mWeakMediaPlayer.get();
if (self == null)
return;
RedPlayerEvent event = new RedPlayerEvent();
event.obj = self;
event.time = System.currentTimeMillis();
notifyOnPrepared(event);
}
@Override
public void onTimedText(MediaPlayer mp, TimedText text) {
}
}
@Override
public void setSpeed(float speed) {
}
@Override
public float getSpeed(float speed) {
return 0.0f;
}
@Override
public int getVideoDecoder() {
return 0;
}
@Override
public float getVideoOutputFramesPerSecond() {
return 0.0f;
}
@Override
public float getVideoDecodeFramesPerSecond() {
return 0.0f;
}
@Override
public long getVideoCachedSizeMs() {
return 0;
}
@Override
public long getAudioCachedSizeMs() {
return 0;
}
@Override
public long getVideoCachedSizeBytes() {
return 0;
}
@Override
public long getAudioCachedSizeBytes() {
return 0;
}
@Override
public long getVideoCachedSizePackets() {
return 0;
}
@Override
public long getAudioCachedSizePackets() {
return 0;
}
@Override
public long getTrafficStatisticByteCount() {
return 0;
}
@Override
public long getRealCacheBytes() {
return 0;
}
@Override
public long getFileSize() {
return 0;
}
@Override
public long getBitRate() {
return 0;
}
@Override
public long getSeekCostTimeMs() {
return 0;
}
@Override
public float getDropFrameRate() {
return 0;
}
@Override
public int getPlayerState() {
return 0;
}
@Override
public float getDropPacketRateBeforeDecode() {
return 0.0f;
}
@Override
public int readDns(String path, String referer) {
return 0;
}
@Override
public void setCallbackLogLevel(int level) {
}
@Override
public int getPlayerCoreType() {
return MEDIA_PLAYER_ANDROID;
}
}

View File

@ -0,0 +1,124 @@
package com.xingin.openredplayercore.core.impl.android.util;
import android.util.Log;
import java.util.Locale;
public class DebugLog {
public static final boolean ENABLE_ERROR = Pragma.ENABLE_VERBOSE;
public static final boolean ENABLE_INFO = Pragma.ENABLE_VERBOSE;
public static final boolean ENABLE_WARN = Pragma.ENABLE_VERBOSE;
public static final boolean ENABLE_DEBUG = Pragma.ENABLE_VERBOSE;
public static final boolean ENABLE_VERBOSE = Pragma.ENABLE_VERBOSE;
public static void e(String tag, String msg) {
if (ENABLE_ERROR) {
Log.e(tag, msg);
}
}
public static void e(String tag, String msg, Throwable tr) {
if (ENABLE_ERROR) {
Log.e(tag, msg, tr);
}
}
public static void efmt(String tag, String fmt, Object... args) {
if (ENABLE_ERROR) {
String msg = String.format(Locale.US, fmt, args);
Log.e(tag, msg);
}
}
public static void i(String tag, String msg) {
if (ENABLE_INFO) {
Log.i(tag, msg);
}
}
public static void i(String tag, String msg, Throwable tr) {
if (ENABLE_INFO) {
Log.i(tag, msg, tr);
}
}
public static void ifmt(String tag, String fmt, Object... args) {
if (ENABLE_INFO) {
String msg = String.format(Locale.US, fmt, args);
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (ENABLE_WARN) {
Log.w(tag, msg);
}
}
public static void w(String tag, String msg, Throwable tr) {
if (ENABLE_WARN) {
Log.w(tag, msg, tr);
}
}
public static void wfmt(String tag, String fmt, Object... args) {
if (ENABLE_WARN) {
String msg = String.format(Locale.US, fmt, args);
Log.w(tag, msg);
}
}
public static void d(String tag, String msg) {
if (ENABLE_DEBUG) {
Log.d(tag, msg);
}
}
public static void d(String tag, String msg, Throwable tr) {
if (ENABLE_DEBUG) {
Log.d(tag, msg, tr);
}
}
public static void dfmt(String tag, String fmt, Object... args) {
if (ENABLE_DEBUG) {
String msg = String.format(Locale.US, fmt, args);
Log.d(tag, msg);
}
}
public static void v(String tag, String msg) {
if (ENABLE_VERBOSE) {
Log.v(tag, msg);
}
}
public static void v(String tag, String msg, Throwable tr) {
if (ENABLE_VERBOSE) {
Log.v(tag, msg, tr);
}
}
public static void vfmt(String tag, String fmt, Object... args) {
if (ENABLE_VERBOSE) {
String msg = String.format(Locale.US, fmt, args);
Log.v(tag, msg);
}
}
public static void printStackTrace(Throwable e) {
if (ENABLE_WARN) {
e.printStackTrace();
}
}
public static void printCause(Throwable e) {
if (ENABLE_WARN) {
Throwable cause = e.getCause();
if (cause != null)
e = cause;
printStackTrace(e);
}
}
}

View File

@ -0,0 +1,5 @@
package com.xingin.openredplayercore.core.impl.android.util;
public class Pragma {
public static final boolean ENABLE_VERBOSE = true;
}

View File

@ -0,0 +1,761 @@
package com.xingin.openredplayercore.core.impl.redplayer;
import android.content.ContentResolver;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.xingin.openredplayercore.core.impl.RedPlayerEvent;
import com.xingin.openredplayercore.core.loader.RedPlayerLibLoader;
import com.xingin.openredplayercore.core.loader.RedPlayerSoLoader;
import com.xingin.openredplayercore.core.impl.AbstractMediaPlayer;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* RedPlayer Core
*/
public class RedMediaPlayer extends AbstractMediaPlayer {
private final static String TAG = RedMediaPlayer.class.getName();
private static final int MEDIA_NOP = 0;
private static final int MEDIA_PREPARED = 1;
private static final int MEDIA_PLAYBACK_COMPLETE = 2;
private static final int MEDIA_BUFFERING_UPDATE = 3;
private static final int MEDIA_SEEK_COMPLETE = 4;
private static final int MEDIA_SET_VIDEO_SIZE = 5;
private static final int MEDIA_BPREPARED = 7;
private static final int MEDIA_ERROR = 100;
private static final int MEDIA_INFO = 200;
protected static final int MEDIA_SET_VIDEO_SAR = 10001;
public static final int RED_LOG_UNKNOWN = 0;
public static final int RED_LOG_DEFAULT = 1;
public static final int RED_LOG_VERBOSE = 2;
public static final int RED_LOG_DEBUG = 3;
public static final int RED_LOG_INFO = 4;
public static final int RED_LOG_WARN = 5;
public static final int RED_LOG_ERROR = 6;
public static final int RED_LOG_FATAL = 7;
public static final int RED_LOG_SILENT = 8;
public static final int DECODER_UNKNOWN = 0;
public static final int DECODER_AVCODEC = 1;
public static final int DECODER_MEDIACODEC = 2;
public static final int DECODER_VIDEOTOOLBOX = 3;
private static int gLogCallBackLevel = RED_LOG_VERBOSE;
private static NativeLogCallback mNativeLogListener;
private static AtomicInteger mAtomicInteger = new AtomicInteger(0);
private int mID;
private int mVideoWidth;
private int mVideoHeight;
private int mVideoSarNum;
private int mVideoSarDen;
private String mDataSource;
private String mUrlList;
private int mUrlListHttpCode;
private SurfaceHolder mSurfaceHolder;
private EventHandler mEventHandler;
private PowerManager.WakeLock mWakeLock = null;
private boolean mScreenOnWhilePlaying;
private boolean mStayAwake;
private long mDuration;
/**
* Default library loader
* Load them by yourself, if your libraries are not installed at default place.
*/
private static final RedPlayerLibLoader sLocalLibLoader = RedPlayerSoLoader.sLocalLibLoader;
/**
* @param context Android Context
* @param libLoader RedLibLoader
*/
public static void loadLibrariesOnce(Context context, RedPlayerLibLoader libLoader) {
RedPlayerSoLoader.loadRedLibsOnce(context, libLoader, "red_player");
}
public static boolean setHaveLoadLibraries(boolean load) {
return RedPlayerSoLoader.setHaveLoadLibraries(load);
}
private static volatile boolean mIsNativeInitialized = false;
private static void initNativeOnce() {
synchronized (RedMediaPlayer.class) {
if (!mIsNativeInitialized) {
native_init();
mIsNativeInitialized = true;
}
}
}
private static native final void native_init();
/**
* Default constructor. Consider using one of the create() methods for
* synchronously instantiating a RedPlayerCore from a Uri or resource.
* <p>
* When done with the RedPlayerCore, you should call {@link #release()}, to
* free the resources. If not released, too many RedPlayerCore instances
* may result in an exception.
* </p>
*/
public RedMediaPlayer() {
this(null, sLocalLibLoader);
}
public RedMediaPlayer(Context context) {
this(context, sLocalLibLoader);
}
/**
* do not loadLibaray
*
* @param libLoader custom library loader, can be null.
*/
public RedMediaPlayer(Context context, RedPlayerLibLoader libLoader) {
initPlayer(context, libLoader);
}
private void initPlayer(Context context, RedPlayerLibLoader libLoader) {
loadLibrariesOnce(context, libLoader);
initNativeOnce();
mID = mAtomicInteger.addAndGet(1);
mDuration = 0L;
Looper looper;
if ((looper = Looper.myLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else if ((looper = Looper.getMainLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else {
mEventHandler = null;
}
native_setup(new WeakReference<RedMediaPlayer>(this));
}
private native void native_setup(Object redplayerThis);
@Override
public void setDisplay(SurfaceHolder sh) throws IllegalStateException {
log(Log.INFO, id() + "setDisplay: " + sh);
mSurfaceHolder = sh;
Surface surface;
if (sh != null) {
surface = sh.getSurface();
} else {
surface = null;
}
_setVideoSurface(surface);
}
private native void _setVideoSurface(Surface surface) throws IllegalStateException;
@Override
public void setDataSource(Context context, Uri uri) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
setDataSource(context, uri, null);
}
@Override
public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
final String scheme = uri.getScheme();
if (ContentResolver.SCHEME_FILE.equals(scheme)) {
setDataSource(uri.getPath());
return;
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)
&& Settings.AUTHORITY.equals(uri.getAuthority())) {
// Redirect ringtones to go directly to underlying provider
uri = RingtoneManager.getActualDefaultRingtoneUri(context,
RingtoneManager.getDefaultType(uri));
if (uri == null) {
throw new FileNotFoundException("Failed to resolve default ringtone");
}
}
setDataSource(uri.toString(), headers);
}
@Override
public void setDataSource(String path, Map<String, String> headers)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
if (headers != null && !headers.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : headers.entrySet()) {
sb.append(entry.getKey());
sb.append(":");
String value = entry.getValue();
if (!TextUtils.isEmpty(value))
sb.append(entry.getValue());
sb.append("\r\n");
_setHeaders(sb.toString());
}
}
setDataSource(path);
}
private native void _setHeaders(String headers);
@Override
public void setDataSourceJson(Context context, String jsonStr) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
_setDataSourceJson(jsonStr);
}
@Override
public void setDataSource(String path) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
mDataSource = path;
_setDataSource(path, null, null);
}
private native void _setDataSource(String path, String[] keys, String[] values)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
private native void _setDataSourceJson(String path)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
@Override
public String getDataSource() {
return mDataSource;
}
@Override
public void prepareAsync() throws IllegalStateException {
log(Log.INFO, id() + "prepareAsync");
_prepareAsync();
}
private native void _prepareAsync() throws IllegalStateException;
@Override
public int readDns(String path, String referer) {
return _read_dns(path, referer);
}
private native int _read_dns(String path, String referer);
@Override
public void start() throws IllegalStateException {
log(Log.INFO, id() + "start");
stayAwake(true);
_start();
}
private native void _start() throws IllegalStateException;
@Override
public void stop() throws IllegalStateException {
log(Log.INFO, id() + "stop");
stayAwake(false);
_stop();
}
private native void _stop() throws IllegalStateException;
@Override
public void pause() throws IllegalStateException {
log(Log.INFO, id() + "pause");
stayAwake(false);
_pause();
}
private native void _pause() throws IllegalStateException;
@Override
public void setScreenOnWhilePlaying(boolean screenOn) {
if (mScreenOnWhilePlaying != screenOn) {
if (screenOn && mSurfaceHolder == null) {
Log.w(TAG,
"setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
}
mScreenOnWhilePlaying = screenOn;
updateSurfaceScreenOn();
}
}
private void stayAwake(boolean awake) {
if (mWakeLock != null) {
if (awake && !mWakeLock.isHeld()) {
mWakeLock.acquire();
} else if (!awake && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
mStayAwake = awake;
updateSurfaceScreenOn();
}
private void updateSurfaceScreenOn() {
if (mSurfaceHolder != null) {
mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
}
}
@Override
public void setEnableMediaCodec(boolean enable) {
_setEnableMediaCodec(enable);
}
private native void _setEnableMediaCodec(boolean enable);
@Override
public void setVideoCacheDir(String dir) {
_setVideoCacheDir(dir);
}
private native void _setVideoCacheDir(String dir);
@Override
public String getAudioCodecInfo() {
return _getAudioCodecInfo();
}
private native String _getAudioCodecInfo();
@Override
public String getVideoCodecInfo() {
return _getVideoCodecInfo();
}
private native String _getVideoCodecInfo();
@Override
public float getVideoFileFps() {
return _getVideoFileFps();
}
private native float _getVideoFileFps();
@Override
public int getVideoWidth() {
return mVideoWidth;
}
@Override
public int getVideoHeight() {
return mVideoHeight;
}
@Override
public native boolean isPlaying();
@Override
public void seekTo(long msec) throws IllegalStateException {
log(Log.INFO, id() + "seekTo " + msec + "ms");
_seekTo(msec);
}
private native void _seekTo(long msec) throws IllegalStateException;
@Override
public long getCurrentPosition() {
return _getCurrentPosition();
}
private native long _getCurrentPosition();
@Override
public long getDuration() {
if (mDuration <= 0L) {
mDuration = _getDuration();
}
return mDuration;
}
private native long _getDuration();
@Override
public void release() {
log(Log.INFO, id() + "release");
stayAwake(false);
updateSurfaceScreenOn();
resetListeners();
_release();
}
private native void _release();
@Override
public void reset() {
log(Log.INFO, id() + "reset");
stayAwake(false);
_reset();
mEventHandler.removeCallbacksAndMessages(null);
mVideoWidth = 0;
mVideoHeight = 0;
}
private native void _reset();
@Override
public void setVolume(float leftVolume, float rightVolume) {
_setVolume(leftVolume, rightVolume);
}
private native void _setVolume(float leftVolume, float rightVolume);
@Override
public String getPlayUrl() throws IllegalStateException {
return _getPlayUrl();
}
private native String _getPlayUrl();
@Override
public int getVideoSarNum() {
return mVideoSarNum;
}
@Override
public int getVideoSarDen() {
return mVideoSarDen;
}
@Override
public void setLooping(boolean looping) {
int loopCount = looping ? 0 : 1;
_setLoopCount(loopCount);
}
private native void _setLoopCount(int loopCount);
@Override
public boolean isLooping() {
int loopCount = _getLoopCount();
return loopCount != 1;
}
private native int _getLoopCount();
@Override
public void setSurface(Surface surface) {
log(Log.INFO, id() + "setSurface " + surface);
mSurfaceHolder = null;
_setVideoSurface(surface);
}
@Override
public void setSpeed(float speed) {
_setSpeed(speed);
}
private native void _setSpeed(float speed);
@Override
public float getSpeed(float speed) {
return _getSpeed(0.0f);
}
private native float _getSpeed(float default_value);
@Override
public int getVideoDecoder() {
return _getVideoDecoder(DECODER_UNKNOWN);
}
private native int _getVideoDecoder(int default_value);
@Override
public float getVideoOutputFramesPerSecond() {
return _getVideoOutputFramesPerSecond(0.0f);
}
private native float _getVideoOutputFramesPerSecond(float default_value);
@Override
public float getVideoDecodeFramesPerSecond() {
return _getVideoDecodeFramesPerSecond(0.0f);
}
private native float _getVideoDecodeFramesPerSecond(float default_value);
@Override
public long getVideoCachedSizeMs() {
return _getVideoCachedSizeMs(0);
}
private native long _getVideoCachedSizeMs(long default_value);
@Override
public long getAudioCachedSizeMs() {
return _getAudioCachedSizeMs(0);
}
private native long _getAudioCachedSizeMs(long default_value);
@Override
public long getVideoCachedSizeBytes() {
return _getVideoCachedSizeBytes(0);
}
private native long _getVideoCachedSizeBytes(long default_value);
@Override
public long getAudioCachedSizeBytes() {
return _getAudioCachedSizeBytes(0);
}
private native long _getAudioCachedSizeBytes(long default_value);
@Override
public long getVideoCachedSizePackets() {
return _getVideoCachedSizePackets(0);
}
private native long _getVideoCachedSizePackets(long default_value);
@Override
public long getAudioCachedSizePackets() {
return _getAudioCachedSizePackets(0);
}
private native long _getAudioCachedSizePackets(long default_value);
@Override
public long getTrafficStatisticByteCount() {
return _getTrafficStatisticByteCount(0);
}
private native long _getTrafficStatisticByteCount(long default_value);
@Override
public long getRealCacheBytes() {
return _getRealCacheBytes(0);
}
private native long _getRealCacheBytes(long default_value);
@Override
public long getFileSize() {
return _getFileSize(0);
}
private native long _getFileSize(long default_value);
@Override
public long getBitRate() {
return _getBitRate(0);
}
private native long _getBitRate(long default_value);
@Override
public long getSeekCostTimeMs() {
return _getSeekCostTimeMs(0);
}
private native long _getSeekCostTimeMs(long default_value);
@Override
public float getDropFrameRate() {
return _getDropFrameRate(.0f);
}
private native float _getDropFrameRate(float default_value);
@Override
public float getDropPacketRateBeforeDecode() {
return _getDropPacketRateBeforeDecode(0.0f);
}
private native float _getDropPacketRateBeforeDecode(float default_value);
@Override
public int getPlayerState() {
return _getPlayerState();
}
private native int _getPlayerState();
private String id() {
return String.format("[id @ %04d] ", mID);
}
private static class EventHandler extends Handler {
private final WeakReference<RedMediaPlayer> mWeakPlayer;
public EventHandler(RedMediaPlayer mp, Looper looper) {
super(looper);
mWeakPlayer = new WeakReference<RedMediaPlayer>(mp);
}
@Override
public void handleMessage(Message msg) {
RedMediaPlayer player = mWeakPlayer.get();
if (player == null || player.mID == 0) {
log(Log.WARN, "RedPlayerCore went away with unhandled events");
return;
}
switch (msg.what) {
case MEDIA_PREPARED:
log(Log.INFO, player.id() + "Info: MEDIA_PREPARED");
player.notifyOnPrepared((RedPlayerEvent) msg.obj);
return;
case MEDIA_PLAYBACK_COMPLETE:
player.stayAwake(false);
player.notifyOnCompletion();
return;
case MEDIA_BUFFERING_UPDATE:
return;
case MEDIA_SEEK_COMPLETE: {
player.notifyOnSeekComplete();
RedPlayerEvent event = (RedPlayerEvent) msg.obj;
event.mseekPos = msg.arg1;
player.notifyOnInfo(MEDIA_INFO_MEDIA_SEEK_REQ_COMPLETE, msg.arg2, event);
return;
}
case MEDIA_SET_VIDEO_SIZE:
player.mVideoWidth = msg.arg1;
player.mVideoHeight = msg.arg2;
player.notifyOnVideoSizeChanged(player.mVideoWidth, player.mVideoHeight,
player.mVideoSarNum, player.mVideoSarDen);
return;
case MEDIA_ERROR:
log(Log.ERROR, player.id() + "Error (" + msg.arg1 + "," + msg.arg2 + ")");
player.notifyOnError(msg.arg1, msg.arg2);
if (msg.arg2 >= 0) {
player.notifyOnCompletion();
player.stayAwake(false);
}
return;
case MEDIA_INFO:
switch (msg.arg1) {
case MEDIA_INFO_VIDEO_RENDERING_START:
log(Log.INFO, player.id() + "Info: MEDIA_INFO_VIDEO_RENDERING_START, msg-arg2=" + msg.arg2);
break;
case MEDIA_INFO_URL_CHANGE:
log(Log.INFO, player.id() + "Info: MEDIA_INFO_URL_CHANGE, msg-obj=" + msg.obj + "\n");
RedPlayerEvent playEvent = (RedPlayerEvent) msg.obj;
if (msg.arg2 != -1) { // 区分current_url与next_url
player.mUrlList = (String) playEvent.obj;
player.mUrlListHttpCode = msg.arg2;
return;
} else {
player.mUrlList = player.mUrlList + "," + (String) playEvent.obj;
}
playEvent.obj = player.mUrlList;
player.notifyOnInfo(msg.arg1, player.mUrlListHttpCode, playEvent); // url1,url2
return;
}
player.notifyOnInfo(msg.arg1, msg.arg2, (RedPlayerEvent) msg.obj);
// No real default action so far.
return;
case MEDIA_NOP: // interface test message - ignore
break;
case MEDIA_SET_VIDEO_SAR:
player.mVideoSarNum = msg.arg1;
player.mVideoSarDen = msg.arg2;
player.notifyOnVideoSizeChanged(player.mVideoWidth, player.mVideoHeight,
player.mVideoSarNum, player.mVideoSarDen);
break;
default:
// log(Log.ERROR, player.id() + "Unknown message type " + msg.what);
}
}
}
private static void postEventFromNative(Object weakThiz, long ctime, int what,
int arg1, int arg2, Object obj) {
if (weakThiz == null)
return;
RedMediaPlayer mp = (RedMediaPlayer) ((WeakReference) weakThiz).get();
if (mp == null) {
return;
}
if (mp.mEventHandler != null) {
RedPlayerEvent event = new RedPlayerEvent();
event.obj = obj;
if (ctime > 0)
event.time = ctime;
else
event.time = System.currentTimeMillis();
event.tcpCount = mp.getTrafficStatisticByteCount();
Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, event);
mp.mEventHandler.sendMessage(m);
}
}
private static void onNativeLog(int level, String tag, byte[] logContent) {
if (level < gLogCallBackLevel) {
return;
}
String logContentStr = "";
try {
logContentStr = new String(logContent, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (mNativeLogListener != null) {
mNativeLogListener.onLogOutput(level, tag, logContentStr);
} else {
Log.println(level, tag, logContentStr);
}
}
private static void log(int level, String log) {
if (level < gLogCallBackLevel) {
return;
}
if (mNativeLogListener != null) {
mNativeLogListener.onLogOutput(level, TAG, log);
} else {
Log.println(level, TAG, log);
}
}
public static void setNativeLogCallback(NativeLogCallback nativeLogCallback) {
mNativeLogListener = nativeLogCallback;
}
public interface NativeLogCallback {
void onLogOutput(int logLevel, String tag, String log);
}
@Override
public void setCallbackLogLevel(int level) {
gLogCallBackLevel = level;
synchronized (RedMediaPlayer.class) {
if (mIsNativeInitialized) {
native_setCallbackLogLevel(gLogCallBackLevel);
}
}
}
public static native void native_setCallbackLogLevel(int level);
@Override
public int getPlayerCoreType() {
return MEDIA_PLAYER_RED;
}
}

View File

@ -0,0 +1,8 @@
package com.xingin.openredplayercore.core.loader;
import android.content.Context;
public interface RedPlayerLibLoader {
void loadLibrary(Context context, String libName) throws UnsatisfiedLinkError,
SecurityException;
}

View File

@ -0,0 +1,76 @@
package com.xingin.openredplayercore.core.loader;
import android.content.Context;
public class RedPlayerSoLoader {
private final static String TAG = RedPlayerSoLoader.class.getName();
/**
* Default library loader
* Load them by yourself, if your libraries are not installed at default place.
*/
public static final RedPlayerLibLoader sLocalLibLoader = (context, libName) -> System.loadLibrary(libName);
private static volatile boolean sIsNativeLibsLoaded = false;
/**
* @return soLib has loaded
*/
public static boolean isNativeLibsLoaded() {
synchronized (sLoadSoLibsLock) {
return sIsNativeLibsLoaded;
}
}
public static boolean setHaveLoadLibraries(boolean load) {
synchronized (sLoadSoLibsLock) {
boolean prevLibLoaded = sIsNativeLibsLoaded;
sIsNativeLibsLoaded = load;
return prevLibLoaded;
}
}
private static final Object sLoadSoLibsLock = new Object();
/**
* @param context Android Context
* @param libLoader RedPlayerLibLoader
*/
public static void loadRedLibsOnce(Context context, RedPlayerLibLoader libLoader, String tag) {
synchronized (sLoadSoLibsLock) {
if (!sIsNativeLibsLoaded) {
long curTime = System.currentTimeMillis();
if (libLoader == null)
libLoader = sLocalLibLoader;
libLoader.loadLibrary(context, "c++_shared");
libLoader.loadLibrary(context, "ffmpeg");
libLoader.loadLibrary(context, "redlog");
libLoader.loadLibrary(context, "redbase");
libLoader.loadLibrary(context, "reddownload");
libLoader.loadLibrary(context, "redstrategycenter");
libLoader.loadLibrary(context, "opensource");
libLoader.loadLibrary(context, "openrender");
libLoader.loadLibrary(context, "opendecoder");
libLoader.loadLibrary(context, "soundtouch");
libLoader.loadLibrary(context, "redplayer");
sIsNativeLibsLoaded = true;
if (sSoLoadCallback != null) {
sSoLoadCallback.onFinishSoLoad(tag, System.currentTimeMillis() - curTime);
}
}
}
}
private static SoLoadCallback sSoLoadCallback;
public static void setSoLoadCallback(SoLoadCallback soLoadCallback) {
sSoLoadCallback = soLoadCallback;
}
public interface SoLoadCallback {
/**
* so load success
*/
void onFinishSoLoad(String tag, long cost);
}
}

View File

@ -0,0 +1,71 @@
package com.xingin.openredplayercore.core.renderview;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
public interface IRenderView {
int AR_ASPECT_FIT_PARENT = 0; // without clip
int AR_ASPECT_FILL_PARENT = 1; // may clip
int AR_ASPECT_WRAP_CONTENT = 2;
int AR_MATCH_PARENT = 3;
int AR_16_9_FIT_PARENT = 4;
int AR_4_3_FIT_PARENT = 5;
View getView();
boolean shouldWaitForResize();
void setVideoSize(int videoWidth, int videoHeight);
void setVideoSampleAspectRatio(int videoSarNum, int videoSarDen);
void setVideoRotation(int degree);
void setAspectRatio(int aspectRatio);
void addRenderCallback(@NonNull IRenderCallback callback);
void removeRenderCallback(@NonNull IRenderCallback callback);
interface ISurfaceHolder {
void bindToMediaPlayer(IMediaPlayer mp);
@NonNull
IRenderView getRenderView();
@Nullable
SurfaceHolder getSurfaceHolder();
@Nullable
Surface openSurface();
@Nullable
SurfaceTexture getSurfaceTexture();
}
interface IRenderCallback {
/**
* @param holder
* @param width could be 0
* @param height could be 0
*/
void onSurfaceCreated(@NonNull ISurfaceHolder holder, int width, int height);
/**
* @param holder
* @param format could be 0
* @param width
* @param height
*/
void onSurfaceChanged(@NonNull ISurfaceHolder holder, int format, int width, int height);
void onSurfaceDestroyed(@NonNull ISurfaceHolder holder);
}
}

View File

@ -0,0 +1,7 @@
package com.xingin.openredplayercore.core.renderview;
import android.graphics.SurfaceTexture;
public interface ISurfaceTextureHost {
void releaseSurfaceTexture(SurfaceTexture surfaceTexture);
}

View File

@ -0,0 +1,245 @@
package com.xingin.openredplayercore.core.renderview;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
import com.xingin.openredplayercore.core.renderview.helper.MeasureHelper;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* SurfaceView渲染
*/
public class SurfaceRenderView extends SurfaceView implements IRenderView {
private MeasureHelper mMeasureHelper;
public SurfaceRenderView(Context context) {
super(context);
initView(context);
}
public SurfaceRenderView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public SurfaceRenderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SurfaceRenderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView(context);
}
private void initView(Context context) {
mMeasureHelper = new MeasureHelper(this);
mSurfaceCallback = new SurfaceCallback(this);
getHolder().addCallback(mSurfaceCallback);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
@Override
public View getView() {
return this;
}
@Override
public boolean shouldWaitForResize() {
return true;
}
@Override
public void setVideoSize(int videoWidth, int videoHeight) {
if (videoWidth > 0 && videoHeight > 0) {
mMeasureHelper.setVideoSize(videoWidth, videoHeight);
getHolder().setFixedSize(videoWidth, videoHeight);
requestLayout();
}
}
@Override
public void setVideoSampleAspectRatio(int videoSarNum, int videoSarDen) {
if (videoSarNum > 0 && videoSarDen > 0) {
mMeasureHelper.setVideoSampleAspectRatio(videoSarNum, videoSarDen);
requestLayout();
}
}
@Override
public void setVideoRotation(int degree) {
Log.e("", "SurfaceView doesn't support rotation (" + degree + ")!\n");
}
@Override
public void setAspectRatio(int aspectRatio) {
mMeasureHelper.setAspectRatio(aspectRatio);
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mMeasureHelper.doMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(mMeasureHelper.getMeasuredWidth(), mMeasureHelper.getMeasuredHeight());
}
private static final class InternalSurfaceHolder implements IRenderView.ISurfaceHolder {
private SurfaceRenderView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
public InternalSurfaceHolder(@NonNull SurfaceRenderView surfaceView,
@Nullable SurfaceHolder surfaceHolder) {
mSurfaceView = surfaceView;
mSurfaceHolder = surfaceHolder;
}
public void bindToMediaPlayer(IMediaPlayer mp) {
if (mp != null) {
mp.setDisplay(mSurfaceHolder);
}
}
@NonNull
@Override
public IRenderView getRenderView() {
return mSurfaceView;
}
@Nullable
@Override
public SurfaceHolder getSurfaceHolder() {
return mSurfaceHolder;
}
@Nullable
@Override
public SurfaceTexture getSurfaceTexture() {
return null;
}
@Nullable
@Override
public Surface openSurface() {
if (mSurfaceHolder == null)
return null;
return mSurfaceHolder.getSurface();
}
}
@Override
public void addRenderCallback(IRenderCallback callback) {
mSurfaceCallback.addRenderCallback(callback);
}
@Override
public void removeRenderCallback(IRenderCallback callback) {
mSurfaceCallback.removeRenderCallback(callback);
}
private SurfaceCallback mSurfaceCallback;
private static final class SurfaceCallback implements SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private boolean mIsFormatChanged;
private int mFormat;
private int mWidth;
private int mHeight;
private WeakReference<SurfaceRenderView> mWeakSurfaceView;
private Map<IRenderCallback, Object> mRenderCallbackMap = new ConcurrentHashMap<IRenderCallback, Object>();
public SurfaceCallback(@NonNull SurfaceRenderView surfaceView) {
mWeakSurfaceView = new WeakReference<SurfaceRenderView>(surfaceView);
}
public void addRenderCallback(@NonNull IRenderCallback callback) {
mRenderCallbackMap.put(callback, callback);
ISurfaceHolder surfaceHolder = null;
if (mSurfaceHolder != null) {
if (surfaceHolder == null)
surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder);
callback.onSurfaceCreated(surfaceHolder, mWidth, mHeight);
}
if (mIsFormatChanged) {
if (surfaceHolder == null)
surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder);
callback.onSurfaceChanged(surfaceHolder, mFormat, mWidth, mHeight);
}
}
public void removeRenderCallback(@NonNull IRenderCallback callback) {
mRenderCallbackMap.remove(callback);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
mIsFormatChanged = false;
mFormat = 0;
mWidth = 0;
mHeight = 0;
ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder);
for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) {
renderCallback.onSurfaceCreated(surfaceHolder, 0, 0);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mSurfaceHolder = null;
mIsFormatChanged = false;
mFormat = 0;
mWidth = 0;
mHeight = 0;
ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder);
for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) {
renderCallback.onSurfaceDestroyed(surfaceHolder);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
mSurfaceHolder = holder;
mIsFormatChanged = true;
mFormat = format;
mWidth = width;
mHeight = height;
ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakSurfaceView.get(), mSurfaceHolder);
for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) {
renderCallback.onSurfaceChanged(surfaceHolder, format, width, height);
}
}
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(SurfaceRenderView.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(SurfaceRenderView.class.getName());
}
}

View File

@ -0,0 +1,296 @@
package com.xingin.openredplayercore.core.renderview;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.TextureView;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
import com.xingin.openredplayercore.core.renderview.helper.MeasureHelper;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* TextureView渲染
*/
public class TextureRenderView extends TextureView implements IRenderView {
private static final String TAG = "TextureRenderView";
private MeasureHelper mMeasureHelper;
public TextureRenderView(Context context) {
super(context);
initView(context);
}
public TextureRenderView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public TextureRenderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
public TextureRenderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView(context);
}
private void initView(Context context) {
mMeasureHelper = new MeasureHelper(this);
mSurfaceCallback = new SurfaceCallback(this);
setSurfaceTextureListener(mSurfaceCallback);
}
@Override
public View getView() {
return this;
}
@Override
public boolean shouldWaitForResize() {
return false;
}
@Override
protected void onDetachedFromWindow() {
mSurfaceCallback.willDetachFromWindow();
super.onDetachedFromWindow();
mSurfaceCallback.didDetachFromWindow();
}
@Override
public void setVideoSize(int videoWidth, int videoHeight) {
if (videoWidth > 0 && videoHeight > 0) {
mMeasureHelper.setVideoSize(videoWidth, videoHeight);
requestLayout();
}
}
@Override
public void setVideoSampleAspectRatio(int videoSarNum, int videoSarDen) {
if (videoSarNum > 0 && videoSarDen > 0) {
mMeasureHelper.setVideoSampleAspectRatio(videoSarNum, videoSarDen);
requestLayout();
}
}
@Override
public void setVideoRotation(int degree) {
mMeasureHelper.setVideoRotation(degree);
setRotation(degree);
}
@Override
public void setAspectRatio(int aspectRatio) {
mMeasureHelper.setAspectRatio(aspectRatio);
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mMeasureHelper.doMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(mMeasureHelper.getMeasuredWidth(), mMeasureHelper.getMeasuredHeight());
}
public IRenderView.ISurfaceHolder getSurfaceHolder() {
return new InternalSurfaceHolder(this, mSurfaceCallback.mSurfaceTexture);
}
private static final class InternalSurfaceHolder implements IRenderView.ISurfaceHolder {
private TextureRenderView mTextureView;
private SurfaceTexture mSurfaceTexture;
public InternalSurfaceHolder(@NonNull TextureRenderView textureView, @Nullable SurfaceTexture surfaceTexture) {
mTextureView = textureView;
mSurfaceTexture = surfaceTexture;
}
public void bindToMediaPlayer(IMediaPlayer mp) {
if (mp == null)
return;
mp.setSurface(openSurface());
}
@NonNull
@Override
public IRenderView getRenderView() {
return mTextureView;
}
@Nullable
@Override
public SurfaceHolder getSurfaceHolder() {
return null;
}
@Nullable
@Override
public SurfaceTexture getSurfaceTexture() {
return mSurfaceTexture;
}
@Nullable
@Override
public Surface openSurface() {
if (mSurfaceTexture == null)
return null;
return new Surface(mSurfaceTexture);
}
}
@Override
public void addRenderCallback(IRenderCallback callback) {
mSurfaceCallback.addRenderCallback(callback);
}
@Override
public void removeRenderCallback(IRenderCallback callback) {
mSurfaceCallback.removeRenderCallback(callback);
}
private SurfaceCallback mSurfaceCallback;
private static final class SurfaceCallback implements SurfaceTextureListener, ISurfaceTextureHost {
private SurfaceTexture mSurfaceTexture;
private boolean mIsFormatChanged;
private int mWidth;
private int mHeight;
private boolean mOwnSurfaceTexture = true;
private boolean mWillDetachFromWindow = false;
private boolean mDidDetachFromWindow = false;
private WeakReference<TextureRenderView> mWeakRenderView;
private Map<IRenderCallback, Object> mRenderCallbackMap = new ConcurrentHashMap<IRenderCallback, Object>();
public SurfaceCallback(@NonNull TextureRenderView renderView) {
mWeakRenderView = new WeakReference<TextureRenderView>(renderView);
}
public void setOwnSurfaceTexture(boolean ownSurfaceTexture) {
mOwnSurfaceTexture = ownSurfaceTexture;
}
public void addRenderCallback(@NonNull IRenderCallback callback) {
mRenderCallbackMap.put(callback, callback);
ISurfaceHolder surfaceHolder = null;
if (mSurfaceTexture != null) {
if (surfaceHolder == null)
surfaceHolder = new InternalSurfaceHolder(mWeakRenderView.get(), mSurfaceTexture);
callback.onSurfaceCreated(surfaceHolder, mWidth, mHeight);
}
if (mIsFormatChanged) {
if (surfaceHolder == null)
surfaceHolder = new InternalSurfaceHolder(mWeakRenderView.get(), mSurfaceTexture);
callback.onSurfaceChanged(surfaceHolder, 0, mWidth, mHeight);
}
}
public void removeRenderCallback(@NonNull IRenderCallback callback) {
mRenderCallbackMap.remove(callback);
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mSurfaceTexture = surface;
mIsFormatChanged = false;
mWidth = 0;
mHeight = 0;
ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakRenderView.get(), surface);
for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) {
renderCallback.onSurfaceCreated(surfaceHolder, 0, 0);
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
mSurfaceTexture = surface;
mIsFormatChanged = true;
mWidth = width;
mHeight = height;
ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakRenderView.get(), surface);
for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) {
renderCallback.onSurfaceChanged(surfaceHolder, 0, width, height);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mSurfaceTexture = surface;
mIsFormatChanged = false;
mWidth = 0;
mHeight = 0;
ISurfaceHolder surfaceHolder = new InternalSurfaceHolder(mWeakRenderView.get(), surface);
for (IRenderCallback renderCallback : mRenderCallbackMap.keySet()) {
renderCallback.onSurfaceDestroyed(surfaceHolder);
}
Log.d(TAG, "onSurfaceTextureDestroyed: destroy: " + mOwnSurfaceTexture);
return mOwnSurfaceTexture;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
@Override
public void releaseSurfaceTexture(SurfaceTexture surfaceTexture) {
if (surfaceTexture == null) {
} else if (mDidDetachFromWindow) {
if (surfaceTexture != mSurfaceTexture) {
surfaceTexture.release();
} else if (!mOwnSurfaceTexture) {
surfaceTexture.release();
}
} else if (mWillDetachFromWindow) {
if (surfaceTexture != mSurfaceTexture) {
surfaceTexture.release();
} else if (!mOwnSurfaceTexture) {
setOwnSurfaceTexture(true);
}
} else {
if (surfaceTexture != mSurfaceTexture) {
surfaceTexture.release();
} else if (!mOwnSurfaceTexture) {
setOwnSurfaceTexture(true);
}
}
}
public void willDetachFromWindow() {
mWillDetachFromWindow = true;
}
public void didDetachFromWindow() {
mDidDetachFromWindow = true;
}
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(TextureRenderView.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(TextureRenderView.class.getName());
}
}

View File

@ -0,0 +1,174 @@
package com.xingin.openredplayercore.core.renderview.helper;
import android.view.View;
import com.xingin.openredplayercore.core.renderview.IRenderView;
import java.lang.ref.WeakReference;
/**
* 测量类根据View宽高视频宽高重新计算缩放
*/
public final class MeasureHelper {
private WeakReference<View> mWeakView;
private int mVideoWidth;
private int mVideoHeight;
private int mVideoSarNum;
private int mVideoSarDen;
private int mVideoRotationDegree;
private int mMeasuredWidth;
private int mMeasuredHeight;
private int mCurrentAspectRatio = IRenderView.AR_ASPECT_FIT_PARENT;
public MeasureHelper(View view) {
mWeakView = new WeakReference<View>(view);
}
public View getView() {
if (mWeakView == null)
return null;
return mWeakView.get();
}
public void setVideoSize(int videoWidth, int videoHeight) {
mVideoWidth = videoWidth;
mVideoHeight = videoHeight;
}
public void setVideoSampleAspectRatio(int videoSarNum, int videoSarDen) {
mVideoSarNum = videoSarNum;
mVideoSarDen = videoSarDen;
}
public void setVideoRotation(int videoRotationDegree) {
mVideoRotationDegree = videoRotationDegree;
}
public void doMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270) {
int tempSpec = widthMeasureSpec;
widthMeasureSpec = heightMeasureSpec;
heightMeasureSpec = tempSpec;
}
int width = View.getDefaultSize(mVideoWidth, widthMeasureSpec);
int height = View.getDefaultSize(mVideoHeight, heightMeasureSpec);
if (mCurrentAspectRatio == IRenderView.AR_MATCH_PARENT) {
width = widthMeasureSpec;
height = heightMeasureSpec;
} else if (mVideoWidth > 0 && mVideoHeight > 0) {
int widthSpecMode = View.MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = View.MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = View.MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = View.MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == View.MeasureSpec.AT_MOST && heightSpecMode == View.MeasureSpec.AT_MOST) {
float specAspectRatio = (float) widthSpecSize / (float) heightSpecSize;
float displayAspectRatio;
switch (mCurrentAspectRatio) {
case IRenderView.AR_16_9_FIT_PARENT:
displayAspectRatio = 16.0f / 9.0f;
if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270)
displayAspectRatio = 1.0f / displayAspectRatio;
break;
case IRenderView.AR_4_3_FIT_PARENT:
displayAspectRatio = 4.0f / 3.0f;
if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270)
displayAspectRatio = 1.0f / displayAspectRatio;
break;
case IRenderView.AR_ASPECT_FIT_PARENT:
case IRenderView.AR_ASPECT_FILL_PARENT:
case IRenderView.AR_ASPECT_WRAP_CONTENT:
default:
displayAspectRatio = (float) mVideoWidth / (float) mVideoHeight;
if (mVideoSarNum > 0 && mVideoSarDen > 0)
displayAspectRatio = displayAspectRatio * mVideoSarNum / mVideoSarDen;
break;
}
boolean shouldBeWider = displayAspectRatio > specAspectRatio;
switch (mCurrentAspectRatio) {
case IRenderView.AR_ASPECT_FIT_PARENT:
case IRenderView.AR_16_9_FIT_PARENT:
case IRenderView.AR_4_3_FIT_PARENT:
if (shouldBeWider) {
width = widthSpecSize;
height = (int) (width / displayAspectRatio);
} else {
height = heightSpecSize;
width = (int) (height * displayAspectRatio);
}
break;
case IRenderView.AR_ASPECT_FILL_PARENT:
if (shouldBeWider) {
height = heightSpecSize;
width = (int) (height * displayAspectRatio);
} else {
width = widthSpecSize;
height = (int) (width / displayAspectRatio);
}
break;
case IRenderView.AR_ASPECT_WRAP_CONTENT:
default:
if (shouldBeWider) {
width = Math.min(mVideoWidth, widthSpecSize);
height = (int) (width / displayAspectRatio);
} else {
height = Math.min(mVideoHeight, heightSpecSize);
width = (int) (height * displayAspectRatio);
}
break;
}
} else if (widthSpecMode == View.MeasureSpec.EXACTLY && heightSpecMode == View.MeasureSpec.EXACTLY) {
width = widthSpecSize;
height = heightSpecSize;
if (mVideoWidth * height < width * mVideoHeight) {
width = height * mVideoWidth / mVideoHeight;
} else if (mVideoWidth * height > width * mVideoHeight) {
height = width * mVideoHeight / mVideoWidth;
}
} else if (widthSpecMode == View.MeasureSpec.EXACTLY) {
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
if (heightSpecMode == View.MeasureSpec.AT_MOST && height > heightSpecSize) {
height = heightSpecSize;
}
} else if (heightSpecMode == View.MeasureSpec.EXACTLY) {
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
if (widthSpecMode == View.MeasureSpec.AT_MOST && width > widthSpecSize) {
width = widthSpecSize;
}
} else {
width = mVideoWidth;
height = mVideoHeight;
if (heightSpecMode == View.MeasureSpec.AT_MOST && height > heightSpecSize) {
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
}
if (widthSpecMode == View.MeasureSpec.AT_MOST && width > widthSpecSize) {
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
}
}
}
mMeasuredWidth = width;
mMeasuredHeight = height;
}
public int getMeasuredWidth() {
return mMeasuredWidth;
}
public int getMeasuredHeight() {
return mMeasuredHeight;
}
public void setAspectRatio(int aspectRatio) {
mCurrentAspectRatio = aspectRatio;
}
}

View File

@ -0,0 +1,17 @@
package com.xingin.openredplayercore;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}

View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,66 @@
plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.android'
id 'maven-publish'
}
android {
compileSdk 34
defaultConfig {
minSdk 21
targetSdk 28
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
ndk {
abiFilters "arm64-v8a", "armeabi-v7a"
}
}
sourceSets {
main {
jniLibs.srcDirs = ["libs"]
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
publishing {
singleVariant('release') {
withSourcesJar()
withJavadocJar()
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation "io.reactivex.rxjava3:rxjava:3.1.8"
}
afterEvaluate {
publishing {
publications {
release(MavenPublication) {
from components.getByName('release')
groupId = project.properties.groupId
artifactId = 'redpreload'
version = project.properties.version
}
}
}
}

View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,26 @@
package com.xingin.openredpreload;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.xingin.openredpreload.test", appContext.getPackageName());
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xingin.openredpreload">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

View File

@ -0,0 +1,150 @@
package com.xingin.openredpreload;
import android.os.Bundle;
import androidx.annotation.Nullable;
import java.lang.ref.WeakReference;
public class OpenRedPreload {
private final static String TAG = OpenRedPreload.class.getName();
/**
* preload traffic info(Bundle)
* "bytes": int -- traffic
*/
public static final int PRELOAD_EVENT_IO_TRAFFIC = 0x30001;
public static final int PRELOAD_EVENT_SPEED = 0x30002;
/**
* http事件(Bundle)
* "error": int -- =0no error
* "wan_ip": String -- ip
* "http_rtt": int -- tcp to fist data pacage time
*/
public static final int PRELOAD_EVENT_DID_HTTP_OPEN = 0x30005;
/**
* tcp event(Bundle)
* "error": int -- =0no error
* "dst_ip": String -- ip
* "tcp_rtt": int -- tcp cost
*/
public static final int PRELOAD_EVENT_DID_TCP_OPEN = 0x30006;
/**
* error event(Bundle)
* "error": int -- =0no error
*/
public static final int PRELOAD_EVENT_ERROR = 0x30008;
public interface DownloadEventListener {
void onEvent(int event, @Nullable Bundle param, @Nullable String url, @Nullable Object userData);
}
private String mDataSource;
private String mDataSourceJson;
static {
System.loadLibrary("redbase");
System.loadLibrary("redlog");
System.loadLibrary("reddownload");
System.loadLibrary("redstrategycenter");
System.loadLibrary("redpreload");
}
private static void onEvent(Object obj, int event, String url, Bundle param) {
if (!(obj instanceof PreloadObject)) {
return;
}
WeakReference<DownloadEventListener> weakListener = ((PreloadObject) obj).listener;
if (weakListener == null) {
return;
}
@SuppressWarnings("unchecked")
DownloadEventListener listener = weakListener.get();
if (listener != null) {
listener.onEvent(event, param, url, ((PreloadObject) obj).userData);
}
}
/**
* start preload
*
* @param param: "downloadtype": int
* "capacity": long
* "use_https": int
* "is_json": boolean
* "referer": String
* "user_agent": String
* "header": String
*/
public void open(String url, String cachePath, long downloadSize, @Nullable WeakReference<DownloadEventListener> weakListener, @Nullable Bundle param, @Nullable Object userData) {
if (param != null) {
boolean is_json = param.getBoolean("is_json", false);
if (is_json) {
mDataSourceJson = url;
} else {
mDataSource = url;
}
}
Object obj = new PreloadObject(weakListener, userData);
_open(url, cachePath, downloadSize, obj, param);
}
public void release() {
if (mDataSource != null && mDataSource != "")
_release(mDataSource);
if (mDataSourceJson != null && mDataSourceJson != "")
_release_json(mDataSourceJson);
}
public void stop() {
_stop();
}
public int deleteCache(String cachePath, String uri, boolean is_full_url) {
return _deleteCache(cachePath, uri, is_full_url ? 1 : 0);
}
public String[] getAllCachedFile(String cachePath) {
return _getAllCachedFile(cachePath);
}
public String getCacheFilePath(String cachePath, String url) {
return _getCacheFilePath(cachePath, url);
}
public long getCachedSize(String path, String uri, boolean is_full_url) {
return _getCacheSize(path, uri, is_full_url ? 1 : 0);
}
private native void _open(String url, String cachePath, long downloadSize, Object preloadObj, Bundle param);
private native void _open_json(String jsonstr, String path, long size, Object obj, String referer, boolean use_https);
private native void _release(String url);
private native void _release_json(String jsonstr);
private native void _stop();
private native int _deleteCache(String path, String uri, int is_full_url);
private native String[] _getAllCachedFile(String path);
private native long _getCacheSize(String path, String uri, int is_full_url);
private native String _getCacheFilePath(String path, String url);
}
class PreloadObject {
public WeakReference<OpenRedPreload.DownloadEventListener> listener;
public Object userData;
public PreloadObject(WeakReference<OpenRedPreload.DownloadEventListener> _weakListener, Object _userData) {
this.listener = _weakListener;
this.userData = _userData;
}
}

View File

@ -0,0 +1,35 @@
package com.xingin.openredpreload.api
import com.xingin.openredpreload.impl.model.VideoCacheRequest
/**
* Media Preload API
*/
interface IMediaPreload {
/** add the preload status listener */
fun addPreloadCacheListener(listener: PreloadCacheListener?)
/** remove the preload status listener */
fun removePreloadCacheListener(listener: PreloadCacheListener?)
/** start all preload task */
fun start(requests: List<VideoCacheRequest>?)
/** stop all preload task */
fun stop()
fun release()
/** get the dir's all files */
fun getAllCacheFilePaths(cacheDir: String?): Array<String>?
/** delete the cache dir task: the url is the key of preload task */
fun deleteCacheFile(url: String?, cacheDir: String?): Int?
/** get the file real download size: not the file size */
fun getCacheFileRealSize(url: String?, cacheDir: String?): Long?
/** get the preload url's file absolute path */
fun getCacheFilePath(url: String?, cacheDir: String?): String?
}

View File

@ -0,0 +1,25 @@
package com.xingin.openredpreload.api
import com.xingin.openredpreload.impl.model.VideoCacheRequest
/** Preload Task Callback */
interface PreloadCacheListener {
/**
* @param cacheFilePath file absolute path
* @param cacheFileSize file size, unit: b
* @param request origin preload request
*/
fun onPreloadSuccess(cacheFilePath: String, cacheFileSize: Long, request: VideoCacheRequest) {}
/**
* @param errorMsg preload error msg
* @param request origin preload request
*/
fun onPreloadError(errorMsg: Long, request: VideoCacheRequest) {}
/**
* @param request origin preload request
*/
fun onPreloadStart(request: VideoCacheRequest) {}
}

View File

@ -0,0 +1,201 @@
package com.xingin.openredpreload.impl
import android.os.Bundle
import android.util.Log
import com.xingin.openredpreload.OpenRedPreload
import com.xingin.openredpreload.api.IMediaPreload
import com.xingin.openredpreload.api.PreloadCacheListener
import com.xingin.openredpreload.impl.model.VideoCacheRequest
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.CopyOnWriteArrayList
/**
* Preload Controller: submit tasks, stop, release and listen preload state
*/
class RedMediaPreload : IMediaPreload {
private val TAG = "RedMediaPreload"
// inner preload core
private val internalPreload: OpenRedPreload = OpenRedPreload()
private var preloadCacheListeners = CopyOnWriteArrayList<PreloadCacheListener>()
private val downloadEventListener =
OpenRedPreload.DownloadEventListener { event: Int, bundle: Bundle?, realCacheUrl: String?, userData: Any? ->
when (event) {
// preload task success
OpenRedPreload.PRELOAD_EVENT_IO_TRAFFIC -> {
if (bundle == null) {
return@DownloadEventListener
}
if (userData !is VideoCacheRequest) {
return@DownloadEventListener
}
val cacheSize = bundle.getInt("cache_size").toLong()
val localPath = bundle.getString("cache_file_path", "")
preloadCacheListeners.forEach { listener ->
listener.onPreloadSuccess(localPath, cacheSize, userData)
}
Log.d(
TAG, "[DownloadEventListener]: PRELOAD_EVENT_IO_TRAFFIC:$userData"
)
}
// Preload Speed
OpenRedPreload.PRELOAD_EVENT_SPEED -> {
if (bundle == null) {
return@DownloadEventListener
}
if (userData !is VideoCacheRequest) {
return@DownloadEventListener
}
val speed = bundle.getLong("speed")
Log.d(
TAG,
"[DownloadEventListener]: speed:${speed}, $userData"
)
}
// TCP Connection
OpenRedPreload.PRELOAD_EVENT_DID_TCP_OPEN -> {
if (bundle == null) {
return@DownloadEventListener
}
if (userData !is VideoCacheRequest) {
return@DownloadEventListener
}
val dstIp = bundle.getString("dst_ip") ?: ""
val source = bundle.getInt("source")
Log.d(
TAG,
"[DownloadEventListener]PRELOAD_EVENT_DID_TCP_OPEN, dstIp:$dstIp, source:$source, userData:$userData"
)
}
// HTTP Connection Success
OpenRedPreload.PRELOAD_EVENT_DID_HTTP_OPEN -> {
if (bundle == null) {
return@DownloadEventListener
}
if (userData !is VideoCacheRequest) {
return@DownloadEventListener
}
val httpRtt = bundle.getInt("http_rtt").toLong()
val source = bundle.getInt("source")
Log.d(
TAG, "[DownloadEventListener]" +
"PRELOAD_EVENT_DID_HTTP_OPEN, httpRtt:$httpRtt source:$source userData:$userData"
)
}
// 预载出错
OpenRedPreload.PRELOAD_EVENT_ERROR -> {
if (bundle == null) {
return@DownloadEventListener
}
if (userData !is VideoCacheRequest) {
return@DownloadEventListener
}
val error = bundle.getInt("error").toLong()
val source = bundle.getInt("source")
preloadCacheListeners.forEach { listener ->
listener.onPreloadError(error, userData)
}
Log.d(
TAG, "[DownloadEventListener]" +
"PRELOAD_EVENT_ERROR, error:$error, source:$source, userData:$userData"
)
}
}
}
override fun addPreloadCacheListener(listener: PreloadCacheListener?) {
listener?.let { preloadCacheListeners.add(it) }
}
override fun removePreloadCacheListener(listener: PreloadCacheListener?) {
listener?.let { preloadCacheListeners.remove(it) }
}
override fun start(requests: List<VideoCacheRequest>?) {
if (requests?.isEmpty() == true) {
Log.d(TAG, "has no preload task, return.")
return
}
submitNewPreloadRequest(requests)
}
override fun stop() {
internalPreload.stop()
Log.d(TAG, "stop(), stop all preload task.")
}
override fun release() {
internalPreload.release()
preloadCacheListeners.clear()
Log.d(TAG, "release(), release all task.")
}
override fun getAllCacheFilePaths(cacheDir: String?): Array<String>? {
if (cacheDir.isNullOrEmpty()) {
return null
}
return internalPreload.getAllCachedFile(cacheDir)?.also {
Log.d(
TAG,
"getAllCacheFilePaths(), cacheDir: $cacheDir, result: ${it.size}"
)
}
}
override fun deleteCacheFile(url: String?, cacheDir: String?): Int? {
if (url.isNullOrEmpty() || cacheDir.isNullOrEmpty()) {
return -1
}
return internalPreload.deleteCache(cacheDir, url, true).also {
Log.d(
TAG,
"deleteCacheFile(), url: $url, cacheDir: $cacheDir, result: $it"
)
}
}
override fun getCacheFileRealSize(url: String?, cacheDir: String?): Long {
if (url.isNullOrEmpty() || cacheDir.isNullOrEmpty()) {
return -1L
}
return internalPreload.getCachedSize(cacheDir, url, true).also {
Log.d(
TAG,
"getCacheFileRealSize(), url: $url, cacheDir: $cacheDir, fileSize: $it"
)
}
}
override fun getCacheFilePath(url: String?, cacheDir: String?): String? {
if (url.isNullOrEmpty() || cacheDir.isNullOrEmpty()) {
return null
}
return internalPreload.getCacheFilePath(cacheDir, url)?.also {
Log.d(
TAG,
"getCacheFilePath(), cacheDir: $cacheDir, url: ${url}, localPath: $it"
)
}
}
/** submit new preload request */
private fun submitNewPreloadRequest(requests: List<VideoCacheRequest>?) {
requests?.forEach { request ->
internalPreload.open(
request.finalUrl,
request.cacheDir,
request.cacheSize,
WeakReference(downloadEventListener),
request.getPreloadParams(),
request
)
}
}
}

View File

@ -0,0 +1,41 @@
package com.xingin.openredpreload.impl.model
import android.os.Bundle
/**
* preload request model
*/
data class VideoCacheRequest(
/** preload task name */
val name: String = "",
/** preload resource url */
val videoUrl: String = "",
/** preload resource json url, high than videoUrl */
val videoJson: String = "",
/** preload cache dir */
val cacheDir: String = "",
/** preload data size */
val cacheSize: Long = 0,
/** preload dir max size: when beyond, start LRU */
val cacheDirMaxSize: Long = 0,
/** preload dir max file count: when beyond,start LRU */
val cacheDirMaxEntries: Long = 0,
val businessLine: String = "",
) {
val finalUrl = videoJson.ifBlank { videoUrl }
fun getPreloadParams(): Bundle {
return Bundle().apply {
if (videoJson.isNotBlank()) {
this.putBoolean("is_json", true)
}
// network: same the http request param
this.putInt("use_https", 1)
this.putString("referer", "")
this.putString("user_agent", "")
this.putString("header", "")
this.putLong("capacity", cacheDirMaxSize)
this.putLong("cache_max_entries", cacheDirMaxEntries)
}
}
}

View File

@ -0,0 +1,17 @@
package com.xingin.openredpreload;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}

View File

@ -0,0 +1,85 @@
# How to use the Android RedPreload SDK
This guide provides step-by-step instructions on how to initialize and configure the Android SDK for our open-source video preload. When use preload to download video data, your MediaPlayer can start more faster than normal. So we highly recommand you combine the RedPreload SDK and [RedPlayer SDK](README.md) to usage.
## Key Features
- Supports preload videos in both normal URL and [JSON](../../JSON.md) formats
- Provides options to configure the preload, such as download size, download cache dir
- Supports monitoring preload status and callbacks for various events
## API References:
* [IMediaPreload.java](OpenRedPreload/src/main/java/com/xingin/openredpreload/api/IMediaPreload.kt)
## ▶️ Getting Started
## Step 1: Create media preload
```java
IMediaPreoad mMediaPreload = new RedMediaPreload();
```
## Step 2: Create preload request
```java
pubic class VideoCacheRequest {
public String name; // preload task name
public String videoUrl; // preload resource url
public String videoJson; // preload resource json url, high than videoUrl
public String cacheDir; // preload cache dir
public String cacheSize; // preload data size
public String cacheDirMaxSize; // preload dir max size: when beyond, start LRU
public String cacheDirMaxEntries; // preload dir max file count: when beyond,start LRU
}
preloadRequest = new VideoCacheRequest()
```
## Step 3: Start preload request
```java
mMediaPreload.start(preloadRequest)
```
By following the three steps above, you can complete the use of the Media Preload SDK
## Step 4: Common preload methods
```java
void start(VideCacheRequest request); // start preload
void stop(); // stop preload
void release(); // release preload module: can't start again, need recreate
long getAllCacheFilePaths(String cacheDir); // get the dir's all files
long deleteCacheFile(String cacheDir, String url); // delete the cache dir task: the url is the key of preload task
float getCacheFileRealSize(String cacheDir, String url); // get the file real download size: not the file size
```
## Step 5: Preload status monitoring & callbacks
- **PreloadCacheListener** This interface runs through the entire lifecycle of the preload, it will be called with many different event.
```java
interface PreloadCacheListener {
/**
* @param cacheFilePath file absolute path
* @param cacheFileSize file size, unit: b
* @param request origin preload request
*/
void onPreloadSuccess(String cacheFilePath, long cacheFileSize, VideoCacheRequest request);
/**
* @param errorMsg preload error msg
* @param request origin preload request
*/
void onPreloadError(long errorMsg, VideoCacheRequest request);
/**
* @param request origin preload request
*/
void onPreloadStart(VideoCacheRequest request);
}
void addPreloadCacheListener(PreloadCacheListener listener); // add the preload status listener
void removePreloadCacheListener(PreloadCacheListener listener); // remove the preload status listener
```

203
source/android/README.md Normal file
View File

@ -0,0 +1,203 @@
# How to use the Android RedPlayer SDK
This guide provides step-by-step instructions on how to initialize and configure the Android SDK for our open-source video player, This player supports videos in both regular URL and [JSON formats](../../JSON.md). In addition to basic usage, it also supports advanced features such as [data preload](Preload_README.md) and playing while downloading and so on.
📌Integrate RedPlayer into your android studio project [RedPlayerDemo](../android/app/README.md)
📌For video preloading feature, please refer to [RedPreload SDK](Preload_README.md)
## Key Features
- Supports playing videos in both normal URL and [JSON formats](../../JSON.md)
- Offers multiple rendering methods, including SurfaceView, TextureView
- Provides options to configure the player, such as HDR decoding, autoplay, loop count, and more
- Supports monitoring player status and callbacks for various events
## API References:
* [IMediaPlayer.java](OpenRedPlayerCore/src/main/java/com/xingin/openredplayercore/core/api/IMediaPlayer.java)
## ▶️ Getting Started
## Step 1: Create the player
```java
IMediaPlayer mMediaPlayer = new RedMediaPlayer();
```
## Step 2: Call SetDataSource
If you are playing a **regular URL**, use the following code:
```java
mMediaPlayer.setDataSource(mAppContext, url);
```
If you are playing a **JSON format**, use the following code:
```java
mMediaPlayer.setDataSourceJson(mAppContext, jsonUrl);
```
## Step 3: Configure the player
Use MediaCodec decoding if your android system support: **The default is false and use ffmpeg**
```java
mMediaPlayer.setEnableMediaCodec(true);
```
Set playing download cache dir: **The default is null, highly recommend specify a path**
```java
mMediaPlayer.setVideoCacheDir(cacheDir);
```
Set is play in looping mode: **The default is false**
```java
mMediaPlayer.setLoop(true);
```
Set whether to mute: **The default is 1.0**
```java
mMediaPlayer.setVolume(0.0f, 0.0f);
```
Set the Surface or SurfaceHolder to player, which decide you use SurfaceView or TextureView</br>
If you are render use **TextureView**, use the following code:
```java
mMediaPlayer.setSurface(surface);
```
If you are render use **SurfaceView**, use the following code:
```java
mMediaPlayer.setDisplay(surfaceHolder);
```
Finally, call prepareAsync to start the connection and decoding:
```java
mMediaPlayer.prepareAsync();
```
## Step 4: Common player methods
```java
void start(); // start player
void pause(); // pause player
void stop(); // stop player: can't start again, need prepareAsync
void reset(); // reset player: the player state to IDLE
void release(); // release player: the player is null, can't call any method
```
## Step 5: Player status retrieval
```java
long getCurrentPosition(); // the player current play time
long getDuration(); // the total duration of the media resource
float getSpeed(); // the player current play speed
long getBitRate(); // the media resource current bit rate
int getVideoWidth(); // the media resource width
int getVideoHeight(); // the media resource height
String getPlayUrl(); // the player final play url
boolean isPlaying(); // the player is in playing state
boolean isLooping(); // the player is in play looping
...
```
## Step 6: Player status monitoring & callbacks
- **OnPreparedListener** When the player is prepared, this listener will be called, you can start playback after this listener.
```java
interface OnPreparedListener {
void onPrepared(IMediaPlayer mp, RedPlayerEvent event);
}
mMediaPlayer.setOnPreparedListener(preparedListener); // monitor the player prepared callback
```
- **OnVideoSizeChangedListener** When video size changed, this listener will be called, you can update you render view with the new width and height.
```java
interface OnVideoSizeChangedListener {
// the width & height params is the new width and height
void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sar_num,int sar_den);
}
mMediaPlayer.setOnVideoSizeChangedListener(sizeChangedListener); // monitor the player video size change callback
```
- **OnCompletionListener** When the player is play complete, this listener will be called, you can play next video in this callback.
```java
interface OnCompletionListener {
void onCompletion(IMediaPlayer mp);
}
mMediaPlayer.setOnCompletionListener(completionListener); // monitor the player play complete callback
```
- **OnSeekCompleteListener** When you seek the player, this listener will be called.
```java
interface OnSeekCompleteListener {
void onSeekComplete(IMediaPlayer mp);
}
mMediaPlayer.setOnSeekCompleteListener(seekCompleteListener); // monitor the seek complete callback
```
- **OnBufferingUpdateListener** When the player buffering the video stream, this listener willl be called, you can get buffering percent.
```java
interface OnBufferingUpdateListener {
void onBufferingUpdate(IMediaPlayer mp, int percent);
}
mMediaPlayer.setOnBufferingUpdateListener(bufferingUpdateListener); // monitor the player buffering callback
```
- **OnErrorListener** When the player play error, this listener will be called, you can get error msg and retry the player.
```java
interface OnErrorListener {
boolean onError(IMediaPlayer mp, int what, int extra);
}
mMediaPlayer.setOnErrorListener(errorListener); // monitor the play error callback
```
- **OnInfoListener** This interface runs through the entire lifecycle of the player, it will be called with many different event.
```java
interface OnInfoListener {
int MEDIA_INFO_OPEN_INPUT = 10005; // the stream connection established
int MEDIA_INFO_FIND_STREAM_INFO = 10006; // the audio and video format detection completed
int MEDIA_INFO_COMPONENT_OPEN = 10007; // the decoder initialization completed
int MEDIA_INFO_VIDEO_FIRST_PACKET_IN_DECODER = 10010; // The first video packet enters the decoder
int MEDIA_INFO_VIDEO_DECODED_START = 10004; // The first video frame decoding is completed
int MEDIA_INFO_VIDEO_RENDERING_START = 3; // The first video frame rendering is completed.
int MEDIA_INFO_BUFFERING_START = 701; // the buffering start
int MEDIA_INFO_BUFFERING_END = 702; // the buffering end
int MEDIA_INFO_VIDEO_ROTATION_CHANGED = 10001;// the video rotation changed
int MEDIA_INFO_VIDEO_START_ON_PLAYING = 10011; // the second frame rendering start
boolean onInfo(IMediaPlayer mp, int what, int extra, RedPlayerEvent event);
}
mMediaPlayer.setOnInfoListener(infoListener); // monitor the player info callback
```
## Step 7: Set Log Callback
```java
interface NativeLogCallback {
void onLogOutput(int logLevel, String tag, String content);
}
/**
* Sets the log callback level for the player.
* @param logLevel The log level for the log callback.
*/
void setLogCallbackLevel(int logLevel);
/**
* Sets the log callback for the player
* @param nativeLogCallback The log callback block.
*/
static void setNativeLogCallback(NativeLogCallback nativeLogCallback);
```

1
source/android/app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,86 @@
# Usage Guide - DEMO
## Before Run
Before building the SDK, please make sure you have the following dependencies installed:
1. **Git:** Ensure that Git is installed on your machine. If not, you can download and install it from [https://git-scm.com/](https://git-scm.com/). Or using the following command:
```bash
brew install git
```
2. **Android SDK:** [Andrioid SDK](https://developer.android.com/studio?hl=en) is android project base dependency. You should download and then config with the following command:
```bash
# add this line to your ~/.bash_profile or ~/.profile, the android sdk will work
export ANDROID_SDK=<your sdk path>
# My build environment:
# macOS 14.0
# Android Studio Flamingo | 2022.2.1 Patch 2
# gradle version: 7.5.0
```
## My Run Environment
- macOS 14.0
- Android Studio Flamingo | 2022.2.1 Patch 2
- gradle version: 7.5.0
## Example Run
To run the example project, clone the repo, and run `./gradlew installDebug` from the Example directory first.
1. Clone the repository
```bash
git clone https://github.com/RTE-Dev/RedPlayer.git
```
2. Navigate to the demo project directory
```bash
cd RedPlayer/source/android
```
3. Build and Install RedPlayer-Demo.apk to your android phone
```bash
./gradlew installDebug
```
### Demo
click to download [RedPlayer-Demo.apk](../docs/RedPlayer-Demo.apk)<br>
![Demo 1](../docs/playing.gif) &nbsp;&nbsp; ![Demo 2](../docs/setting.gif) <br><br>
# 📌How to integrate RedPlayer into your Android project
## Requirements
- Android Phone System 5.0+
## ▶️ Getting Started
### 1. Create a PlayerDemo Project
Start by creating a new android project named `PlayerDemo`
### 2. Setup Dependency
In the root directory of your project, create a `app module` and open the `build.gradle` file
```java
// add the RedPlayer SDK and RedPreload SDK
dependencies {
implementation project(path: ':OpenRedPlayerCore')
implementation project(path: ':OpenRedPreload')
}
```
This module includes dependencies on local **RedPlayer SDK**, **RedPreload SDK** and **ffmpeg**, **opensoundtouch**.
### 3. Build & Install
Run the following command in the terminal to build and install your demo:
```
$ ./gradlew installDebug
```
Then you `app module` will build the apk and auto install you android phone.

View File

@ -0,0 +1,124 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
compileSdk 34
defaultConfig {
applicationId "com.xingin.openredplayer"
minSdk 21
targetSdk 28
versionCode 1
versionName "1.0"
resConfigs "en"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
release {
storeFile file("redplayer")
storePassword "123456"
keyAlias "redplayer"
keyPassword "123456"
}
}
buildTypes {
release {
minifyEnabled true
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
pickFirst 'lib/armeabi-v7a/libredbase.so'
pickFirst 'lib/arm64-v8a/libredbase.so'
pickFirst 'lib/armeabi-v7a/libreddownload.so'
pickFirst 'lib/arm64-v8a/libreddownload.so'
pickFirst 'lib/armeabi-v7a/libredlog.so'
pickFirst 'lib/arm64-v8a/libredlog.so'
pickFirst 'lib/armeabi-v7a/libredstrategycenter.so'
pickFirst 'lib/arm64-v8a/libredstrategycenter.so'
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
compose true
viewBinding true
}
composeOptions {
kotlinCompilerExtensionVersion '1.3.2'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "RedPlayer-Demo.apk"
}
def outputFilePath = "${rootDir.absolutePath}/docs/"
File outputFile = new File(outputFilePath)
variant.assemble.doLast {
copy {
variant.outputs.all { file ->
copy {
from file.outputFile
into outputFile
}
}
}
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.aar'])
implementation 'androidx.core:core-ktx:1.12.0'
implementation platform('org.jetbrains.kotlin:kotlin-bom:1.8.0')
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.7.0'
implementation 'androidx.activity:activity-compose:1.8.2'
implementation platform('androidx.compose:compose-bom:2022.10.00')
implementation 'androidx.compose.ui:ui'
implementation 'androidx.compose.ui:ui-graphics'
implementation 'androidx.compose.ui:ui-tooling-preview'
implementation 'androidx.compose.material3:material3'
implementation 'androidx.recyclerview:recyclerview:1.3.2'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.coordinatorlayout:coordinatorlayout:1.2.0'
implementation 'com.google.android.material:material:1.11.0'
implementation 'androidx.preference:preference-ktx:1.2.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation platform('androidx.compose:compose-bom:2022.10.00')
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
debugImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'
//
implementation project(path: ':OpenRedPreload')
implementation project(path: ':OpenRedPlayerCore')
//
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.google.code.gson:gson:2.10.1'
implementation "io.reactivex.rxjava3:rxjava:3.1.8"
implementation 'io.reactivex.rxjava3:rxandroid:3.0.2'
implementation 'com.github.tbruyelle:rxpermissions:0.12'
implementation 'com.wang.avi:library:2.1.3'
}

Binary file not shown.

21
source/android/app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

Binary file not shown.

View File

@ -0,0 +1,26 @@
package com.xingin.openredplayer;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.xingin.openredplayer", appContext.getPackageName());
}
}

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xingin.openredplayer">
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.SENSOR" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:name=".XhsMediaApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:testOnly="false"
android:theme="@style/Theme.OpenRedPlayer"
tools:targetApi="28">
<!-- 首页 -->
<activity
android:name=".home.XhsHomeActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 输入页 -->
<activity
android:name=".input.XhsInputActivity"
android:screenOrientation="portrait" />
<!-- 双列Feed页 -->
<activity
android:name=".feed.XhsFeedActivity"
android:screenOrientation="portrait" />
<!-- 相册页 -->
<activity
android:name="com.kelin.photoselector.PhotoSelectorActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.Design" />
<!-- 视频播放页 -->
<activity
android:name=".player.XhsPlayerActivity"
android:configChanges="orientation|screenSize|keyboardHidden" />
<!-- 小窗播放后台服务 -->
<service android:name=".floating.XhsFloatingService" />
</application>
</manifest>

View File

@ -0,0 +1,24 @@
package com.xingin.openredplayer
import android.app.Application
import com.kelin.photoselector.PhotoSelector
class XhsMediaApplication : Application() {
override fun onCreate() {
super.onCreate()
instance = this
// 初始化相册选择
PhotoSelector.init(
this,
this.packageName + ".fileProvider",
true,
100,
false
)
}
companion object {
lateinit var instance: XhsMediaApplication
private set
}
}

View File

@ -0,0 +1,258 @@
package com.xingin.openredplayer.feed
import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.tbruyelle.rxpermissions3.RxPermissions
import com.xingin.openredplayer.R
import com.xingin.openredplayer.feed.model.XhsFeedModel
import com.xingin.openredplayer.feed.model.XhsVisibleItemInfo
import com.xingin.openredplayer.feed.model.generateCacheRequest
import com.xingin.openredplayer.feed.model.getHomeFeedData
import com.xingin.openredplayer.feed.model.getVisibleItemsInfo
import com.xingin.openredplayer.player.XhsPlayerActivity
import com.xingin.openredplayer.player.XhsPlayerActivity.Companion.INTENT_KEY_SHOW_LOADING
import com.xingin.openredplayer.player.XhsPlayerActivity.Companion.INTENT_KEY_URLS
import com.xingin.openredplayer.setting.XhsPlayerSettings
import com.xingin.openredplayer.utils.Utils
import com.xingin.openredpreload.api.IMediaPreload
import com.xingin.openredpreload.api.PreloadCacheListener
import com.xingin.openredpreload.impl.RedMediaPreload
import com.xingin.openredpreload.impl.model.VideoCacheRequest
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable
import java.io.Serializable
class XhsFeedActivity : AppCompatActivity(), XhsFeedAdapter.OnItemClickListener {
companion object {
private const val TAG = "XhsFeedActivity"
}
/** UI */
private lateinit var backView: ImageView
private lateinit var feedAdapter: XhsFeedAdapter
private lateinit var feedRecyclerView: RecyclerView
private lateinit var feedLayoutManager: StaggeredGridLayoutManager
private val currentPlayerMap = hashMapOf<Int, XhsFeedViewHolder>()
private var startScrollY = 0
private var endScrollY = 0
private var rvScrollDistance = 0
/** Config */
private lateinit var settingConfig: XhsPlayerSettings
/** preload */
private lateinit var mediaPreload: IMediaPreload
private var preloadDisposable: Disposable? = null
/** premission */
private val rxPermissions = RxPermissions(this)
private var permissionDisposable: Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_xhs_home_feed_layout)
settingConfig = XhsPlayerSettings(this)
initView()
initPreload()
initPermission()
}
override fun onDestroy() {
super.onDestroy()
mediaPreload.release()
preloadDisposable?.dispose()
permissionDisposable?.dispose()
clearAndStopOtherPlayer()
}
/** request storage permissionwhen grant the permissionstart preload the video stream data */
private fun initPermission() {
permissionDisposable = rxPermissions.request(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_NETWORK_STATE,
).subscribe { granted ->
if (granted) {
feedRecyclerView.postDelayed({
tryPreCacheVideoIfNeed(feedRecyclerView, "initPreload")
}, 1000)
}
}
}
private fun initView() {
backView = findViewById(R.id.top_action_back_view)
backView.setOnClickListener {
finish()
}
feedRecyclerView = findViewById(R.id.appbar_recyclerview)
feedLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
feedRecyclerView.layoutManager = feedLayoutManager
feedRecyclerView.addItemDecoration(XhsItemDecoration(2, 10, includeEdge = false))
feedRecyclerView.itemAnimator = DefaultItemAnimator()
feedRecyclerView.setHasFixedSize(true)
feedRecyclerView.addOnItemTouchListener(object :
RecyclerView.SimpleOnItemTouchListener() {})
feedRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
when (newState) {
// the RV scroll state to IDLEstart preload the video feed in current screen
RecyclerView.SCROLL_STATE_IDLE -> {
endScrollY = recyclerView.computeVerticalScrollOffset()
rvScrollDistance = endScrollY - startScrollY
tryPreCacheVideoIfNeed(recyclerView, "onScrollStateChangedV2")
}
// the RV scroll state to DRAGGING stop preload the video feed
RecyclerView.SCROLL_STATE_DRAGGING -> {
startScrollY = recyclerView.computeVerticalScrollOffset()
mediaPreload.stop()
}
// the RV scroll state to SETTLINGstop preload the video feed
RecyclerView.SCROLL_STATE_SETTLING -> {
mediaPreload.stop()
}
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
clearAndStopOtherPlayer()
if (recyclerView.canScrollVertically(1)) {
return
}
val moreDataList = getHomeFeedData()
feedAdapter.loadMoreData(moreDataList)
}
})
// init Adapter
initFeedAdapter()
}
private fun initFeedAdapter() {
feedAdapter = XhsFeedAdapter(this, getHomeFeedData())
feedAdapter.setOnItemClickListener(this)
feedRecyclerView.adapter = feedAdapter
}
/** init preload module */
private fun initPreload() {
mediaPreload = RedMediaPreload().apply {
addPreloadCacheListener(object : PreloadCacheListener {
override fun onPreloadSuccess(
cacheFilePath: String,
cacheFileSize: Long,
request: VideoCacheRequest
) {
Log.d(TAG, "the request $request is preload success.")
}
override fun onPreloadError(errorMsg: Long, request: VideoCacheRequest) {
Log.d(TAG, "the request $request is preload error, the error code is:$errorMsg")
}
override fun onPreloadStart(request: VideoCacheRequest) {
Log.d(TAG, "the request $request is preload start.")
}
})
}
}
@MainThread
private fun tryPreCacheVideoIfNeed(recyclerView: RecyclerView, invoke: String = "unknown") {
// 1.0 release the last preload result.
preloadDisposable?.dispose()
val layoutManager = recyclerView.layoutManager
if (layoutManager !is StaggeredGridLayoutManager) {
return
}
// 1.1 find the visible items in screen: async execute
preloadDisposable = layoutManager.getVisibleItemsInfo(recyclerView)
.doOnNext { visibleItems ->
// 1.2 covert the visible item model to video cache request
val pendingCacheReqList = mutableListOf<VideoCacheRequest>()
for (visibleItemInfo in visibleItems) {
if (visibleItemInfo.index == RecyclerView.NO_POSITION) continue
val cacheRequest = generateCacheRequest(recyclerView, visibleItemInfo.index)
cacheRequest?.let { pendingCacheReqList.add(it) }
}
// 1.3 start preload the video cache request
mediaPreload.start(pendingCacheReqList)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe { visibleItems ->
// 1.4 try to play the feed: random select one
tryFetchVideoPlay(visibleItems, rvScrollDistance)
}.also { Log.d(TAG, "tryPreCacheVideoIfNeed(), invoke by $invoke") }
}
override fun onClick(holder: RecyclerView.ViewHolder?, position: Int, model: XhsFeedModel?) {
val intent = Intent(this, XhsPlayerActivity::class.java)
intent.putExtra(INTENT_KEY_URLS, listOf(model?.finalUrl) as Serializable)
intent.putExtra(INTENT_KEY_SHOW_LOADING, model?.isShowLoading)
startActivity(intent)
}
/** try find the current feed to play */
private fun tryFetchVideoPlay(visibleItems: List<XhsVisibleItemInfo>, distance: Int) {
if (!settingConfig.enableCoverVideoPlayer) {
return
}
if (!Utils.beyondScreenOneThirdHeight(this@XhsFeedActivity, distance)) {
return
}
val runnable = Runnable {
val visibleItem =
Utils.getElementRandom(visibleItems.filter { it.priority == 100 })
?: return@Runnable
val currentPosition = visibleItem.index
val currentItemHolder = currentPlayerMap.remove(currentPosition)
if (currentItemHolder != null) {
clearAndStopOtherPlayer()
// has played, fetch and continue play
currentItemHolder.videoPlayerView.start()
currentItemHolder.videoPlayerView.setLoop(true)
currentItemHolder.videoPlayerView.setVolume(0f, 0f)
currentItemHolder.videoPlayerView.setOnStartPlayListener { _, _, _ ->
currentItemHolder.imageView.visibility = View.INVISIBLE
}
currentPlayerMap[currentPosition] = currentItemHolder
} else {
clearAndStopOtherPlayer()
val itemModel = feedAdapter.items.getOrNull(currentPosition) ?: return@Runnable
if (itemModel.canPlay == false) {
return@Runnable
}
// has never played, init player and start play
val itemView =
feedLayoutManager.findViewByPosition(currentPosition) ?: return@Runnable
val itemHolder = feedRecyclerView.getChildViewHolder(itemView) as XhsFeedViewHolder
itemHolder.videoPlayerView.setVideoPath(itemModel.finalUrl)
itemHolder.videoPlayerView.setLoop(true)
itemHolder.videoPlayerView.setVolume(0f, 0f)
itemHolder.videoPlayerView.setOnStartPlayListener { _, _, _ ->
itemHolder.imageView.visibility = View.INVISIBLE
}
currentPlayerMap[currentPosition] = itemHolder
}
}
feedRecyclerView.postDelayed(runnable, 100)
}
/** stop all media player */
private fun clearAndStopOtherPlayer() {
currentPlayerMap.values.forEach { holder ->
holder.imageView.visibility = View.VISIBLE
holder.videoPlayerView.release()
}
currentPlayerMap.clear()
}
}

View File

@ -0,0 +1,69 @@
package com.xingin.openredplayer.feed
import android.annotation.SuppressLint
import android.app.Activity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.contentValuesOf
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.xingin.openredplayer.R
import com.xingin.openredplayer.feed.model.XhsFeedModel
class XhsFeedAdapter(val context: Activity, var items: MutableList<XhsFeedModel>) :
RecyclerView.Adapter<XhsFeedViewHolder>() {
private var mOnItemClickListener: OnItemClickListener? = null
private var mOnItemLongClickListener: OnItemLongClickListener? = null
private var itemCount = 0
init {
itemCount = items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): XhsFeedViewHolder {
val item =
LayoutInflater.from(parent.context).inflate(R.layout.item_feed_layout, parent, false)
return XhsFeedViewHolder(item)
}
@SuppressLint("UseCompatLoadingForDrawables")
override fun onBindViewHolder(holder: XhsFeedViewHolder, position: Int) {
val model = items[position]
// holder.imageView.setImageResource(model.coverUrl)
Glide.with(context).load("").placeholder(model.coverUrl).into(holder.imageView)
holder.itemView.setOnClickListener {
mOnItemClickListener?.onClick(holder, position, model)
}
holder.itemView.setOnLongClickListener {
mOnItemLongClickListener?.onLongClick(holder, position, model)
return@setOnLongClickListener true
}
}
override fun getItemCount(): Int {
return items.size
}
fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
mOnItemClickListener = onItemClickListener
}
fun setOnItemLongClickListener(onItemLongClickListener: OnItemLongClickListener?) {
mOnItemLongClickListener = onItemLongClickListener
}
fun loadMoreData(feeds: List<XhsFeedModel>) {
val oldItemCount: Int = itemCount
items.addAll(feeds)
itemCount = items.size
notifyItemRangeInserted(oldItemCount, feeds.size)
}
interface OnItemClickListener {
fun onClick(holder: RecyclerView.ViewHolder?, position: Int, model: XhsFeedModel?)
}
interface OnItemLongClickListener {
fun onLongClick(holder: RecyclerView.ViewHolder?, position: Int, model: XhsFeedModel?)
}
}

View File

@ -0,0 +1,17 @@
package com.xingin.openredplayer.feed
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.xingin.openredplayer.R
import com.xingin.openredplayer.feed.view.XhsFeedCoverPlayerView
class XhsFeedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imageView: ImageView
var videoPlayerView: XhsFeedCoverPlayerView
init {
imageView = itemView.findViewById(R.id.iv)
videoPlayerView = itemView.findViewById(R.id.feed_video_view)
}
}

View File

@ -0,0 +1,39 @@
package com.xingin.openredplayer.feed
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class XhsItemDecoration(
private val spanCount: Int,
private val spacing: Int,
private val includeEdge: Boolean
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
val position = parent.getChildAdapterPosition(view) // item position
val column = position % spanCount // item column
if (includeEdge) {
outRect.left =
spacing - column * spacing / spanCount // spacing - column * ((1f / spanCount) * spacing)
outRect.right =
(column + 1) * spacing / spanCount // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing
}
outRect.bottom = spacing // item bottom
} else {
outRect.left = column * spacing / spanCount // column * ((1f / spanCount) * spacing)
outRect.right =
spacing - (column + 1) * spacing / spanCount // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing // item top
}
}
}
}

View File

@ -0,0 +1,168 @@
package com.xingin.openredplayer.feed.model
import com.kelin.photoselector.model.Photo
import com.xingin.openredplayer.R
import com.xingin.openredplayer.utils.Utils
/** define the feed model */
data class XhsFeedModel(
val coverUrl: Int,
val isLocal: Boolean,
val videoUrl: String? = null,
val videoJsonUrl: String? = null,
val isShowLoading: Boolean? = false,
val canPlay: Boolean? = true,
) {
val finalUrl = if (videoJsonUrl.isNullOrEmpty()) videoUrl else videoJsonUrl
}
/** init the rv data model */
fun getHomeFeedData(): MutableList<XhsFeedModel> {
return ArrayList<XhsFeedModel>().apply {
// JSON
this.add(
createModel(
coverUrl = R.mipmap.icon_video_1,
isLocal = false,
jsonVideoUrl = JSON_DATA_SOURCE,
isShowLoading = false,
canPlay = true,
)
)
// MP4
this.add(
createModel(
coverUrl = R.mipmap.icon_video_2,
isLocal = false,
videoUrl = VIDEO_ONE,
isShowLoading = false,
canPlay = true,
)
)
// MP4-HDR
this.add(
createModel(
coverUrl = R.mipmap.icon_video_3,
isLocal = false,
videoUrl = VIDEO_TWO,
isShowLoading = false,
canPlay = true,
)
)
// HLS
this.add(
createModel(
coverUrl = R.mipmap.icon_video_4,
isLocal = false,
videoUrl = VIDEO_ONE,
isShowLoading = false,
canPlay = true,
)
)
// HLS-Live-4k
this.add(
createModel(
coverUrl = R.mipmap.icon_video_5,
isLocal = false,
videoUrl = VIDEO_TWO,
isShowLoading = false,
canPlay = false,
)
)
// RTMP
this.add(
createModel(
coverUrl = R.mipmap.icon_video_6,
isLocal = false,
videoUrl = VIDEO_ONE,
isShowLoading = false,
canPlay = false,
)
)
// m3u8
this.add(
createModel(
coverUrl = R.mipmap.icon_video_7,
isLocal = false,
videoUrl = VIDEO_TWO,
isShowLoading = false,
canPlay = true,
)
)
// MOV
this.add(
createModel(
coverUrl = R.mipmap.icon_video_8,
isLocal = false,
videoUrl = VIDEO_ONE,
isShowLoading = false,
canPlay = true,
)
)
this.add(
createModel(
coverUrl = R.mipmap.icon_video_9,
isLocal = false,
videoUrl = VIDEO_TWO,
isShowLoading = false,
canPlay = true,
)
)
this.add(
createModel(
coverUrl = R.mipmap.icon_video_1,
isLocal = false,
videoUrl = VIDEO_ONE,
isShowLoading = false,
canPlay = true,
)
)
this.add(
createModel(
coverUrl = R.mipmap.icon_video_2,
isLocal = false,
videoUrl = VIDEO_TWO,
isShowLoading = false,
canPlay = true,
)
)
this.add(
createModel(
coverUrl = R.mipmap.icon_video_3,
isLocal = false,
videoUrl = VIDEO_ONE,
isShowLoading = false,
canPlay = true,
)
)
}
}
private fun createModel(
coverUrl: Int,
isLocal: Boolean,
videoUrl: String? = null,
jsonVideoUrl: String? = null,
isShowLoading: Boolean? = false,
canPlay: Boolean? = false,
): XhsFeedModel {
return XhsFeedModel(coverUrl, isLocal, videoUrl, jsonVideoUrl, isShowLoading, canPlay)
}
/** the video source */
val VIDEO_ONE =
Utils.decodeBase64("aHR0cHM6Ly9zbnMtdmlkZW8tYWwueGhzY2RuLmNvbS9zdHJlYW0vMTEwLzQwNS8wMWU1ODNjYjZlMGZlZDVhMDEwMzcwMDM4YzhhZDk2MmZiXzQwNS5tcDQ=")
val VIDEO_TWO =
Utils.decodeBase64("aHR0cDovL3Nucy12aWRlby1hbC54aHNjZG4uY29tL3NwZWN0cnVtLzAxZTI5NjRlNDE2YmUwNzcwMTgzNzAwMzgxMWI0ZTM5YzlfNTEzLm1wNA==")
/** the json data source */
val JSON_DATA_SOURCE = Utils.decodeBase64(
"eyJzdHJlYW0iOnsiaDI2NCI6W3sid2lkdGgiOjcyMCwiaGVpZ2h0IjoxMjgwLCJhdmdfYml0cmF0ZSI6MTAzNTE1NCwibWFzdGVyX3VybCI6Imh0dHBzOi8vc25zLXZpZGVvLWFsLnhoc2Nkbi5jb20vc3RyZWFtLzExMC80MDUvMDFlNTgzY2I2ZTBmZWQ1YTAxMDM3MDAzOGM4YWQ5NjJmYl80MDUubXA0IiwiYmFja3VwX3VybHMiOlsiaHR0cHM6Ly9zbnMtdmlkZW8tYWwueGhzY2RuLmNvbS9zdHJlYW0vMTEwLzQwNS8wMWU1ODNjYjZlMGZlZDVhMDEwMzcwMDM4YzhhZDk2MmZiXzQwNS5tcDQiXX1dLCJoMjY1IjpbeyJ3aWR0aCI6NzIwLCJoZWlnaHQiOjEyODAsImF2Z19iaXRyYXRlIjo2ODcwMjYsIm1hc3Rlcl91cmwiOiJodHRwczovL3Nucy12aWRlby1hbC54aHNjZG4uY29tL3N0cmVhbS8xMTAvNDA1LzAxZTU4M2NiNmUwZmVkNWEwMTAzNzAwMzhjOGFkOTYyZmJfNDA1Lm1wNCIsImJhY2t1cF91cmxzIjpbImh0dHBzOi8vc25zLXZpZGVvLWFsLnhoc2Nkbi5jb20vc3RyZWFtLzExMC80MDUvMDFlNTgzY2I2ZTBmZWQ1YTAxMDM3MDAzOGM4YWQ5NjJmYl80MDUubXA0Il19LHsid2lkdGgiOjEwODAsImhlaWdodCI6MTkyMCwiYXZnX2JpdHJhdGUiOjkzOTU1NCwibWFzdGVyX3VybCI6Imh0dHBzOi8vc25zLXZpZGVvLWFsLnhoc2Nkbi5jb20vc3RyZWFtLzExMC80MDUvMDFlNTgzY2I2ZTBmZWQ1YTAxMDM3MDAzOGM4YWQ5NjJmYl80MDUubXA0IiwiYmFja3VwX3VybHMiOlsiaHR0cHM6Ly9zbnMtdmlkZW8tYWwueGhzY2RuLmNvbS9zdHJlYW0vMTEwLzQwNS8wMWU1ODNjYjZlMGZlZDVhMDEwMzcwMDM4YzhhZDk2MmZiXzQwNS5tcDQiXX1dfX0="
)
fun covertToVideoUrls(photos: List<Photo>?): List<String> {
val urls = arrayListOf<String>()
photos?.forEach { urls.add(it.uri) }
return urls
}

View File

@ -0,0 +1,128 @@
package com.xingin.openredplayer.feed.model
import android.graphics.Rect
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.xingin.openredplayer.XhsMediaApplication
import com.xingin.openredplayer.feed.XhsFeedAdapter
import com.xingin.openredplayer.utils.Utils
import com.xingin.openredpreload.impl.model.VideoCacheRequest
import kotlin.math.min
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.TreeMap
/**
* RecyclerView VisibleItem
*
* @property index
* @property priority
* @property column
*/
class XhsVisibleItemInfo constructor(
val index: Int,
val priority: Int,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as XhsVisibleItemInfo
if (index != other.index) return false
return true
}
override fun hashCode(): Int {
return index
}
override fun toString(): String {
return "XhsVisibleItemInfo(index=$index, priority=$priority)"
}
}
/** get StaggeredGridLayoutManager visible Items in screen */
fun StaggeredGridLayoutManager.getVisibleItemsInfo(recyclerView: RecyclerView): Observable<List<XhsVisibleItemInfo>> {
val recyclerViewRect = Rect()
recyclerView.getGlobalVisibleRect(recyclerViewRect)
val minVisibleItemPosition: Int =
findFirstVisibleItemPositions(null).minOrNull() ?: RecyclerView.NO_POSITION
val maxVisibleItemPosition: Int =
findLastVisibleItemPositions(null).maxOrNull() ?: RecyclerView.NO_POSITION
if (minVisibleItemPosition == RecyclerView.NO_POSITION || maxVisibleItemPosition == RecyclerView.NO_POSITION) {
return Observable.empty()
}
val resultMap = TreeMap<Int, XhsVisibleItemInfo>()
return Observable.range(minVisibleItemPosition, maxVisibleItemPosition).map { position ->
val itemView = findViewByPosition(position)
val itemRect = Rect().apply {
itemView?.getGlobalVisibleRect(this)
}
val itemHeight = itemView?.height ?: 0
return@map Triple(
itemRect, itemHeight, position
)
}.observeOn(Schedulers.io()).map { triple ->
val itemRect = triple.first
val itemHeight = triple.second
val itemPosition = triple.third
val percentFirst = min(
when {
// the item height is 0: no impression, ignore
itemHeight == 0 -> 0
// the item is in the rv: calculate the impression percent
itemRect.bottom >= recyclerViewRect.bottom -> {
(recyclerViewRect.bottom - itemRect.top) * 100 / itemHeight
}
// the item beyond the rv: calculate the percent in rv
else -> {
(itemRect.bottom - recyclerViewRect.top) * 100 / itemHeight
}
}, 100
)
return@map XhsVisibleItemInfo(itemPosition, percentFirst)
}.toList().map { items ->
items.forEach {
if (!resultMap.containsKey(it.index)) {
resultMap[it.index] = it
}
}
// return with the order in screen: also can order by biz priority
return@map resultMap.values.toList()
}.toObservable()
}
/** get the index feed in adapter, and convert the video cache request */
fun generateCacheRequest(recyclerView: RecyclerView, index: Int): VideoCacheRequest? {
val adapter = recyclerView.adapter ?: return null
if (adapter !is XhsFeedAdapter) {
return null
}
return when (val feed = adapter.items.getOrNull(index)) {
is XhsFeedModel -> {
createCacheRequest(feed)
}
else -> null
}
}
val DEFAULT_CACHE_VIDEO_DIR = Utils.getVideCacheDir()
const val DEFAULT_CACHE_VIDEO_SIZE_MOBILE = 512 * 1024L
const val DEFAULT_CACHE_VIDEO_MAX_SIZE = 200 * 1024L * 1024L
const val DEFAULT_CACHE_VIDEO_MAX_ENTRIES = 200L
const val DEFAULT_CACHE_VIDEO_BUSINESS_LINE = "home_feed"
/** create the VideoCacheRequest through feed */
fun createCacheRequest(xhsFeedModel: XhsFeedModel): VideoCacheRequest {
return VideoCacheRequest(
"",
xhsFeedModel.videoUrl ?: "",
xhsFeedModel.videoJsonUrl ?: "",
DEFAULT_CACHE_VIDEO_DIR,
DEFAULT_CACHE_VIDEO_SIZE_MOBILE,
DEFAULT_CACHE_VIDEO_MAX_SIZE,
DEFAULT_CACHE_VIDEO_MAX_ENTRIES,
DEFAULT_CACHE_VIDEO_BUSINESS_LINE,
)
}

View File

@ -0,0 +1,575 @@
package com.xingin.openredplayer.feed.view;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.MediaController;
import androidx.annotation.NonNull;
import com.xingin.openredplayer.setting.XhsPlayerSettings;
import com.xingin.openredplayer.utils.Utils;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
import com.xingin.openredplayercore.core.impl.RedPlayerEvent;
import com.xingin.openredplayercore.core.impl.android.AndroidMediaPlayer;
import com.xingin.openredplayercore.core.impl.redplayer.RedMediaPlayer;
import com.xingin.openredplayercore.core.renderview.IRenderView;
import com.xingin.openredplayercore.core.renderview.SurfaceRenderView;
import com.xingin.openredplayercore.core.renderview.TextureRenderView;
import java.io.IOException;
public class XhsFeedCoverPlayerView extends FrameLayout implements MediaController.MediaPlayerControl {
private String TAG = "XhsFeedCoverPlayerView";
private String mUrl;
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
private IRenderView.ISurfaceHolder mSurfaceHolder = null;
private IMediaPlayer mMediaPlayer = null;
private int mVideoWidth;
private int mVideoHeight;
private int mSurfaceWidth;
private int mSurfaceHeight;
private int mVideoRotationDegree;
private IMediaPlayer.OnPreparedListener mOnPreparedListener;
private IMediaPlayer.OnInfoListener mOnInfoListener;
private IMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener;
private IMediaPlayer.OnCompletionListener mOnCompletionListener;
private IMediaPlayer.OnErrorListener mOnErrorListener;
private IMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener;
private IMediaPlayer.OnStartOrPauseListener mOnStartPlayListener;
private IMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener;
private int mCurrentBufferPercentage;
private int mSeekWhenPrepared;
private boolean mCanPause = true;
private boolean mCanSeekBack = true;
private boolean mCanSeekForward = true;
private Context mAppContext;
private IRenderView mRenderView;
private int mVideoSarNum;
private int mVideoSarDen;
private final XhsPlayerSettings mSettings = new XhsPlayerSettings(getContext());
public XhsFeedCoverPlayerView(Context context) {
super(context);
initVideoView(context);
}
public XhsFeedCoverPlayerView(Context context, AttributeSet attrs) {
super(context, attrs);
initVideoView(context);
}
public XhsFeedCoverPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initVideoView(context);
}
public XhsFeedCoverPlayerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initVideoView(context);
}
private void initVideoView(Context context) {
mAppContext = context.getApplicationContext();
initRenders();
mVideoWidth = 0;
mVideoHeight = 0;
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void setRenderView(IRenderView renderView) {
if (mRenderView != null) {
if (mMediaPlayer != null) mMediaPlayer.setDisplay(null);
View renderUIView = mRenderView.getView();
mRenderView.removeRenderCallback(mSHCallback);
mRenderView = null;
removeView(renderUIView);
}
if (renderView == null) return;
mRenderView = renderView;
renderView.setAspectRatio(mCurrentAspectRatio);
if (mVideoWidth > 0 && mVideoHeight > 0) renderView.setVideoSize(mVideoWidth, mVideoHeight);
if (mVideoSarNum > 0 && mVideoSarDen > 0) {
renderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
}
View renderUIView = mRenderView.getView();
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER);
renderUIView.setLayoutParams(lp);
addView(renderUIView);
mRenderView.addRenderCallback(mSHCallback);
mRenderView.setVideoRotation(mVideoRotationDegree);
}
public void setRender() {
if (mSettings.getEnableSurfaceView()) {
SurfaceRenderView renderView = new SurfaceRenderView(getContext());
setRenderView(renderView);
} else {
TextureRenderView renderView = new TextureRenderView(getContext());
if (mMediaPlayer != null) {
renderView.getSurfaceHolder().bindToMediaPlayer(mMediaPlayer);
renderView.setVideoSize(mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());
renderView.setVideoSampleAspectRatio(mMediaPlayer.getVideoSarNum(), mMediaPlayer.getVideoSarDen());
renderView.setAspectRatio(mCurrentAspectRatio);
}
setRenderView(renderView);
}
}
public void setVideoPath(String path) {
mUrl = path;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(null);
}
}
public void switchVideo(String path) {
setVideoPath(path);
}
private void openVideo() {
if (mUrl.isEmpty() || mSurfaceHolder == null) {
return;
}
release();
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
try {
mMediaPlayer = createMediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnInfoListener(mInfoListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
mCurrentBufferPercentage = 0;
// json多档位
if (Utils.isValidJsonString(mUrl)) {
mMediaPlayer.setDataSourceJson(mAppContext, mUrl);
}
// 单个地址: 在线或本地
else {
mMediaPlayer.setDataSource(mUrl);
}
bindSurfaceHolder(mMediaPlayer, mSurfaceHolder);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
mCurrentState = STATE_PREPARING;
} catch (Exception e) {
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
}
}
private final IMediaPlayer.OnVideoSizeChangedListener mSizeChangedListener = new IMediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
mVideoSarNum = mp.getVideoSarNum();
mVideoSarDen = mp.getVideoSarDen();
if (mVideoWidth != 0 && mVideoHeight != 0) {
if (mRenderView != null) {
mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
}
requestLayout();
}
if (mOnVideoSizeChangedListener != null) {
mOnVideoSizeChangedListener.onVideoSizeChanged(mp, width, height, sarNum, sarDen);
}
}
};
private IMediaPlayer createMediaPlayer() {
IMediaPlayer mediaPlayer = mSettings.getEnableAndroidMediaPlayer() ? new AndroidMediaPlayer() : new RedMediaPlayer();
// 设置播放器使用硬解: 具体是否有硬解可用,内核来决定
mediaPlayer.setEnableMediaCodec(mSettings.getUsingMediaCodec());
// 设置视频缓存路径: 边播边下的视频缓存路径设置后无网可播播过的视频
mediaPlayer.setVideoCacheDir(Utils.INSTANCE.getVideCacheDir());
return mediaPlayer;
}
private final IMediaPlayer.OnPreparedListener mPreparedListener = new IMediaPlayer.OnPreparedListener() {
public void onPrepared(IMediaPlayer mp, RedPlayerEvent event) {
mCurrentState = STATE_PREPARED;
mTargetState = STATE_PLAYING;
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mMediaPlayer, event);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared;
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if (mVideoWidth != 0 && mVideoHeight != 0) {
if (mRenderView != null) {
mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
if (!mRenderView.shouldWaitForResize() || mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
} else {
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private final IMediaPlayer.OnCompletionListener mCompletionListener = new IMediaPlayer.OnCompletionListener() {
public void onCompletion(IMediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}
};
private final IMediaPlayer.OnInfoListener mInfoListener = new IMediaPlayer.OnInfoListener() {
public boolean onInfo(IMediaPlayer mp, int arg1, int arg2, RedPlayerEvent event) {
if (mOnInfoListener != null) {
mOnInfoListener.onInfo(mp, arg1, arg2, event);
}
switch (arg1) {
case IMediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
Log.d(TAG, "MEDIA_INFO_VIDEO_TRACK_LAGGING:");
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
Log.d(TAG, "MEDIA_INFO_VIDEO_RENDERING_START:");
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
Log.d(TAG, "MEDIA_INFO_BUFFERING_START:");
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
Log.d(TAG, "MEDIA_INFO_BUFFERING_END:");
break;
case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
Log.d(TAG, "MEDIA_INFO_NETWORK_BANDWIDTH: " + arg2);
break;
case IMediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
Log.d(TAG, "MEDIA_INFO_BAD_INTERLEAVING:");
break;
case IMediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
Log.d(TAG, "MEDIA_INFO_NOT_SEEKABLE:");
break;
case IMediaPlayer.MEDIA_INFO_METADATA_UPDATE:
Log.d(TAG, "MEDIA_INFO_METADATA_UPDATE:");
break;
case IMediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE:
Log.d(TAG, "MEDIA_INFO_UNSUPPORTED_SUBTITLE:");
break;
case IMediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT:
Log.d(TAG, "MEDIA_INFO_SUBTITLE_TIMED_OUT:");
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
mVideoRotationDegree = arg2;
Log.d(TAG, "MEDIA_INFO_VIDEO_ROTATION_CHANGED: " + arg2);
if (mRenderView != null) mRenderView.setVideoRotation(arg2);
break;
case IMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START:
Log.d(TAG, "MEDIA_INFO_AUDIO_RENDERING_START:");
break;
}
return true;
}
};
private final IMediaPlayer.OnErrorListener mErrorListener = new IMediaPlayer.OnErrorListener() {
public boolean onError(IMediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
return true;
}
};
private final IMediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new IMediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(IMediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
if (mOnBufferingUpdateListener != null) {
mOnBufferingUpdateListener.onBufferingUpdate(mp, percent);
}
}
};
private final IMediaPlayer.OnSeekCompleteListener mSeekCompleteListener = mp -> {
if (mOnSeekCompleteListener != null) {
mOnSeekCompleteListener.onSeekComplete(mp);
}
};
public void setOnPreparedListener(IMediaPlayer.OnPreparedListener l) {
mOnPreparedListener = l;
}
public void setOnCompletionListener(IMediaPlayer.OnCompletionListener l) {
mOnCompletionListener = l;
}
public void setOnErrorListener(IMediaPlayer.OnErrorListener l) {
mOnErrorListener = l;
}
public void setOnInfoListener(IMediaPlayer.OnInfoListener l) {
mOnInfoListener = l;
}
public void setOnBufferingUpdateListener(IMediaPlayer.OnBufferingUpdateListener l) {
mOnBufferingUpdateListener = l;
}
public void setOnSeekCompleteListenerListener(IMediaPlayer.OnSeekCompleteListener l) {
mOnSeekCompleteListener = l;
}
public void setOnVideoSizeChangedListener(IMediaPlayer.OnVideoSizeChangedListener l) {
mOnVideoSizeChangedListener = l;
}
public void setOnStartPlayListener(IMediaPlayer.OnStartOrPauseListener l) {
mOnStartPlayListener = l;
}
private void bindSurfaceHolder(IMediaPlayer mp, IRenderView.ISurfaceHolder holder) {
if (mp == null) return;
if (holder == null) {
mp.setDisplay(null);
return;
}
holder.bindToMediaPlayer(mp);
}
IRenderView.IRenderCallback mSHCallback = new IRenderView.IRenderCallback() {
@Override
public void onSurfaceChanged(@NonNull IRenderView.ISurfaceHolder holder, int format, int w, int h) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceChanged: unmatched render callback\n");
return;
}
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = !mRenderView.shouldWaitForResize() || (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
@Override
public void onSurfaceCreated(@NonNull IRenderView.ISurfaceHolder holder, int width, int height) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceCreated: unmatched render callback\n");
return;
}
mSurfaceHolder = holder;
if (mMediaPlayer != null) bindSurfaceHolder(mMediaPlayer, holder);
}
@Override
public void onSurfaceDestroyed(@NonNull IRenderView.ISurfaceHolder holder) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceDestroyed: unmatched render callback\n");
return;
}
mSurfaceHolder = null;
releaseWithoutStop();
}
};
public void releaseWithoutStop() {
if (mMediaPlayer != null) mMediaPlayer.setDisplay(null);
}
public void release() {
if (mMediaPlayer != null) {
mMediaPlayer.pause();
mMediaPlayer.release();
mMediaPlayer = null;
}
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(null);
}
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
if (mOnStartPlayListener != null) {
mOnStartPlayListener.onVideoStartOrPause(mMediaPlayer, true, mUrl);
}
}
mTargetState = STATE_PLAYING;
}
@Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
if (mOnStartPlayListener != null) {
mOnStartPlayListener.onVideoStartOrPause(mMediaPlayer, false, mUrl);
}
}
}
mTargetState = STATE_PAUSED;
}
public void stop() {
if (isInPlaybackState()) {
mMediaPlayer.stop();
}
}
public void setSpeed(float speed) {
if (isInPlaybackState()) {
mMediaPlayer.setSpeed(speed);
}
}
public void setVolume(float left, float right) {
if (mMediaPlayer != null) {
mMediaPlayer.setVolume(left, right);
}
}
public void setLoop(boolean isLoop) {
if (mMediaPlayer != null) {
mMediaPlayer.setLooping(isLoop);
}
}
@Override
public int getDuration() {
if (isInPlaybackState()) {
return (int) mMediaPlayer.getDuration();
}
return -1;
}
@Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
return (int) mMediaPlayer.getCurrentPosition();
}
return 0;
}
@Override
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
@Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null && mCurrentState != STATE_ERROR && mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
@Override
public boolean canPause() {
return mCanPause;
}
@Override
public boolean canSeekBackward() {
return mCanSeekBack;
}
@Override
public boolean canSeekForward() {
return mCanSeekForward;
}
@Override
public int getAudioSessionId() {
return 0;
}
public IMediaPlayer getMediaPlayer() {
return mMediaPlayer;
}
private static final int[] s_allAspectRatio = {IRenderView.AR_ASPECT_FIT_PARENT, IRenderView.AR_ASPECT_FILL_PARENT, IRenderView.AR_ASPECT_WRAP_CONTENT, IRenderView.AR_16_9_FIT_PARENT, IRenderView.AR_4_3_FIT_PARENT};
private final int mCurrentAspectRatio = s_allAspectRatio[0];
private void initRenders() {
setRender();
}
public void setViewScale(float scale) {
mRenderView.getView().setScaleX(scale);
mRenderView.getView().setScaleY(scale);
}
public void setViewTranslation(float translationX, float translationY) {
mRenderView.getView().setTranslationX(translationX);
mRenderView.getView().setTranslationY(translationY);
}
}

View File

@ -0,0 +1,577 @@
package com.xingin.openredplayer.floating;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.MediaController;
import androidx.annotation.NonNull;
import com.xingin.openredplayer.setting.XhsPlayerSettings;
import com.xingin.openredplayer.utils.Utils;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
import com.xingin.openredplayercore.core.impl.RedPlayerEvent;
import com.xingin.openredplayercore.core.impl.android.AndroidMediaPlayer;
import com.xingin.openredplayercore.core.impl.redplayer.RedMediaPlayer;
import com.xingin.openredplayercore.core.renderview.IRenderView;
import com.xingin.openredplayercore.core.renderview.SurfaceRenderView;
import com.xingin.openredplayercore.core.renderview.TextureRenderView;
import java.io.IOException;
public class XhsFloatingPlayerView extends FrameLayout implements MediaController.MediaPlayerControl {
private String TAG = "XhsFloatingPlayerView";
private String mUrl;
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
private IRenderView.ISurfaceHolder mSurfaceHolder = null;
private IMediaPlayer mMediaPlayer = null;
private int mVideoWidth;
private int mVideoHeight;
private int mSurfaceWidth;
private int mSurfaceHeight;
private int mVideoRotationDegree;
private IMediaPlayer.OnPreparedListener mOnPreparedListener;
private IMediaPlayer.OnInfoListener mOnInfoListener;
private IMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener;
private IMediaPlayer.OnCompletionListener mOnCompletionListener;
private IMediaPlayer.OnErrorListener mOnErrorListener;
private IMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener;
private IMediaPlayer.OnStartOrPauseListener mOnStartPlayListener;
private IMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener;
private int mCurrentBufferPercentage;
private int mSeekWhenPrepared;
private boolean mCanPause = true;
private boolean mCanSeekBack = true;
private boolean mCanSeekForward = true;
private Context mAppContext;
private IRenderView mRenderView;
private int mVideoSarNum;
private int mVideoSarDen;
private final XhsPlayerSettings mSettings = new XhsPlayerSettings(getContext());
public XhsFloatingPlayerView(Context context) {
super(context);
initVideoView(context);
}
public XhsFloatingPlayerView(Context context, AttributeSet attrs) {
super(context, attrs);
initVideoView(context);
}
public XhsFloatingPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initVideoView(context);
}
public XhsFloatingPlayerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initVideoView(context);
}
private void initVideoView(Context context) {
mAppContext = context.getApplicationContext();
initRenders();
mVideoWidth = 0;
mVideoHeight = 0;
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void setRenderView(IRenderView renderView) {
if (mRenderView != null) {
if (mMediaPlayer != null) mMediaPlayer.setDisplay(null);
View renderUIView = mRenderView.getView();
mRenderView.removeRenderCallback(mSHCallback);
mRenderView = null;
removeView(renderUIView);
}
if (renderView == null) return;
mRenderView = renderView;
renderView.setAspectRatio(mCurrentAspectRatio);
if (mVideoWidth > 0 && mVideoHeight > 0) renderView.setVideoSize(mVideoWidth, mVideoHeight);
if (mVideoSarNum > 0 && mVideoSarDen > 0) {
renderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
}
View renderUIView = mRenderView.getView();
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER);
renderUIView.setLayoutParams(lp);
addView(renderUIView);
mRenderView.addRenderCallback(mSHCallback);
mRenderView.setVideoRotation(mVideoRotationDegree);
}
public void setRender() {
if (mSettings.getEnableSurfaceView()) {
SurfaceRenderView renderView = new SurfaceRenderView(getContext());
setRenderView(renderView);
} else {
TextureRenderView renderView = new TextureRenderView(getContext());
if (mMediaPlayer != null) {
renderView.getSurfaceHolder().bindToMediaPlayer(mMediaPlayer);
renderView.setVideoSize(mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());
renderView.setVideoSampleAspectRatio(mMediaPlayer.getVideoSarNum(), mMediaPlayer.getVideoSarDen());
renderView.setAspectRatio(mCurrentAspectRatio);
}
setRenderView(renderView);
}
}
public void setVideoPath(String path) {
mUrl = path;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(null);
}
}
public void switchVideo(String path) {
setVideoPath(path);
}
private void openVideo() {
if (mUrl.isEmpty() || mSurfaceHolder == null) {
return;
}
release();
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
try {
mMediaPlayer = createMediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnInfoListener(mInfoListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
mCurrentBufferPercentage = 0;
// json多档位
if (Utils.isValidJsonString(mUrl)) {
mMediaPlayer.setDataSourceJson(mAppContext, mUrl);
}
// 单个地址: 在线或本地
else {
mMediaPlayer.setDataSource(mUrl);
}
bindSurfaceHolder(mMediaPlayer, mSurfaceHolder);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
mCurrentState = STATE_PREPARING;
} catch (Exception e) {
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
}
}
private final IMediaPlayer.OnVideoSizeChangedListener mSizeChangedListener = new IMediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
mVideoSarNum = mp.getVideoSarNum();
mVideoSarDen = mp.getVideoSarDen();
if (mVideoWidth != 0 && mVideoHeight != 0) {
if (mRenderView != null) {
mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
}
requestLayout();
}
if (mOnVideoSizeChangedListener != null) {
mOnVideoSizeChangedListener.onVideoSizeChanged(mp, width, height, sarNum, sarDen);
}
}
};
private IMediaPlayer createMediaPlayer() {
IMediaPlayer mediaPlayer = mSettings.getEnableAndroidMediaPlayer() ? new AndroidMediaPlayer() : new RedMediaPlayer();
// 设置播放器使用硬解: 具体是否有硬解可用,内核来决定
mediaPlayer.setEnableMediaCodec(mSettings.getUsingMediaCodec());
// 设置视频缓存路径: 边播边下的视频缓存路径设置后无网可播播过的视频
mediaPlayer.setVideoCacheDir(Utils.INSTANCE.getVideCacheDir());
return mediaPlayer;
}
private final IMediaPlayer.OnPreparedListener mPreparedListener = new IMediaPlayer.OnPreparedListener() {
public void onPrepared(IMediaPlayer mp, RedPlayerEvent event) {
mCurrentState = STATE_PREPARED;
mTargetState = STATE_PLAYING;
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mMediaPlayer, event);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared;
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if (mVideoWidth != 0 && mVideoHeight != 0) {
if (mRenderView != null) {
mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
if (!mRenderView.shouldWaitForResize() || mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
} else {
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private final IMediaPlayer.OnCompletionListener mCompletionListener = new IMediaPlayer.OnCompletionListener() {
public void onCompletion(IMediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}
};
private final IMediaPlayer.OnInfoListener mInfoListener = new IMediaPlayer.OnInfoListener() {
public boolean onInfo(IMediaPlayer mp, int arg1, int arg2, RedPlayerEvent event) {
if (mOnInfoListener != null) {
mOnInfoListener.onInfo(mp, arg1, arg2, event);
}
switch (arg1) {
case IMediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
Log.d(TAG, "MEDIA_INFO_VIDEO_TRACK_LAGGING:");
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
Log.d(TAG, "MEDIA_INFO_VIDEO_RENDERING_START:");
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
Log.d(TAG, "MEDIA_INFO_BUFFERING_START:");
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
Log.d(TAG, "MEDIA_INFO_BUFFERING_END:");
break;
case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
Log.d(TAG, "MEDIA_INFO_NETWORK_BANDWIDTH: " + arg2);
break;
case IMediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
Log.d(TAG, "MEDIA_INFO_BAD_INTERLEAVING:");
break;
case IMediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
Log.d(TAG, "MEDIA_INFO_NOT_SEEKABLE:");
break;
case IMediaPlayer.MEDIA_INFO_METADATA_UPDATE:
Log.d(TAG, "MEDIA_INFO_METADATA_UPDATE:");
break;
case IMediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE:
Log.d(TAG, "MEDIA_INFO_UNSUPPORTED_SUBTITLE:");
break;
case IMediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT:
Log.d(TAG, "MEDIA_INFO_SUBTITLE_TIMED_OUT:");
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
mVideoRotationDegree = arg2;
Log.d(TAG, "MEDIA_INFO_VIDEO_ROTATION_CHANGED: " + arg2);
if (mRenderView != null) mRenderView.setVideoRotation(arg2);
break;
case IMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START:
Log.d(TAG, "MEDIA_INFO_AUDIO_RENDERING_START:");
break;
}
return true;
}
};
private final IMediaPlayer.OnErrorListener mErrorListener = new IMediaPlayer.OnErrorListener() {
public boolean onError(IMediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
return true;
}
};
private final IMediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new IMediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(IMediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
if (mOnBufferingUpdateListener != null) {
mOnBufferingUpdateListener.onBufferingUpdate(mp, percent);
}
}
};
private final IMediaPlayer.OnSeekCompleteListener mSeekCompleteListener = mp -> {
if (mOnSeekCompleteListener != null) {
mOnSeekCompleteListener.onSeekComplete(mp);
}
};
public void setOnPreparedListener(IMediaPlayer.OnPreparedListener l) {
mOnPreparedListener = l;
}
public void setOnCompletionListener(IMediaPlayer.OnCompletionListener l) {
mOnCompletionListener = l;
}
public void setOnErrorListener(IMediaPlayer.OnErrorListener l) {
mOnErrorListener = l;
}
public void setOnInfoListener(IMediaPlayer.OnInfoListener l) {
mOnInfoListener = l;
}
public void setOnBufferingUpdateListener(IMediaPlayer.OnBufferingUpdateListener l) {
mOnBufferingUpdateListener = l;
}
public void setOnSeekCompleteListenerListener(IMediaPlayer.OnSeekCompleteListener l) {
mOnSeekCompleteListener = l;
}
public void setOnVideoSizeChangedListener(IMediaPlayer.OnVideoSizeChangedListener l) {
mOnVideoSizeChangedListener = l;
}
public void setOnStartPlayListener(IMediaPlayer.OnStartOrPauseListener l) {
mOnStartPlayListener = l;
}
private void bindSurfaceHolder(IMediaPlayer mp, IRenderView.ISurfaceHolder holder) {
if (mp == null) return;
if (holder == null) {
mp.setDisplay(null);
return;
}
holder.bindToMediaPlayer(mp);
}
IRenderView.IRenderCallback mSHCallback = new IRenderView.IRenderCallback() {
@Override
public void onSurfaceChanged(@NonNull IRenderView.ISurfaceHolder holder, int format, int w, int h) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceChanged: unmatched render callback\n");
return;
}
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = !mRenderView.shouldWaitForResize() || (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
@Override
public void onSurfaceCreated(@NonNull IRenderView.ISurfaceHolder holder, int width, int height) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceCreated: unmatched render callback\n");
return;
}
mSurfaceHolder = holder;
if (mMediaPlayer != null) bindSurfaceHolder(mMediaPlayer, holder);
else openVideo();
}
@Override
public void onSurfaceDestroyed(@NonNull IRenderView.ISurfaceHolder holder) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceDestroyed: unmatched render callback\n");
return;
}
mSurfaceHolder = null;
releaseWithoutStop();
}
};
public void releaseWithoutStop() {
if (mMediaPlayer != null) mMediaPlayer.setDisplay(null);
}
public void release() {
if (mMediaPlayer != null) {
mMediaPlayer.pause();
mMediaPlayer.release();
mMediaPlayer = null;
}
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(null);
}
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
if (mOnStartPlayListener != null) {
mOnStartPlayListener.onVideoStartOrPause(mMediaPlayer, true, mUrl);
}
}
mTargetState = STATE_PLAYING;
}
@Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
if (mOnStartPlayListener != null) {
mOnStartPlayListener.onVideoStartOrPause(mMediaPlayer, false, mUrl);
}
}
}
mTargetState = STATE_PAUSED;
}
public void stop() {
if (isInPlaybackState()) {
mMediaPlayer.stop();
}
}
public void setSpeed(float speed) {
if (isInPlaybackState()) {
mMediaPlayer.setSpeed(speed);
}
}
public void setVolume(float left, float right) {
if (mMediaPlayer != null) {
mMediaPlayer.setVolume(left, right);
}
}
public void setLoop(boolean isLoop) {
if (mMediaPlayer != null) {
mMediaPlayer.setLooping(isLoop);
}
}
@Override
public int getDuration() {
if (isInPlaybackState()) {
return (int) mMediaPlayer.getDuration();
}
return -1;
}
@Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
return (int) mMediaPlayer.getCurrentPosition();
}
return 0;
}
@Override
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
@Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null && mCurrentState != STATE_ERROR && mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
@Override
public boolean canPause() {
return mCanPause;
}
@Override
public boolean canSeekBackward() {
return mCanSeekBack;
}
@Override
public boolean canSeekForward() {
return mCanSeekForward;
}
@Override
public int getAudioSessionId() {
return 0;
}
public IMediaPlayer getMediaPlayer() {
return mMediaPlayer;
}
private static final int[] s_allAspectRatio = {IRenderView.AR_ASPECT_FIT_PARENT, IRenderView.AR_ASPECT_FILL_PARENT, IRenderView.AR_ASPECT_WRAP_CONTENT, IRenderView.AR_16_9_FIT_PARENT, IRenderView.AR_4_3_FIT_PARENT};
private final int mCurrentAspectRatio = s_allAspectRatio[0];
private void initRenders() {
setRender();
}
public void setViewScale(float scale) {
mRenderView.getView().setScaleX(scale);
mRenderView.getView().setScaleY(scale);
}
public void setViewTranslation(float translationX, float translationY) {
mRenderView.getView().setTranslationX(translationX);
mRenderView.getView().setTranslationY(translationY);
}
}

View File

@ -0,0 +1,126 @@
package com.xingin.openredplayer.floating
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.xingin.openredplayer.R
import com.xingin.openredplayer.player.XhsPlayerActivity
import com.xingin.openredplayer.player.XhsVideoPlayerView
import java.io.Serializable
/**
* Small Window Service
*/
class XhsFloatingService : Service() {
companion object {
const val ACTION_SHOW_VIDEO = "action_play_video_show"
const val ACTION_HIDE_VIDEO = "action_play_video_hide"
const val INTENT_KEY_VIDEO_URLS = "video_urls"
const val INTENT_KEY_SHOW_LOADING = "video_show_loading"
var serviceHasStarted = false
}
private lateinit var floatingWindowHelper: XhsFloatingWindowHelper
private lateinit var videoPlayerLayout: View
private lateinit var videoCloseView: ImageView
private lateinit var videoFullScreenView: ImageView
private lateinit var videoPlayerView: XhsVideoPlayerView
private var videoUrl: String? = null
private var showLoading: Boolean? = null
private var mLocalBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
ACTION_SHOW_VIDEO -> {
showVideo(
intent.getStringExtra(INTENT_KEY_VIDEO_URLS),
intent.getBooleanExtra(INTENT_KEY_SHOW_LOADING, false),
)
}
ACTION_HIDE_VIDEO -> {
hideVideo()
}
else -> {}
}
}
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
serviceHasStarted = true
LocalBroadcastManager.getInstance(this).apply {
registerReceiver(mLocalBroadcastReceiver, IntentFilter(ACTION_SHOW_VIDEO))
registerReceiver(mLocalBroadcastReceiver, IntentFilter(ACTION_HIDE_VIDEO))
}
floatingWindowHelper = XhsFloatingWindowHelper(this)
val layoutInflater = LayoutInflater.from(this)
videoPlayerLayout = layoutInflater.inflate(R.layout.window_player_layout, null, false)
videoPlayerView = videoPlayerLayout.findViewById(R.id.window_video_view)
videoCloseView = videoPlayerLayout.findViewById(R.id.window_close_view)
videoFullScreenView = videoPlayerLayout.findViewById(R.id.window_full_screen_view)
videoCloseView.setOnClickListener {
hideVideo()
}
videoFullScreenView.setOnClickListener {
handleFullScreenEvent()
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
showVideo(
intent?.getStringExtra(INTENT_KEY_VIDEO_URLS),
intent?.getBooleanExtra(INTENT_KEY_SHOW_LOADING, false),
)
return super.onStartCommand(intent, flags, startId)
}
private fun showVideo(url: String?, loading: Boolean?) {
hideVideo()
videoUrl = url
showLoading = loading
videoPlayerView.setOnCompletionListener {
handleVideoPlayCompleteEvent()
}
videoPlayerView.setVideoPath(url)
floatingWindowHelper.addView(videoPlayerLayout, true)
}
private fun hideVideo() {
videoPlayerView.release()
floatingWindowHelper.removeView()
}
private fun handleVideoPlayCompleteEvent() {
videoPlayerView.seekTo(0)
videoPlayerView.start()
}
private fun handleFullScreenEvent() {
val intent = Intent(this, XhsPlayerActivity::class.java)
intent.putExtra(XhsPlayerActivity.INTENT_KEY_URLS, listOf(videoUrl) as Serializable)
intent.putExtra(XhsPlayerActivity.INTENT_KEY_SHOW_LOADING, showLoading)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
}
override fun onDestroy() {
super.onDestroy()
LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcastReceiver)
floatingWindowHelper.clear()
serviceHasStarted = false
}
}

View File

@ -0,0 +1,197 @@
package com.xingin.openredplayer.floating
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import android.widget.LinearLayout
import com.xingin.openredplayer.XhsMediaApplication
import com.xingin.openredplayer.utils.Utils.dp2px
import com.xingin.openredplayer.utils.Utils.getScreenRealHeight
import com.xingin.openredplayer.utils.Utils.getScreenRealWidth
import com.xingin.openredplayer.utils.Utils.vibrate
/** the small window controller: show, hide, drag, auto stick slide... */
class XhsFloatingWindowHelper(context: Context) {
private var windowManager: WindowManager?
private var currentView: View? = null
private var currentLayoutParams: WindowManager.LayoutParams? = null
private var stickAnimator: ValueAnimator? = null
init {
windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
/** create the small window layout params */
private fun createLayoutParams(): WindowManager.LayoutParams {
return WindowManager.LayoutParams().apply {
type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
WindowManager.LayoutParams.TYPE_PHONE
}
format = PixelFormat.RGBA_8888
gravity = Gravity.END or Gravity.BOTTOM
flags =
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
width = LinearLayout.LayoutParams.WRAP_CONTENT
height = LinearLayout.LayoutParams.WRAP_CONTENT
}
}
/** add and show the small window */
@SuppressLint("ClickableViewAccessibility")
fun addView(view: View, canMove: Boolean) {
currentView = view
currentLayoutParams = createLayoutParams()
windowManager?.addView(currentView, currentLayoutParams)
if (canMove) {
currentView?.setOnTouchListener(OnFloatingTouchListener())
}
}
/** remove and hide the small window */
fun removeView() {
windowManager?.let { windowManager ->
currentView?.let { windowManager.removeView(it) }
}
currentView = null
currentLayoutParams = null
stickAnimator?.removeAllListeners()
stickAnimator?.cancel()
stickAnimator = null
}
/** release all small window resource */
fun clear() {
windowManager?.let { windowManager ->
currentView?.let { windowManager.removeView(it) }
}
currentView = null
currentLayoutParams = null
windowManager = null
// release anim
stickAnimator?.removeAllListeners()
stickAnimator?.cancel()
stickAnimator = null
}
/** handle the small window drag event */
inner class OnFloatingTouchListener : OnTouchListener {
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> vibrate(XhsMediaApplication.instance)
MotionEvent.ACTION_MOVE -> {
val movedX = event.rawX.toInt()
val movedY = event.rawY.toInt()
currentLayoutParams?.x = calculateLayoutParamsX(movedX)
currentLayoutParams?.y = calculateLayoutParamsY(movedY)
// drag the window with the move event
windowManager?.updateViewLayout(view, currentLayoutParams)
}
MotionEvent.ACTION_UP -> {
val start = (currentLayoutParams?.x ?: 0)
val end = calculateFinalEndPosition(start = start)
// stick the small window to screen slide
stickToSide(view, start = start, end = end)
}
else -> {}
}
return view.onTouchEvent(event)
}
/** calculate the x-coordinate of the small window based on the sliding position: which is opposite to the common understanding. */
private fun calculateLayoutParamsX(startX: Int): Int {
return getScreenRealWidth() - startX - getWindowWidth() / 2
}
/** calculate the y-coordinate of the small window based on the sliding position: which is opposite to the common understanding. */
private fun calculateLayoutParamsY(startY: Int): Int {
return getScreenRealHeight() - startY - getWindowHeight() / 2
}
/** calculate whether to stick to the left or right after releasing */
private fun calculateFinalEndPosition(start: Int): Int {
return if (beyondHalfScreenWidth(start)) {
// stick to the right
getLayoutParamsMaxX()
} else {
// stick to the left
getLayoutParamsMinX()
}
}
/** animation of automatically sticking to the edge after releasing */
private fun stickToSide(view: View, start: Int, end: Int) {
stickAnimator = ValueAnimator.ofInt(start, end)
.setDuration(WINDOW_ANIM_DURATION)
.apply {
interpolator = DecelerateInterpolator()
addUpdateListener { animation: ValueAnimator ->
currentLayoutParams?.x = animation.animatedValue as Int
windowManager?.updateViewLayout(view, currentLayoutParams)
}
start()
}
}
/** get the coordinate of the leftmost point of the small window: opposite to the common understanding, it is the screen width minus the view width. */
private fun getLayoutParamsMinX(): Int {
return getScreenRealWidth() - getWindowWidth()
}
/** get the coordinate of the rightmost point of the small window: opposite to the common understanding, 0 is the rightmost point. */
private fun getLayoutParamsMaxX(): Int {
return 0
}
/** whether the current position exceeds half of the screen width: start is the current starting coordinate of the small window. */
private fun beyondHalfScreenWidth(start: Int): Boolean {
return getScreenRealWidth() - start - getWindowWidth() / 2 >= getScreenRealWidth() / 2
}
/** get the width of the small window: used for various position calculations, and the width can be dynamically set based on the video aspect ratio. */
private fun getWindowWidth(): Int {
return dp2px(120)
}
/** get the height of the small window: used for various position calculations, and the height can be dynamically set based on the video aspect ratio. */
private fun getWindowHeight(): Int {
return dp2px(215)
}
}
companion object {
const val WINDOW_ANIM_DURATION = 300L
private const val PACKAGE_NAME = "package:"
fun checkHasFloatingPermission(context: Context?): Boolean {
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
true
} else Settings.canDrawOverlays(context)
}
fun startSettingPage(context: Context) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse(PACKAGE_NAME + context.packageName)
).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
context.startActivity(intent)
}
}
}

View File

@ -0,0 +1,80 @@
package com.xingin.openredplayer.home
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.xingin.openredplayer.R
import com.xingin.openredplayer.setting.SettingsFragment
class XhsHomeActivity : AppCompatActivity() {
private lateinit var tabLayout: TabLayout
private lateinit var viewPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_xhs_home_page_layout)
initViewPager()
initTabLayout()
}
private fun initViewPager() {
viewPager = findViewById(R.id.view_pager)
val fragments: MutableList<Fragment> = ArrayList()
fragments.add(XhsHomeFragment.newInstance())
fragments.add(SettingsFragment.newInstance())
val adapter = XhsHomePagerAdapter(supportFragmentManager, fragments)
viewPager.adapter = adapter
}
@SuppressLint("UseCompatLoadingForDrawables")
private fun initTabLayout() {
tabLayout = findViewById(R.id.tab_layout)
tabLayout.setupWithViewPager(viewPager)
tabLayout.getTabAt(0)?.run {
text = getString(R.string.home)
icon = getDrawable(R.drawable.icon_home_selected)
view.isLongClickable = false
}
tabLayout.getTabAt(1)?.run {
text = getString(R.string.setting)
icon = getDrawable(R.drawable.icon_setting)
view.isLongClickable = false
}
tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.position
when (tab.position) {
0 -> {
tab.icon = getDrawable(R.drawable.icon_home_selected)
}
1 -> {
tab.icon = getDrawable(R.drawable.icon_setting_selected)
}
}
}
override fun onTabUnselected(tab: TabLayout.Tab) {
when (tab.position) {
0 -> {
tab.icon = getDrawable(R.drawable.icon_home)
}
1 -> {
tab.icon = getDrawable(R.drawable.icon_setting)
}
}
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
})
}
}

View File

@ -0,0 +1,132 @@
package com.xingin.openredplayer.home
import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.kelin.photoselector.PhotoSelector
import com.tbruyelle.rxpermissions3.RxPermissions
import com.xingin.openredplayer.R
import com.xingin.openredplayer.feed.XhsFeedActivity
import com.xingin.openredplayer.feed.model.VIDEO_ONE
import com.xingin.openredplayer.feed.model.covertToVideoUrls
import com.xingin.openredplayer.floating.XhsFloatingService
import com.xingin.openredplayer.floating.XhsFloatingWindowHelper
import com.xingin.openredplayer.input.XhsInputActivity
import com.xingin.openredplayer.player.XhsPlayerActivity
import io.reactivex.rxjava3.disposables.Disposable
import java.io.Serializable
class XhsHomeFragment : Fragment() {
private lateinit var rootView: View
private lateinit var itemUrlView: View
private lateinit var itemAlbumView: View
private lateinit var itemFeedView: View
private lateinit var itemWindowView: View
private lateinit var rxPermissions: RxPermissions
private var permissionDisposable: Disposable? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
rootView = inflater.inflate(R.layout.fragment_xhs_home_layout, null, false)
return rootView
}
override fun onDestroy() {
super.onDestroy()
permissionDisposable?.dispose()
}
private fun initView() {
itemUrlView = rootView.findViewById(R.id.layout_play_url)
itemUrlView.setOnClickListener { openInputPage() }
itemAlbumView = rootView.findViewById(R.id.layout_local_album)
itemAlbumView.setOnClickListener { openAlbumPage() }
itemFeedView = rootView.findViewById(R.id.layout_double_column)
itemFeedView.setOnClickListener { openFeedPage() }
itemWindowView = rootView.findViewById(R.id.layout_window)
itemWindowView.setOnClickListener { openWindow() }
// init permission
rxPermissions = RxPermissions(this)
}
private fun openInputPage() {
val intent = Intent(this.activity, XhsInputActivity::class.java)
startActivity(intent)
}
private fun openAlbumPage() {
permissionDisposable = rxPermissions.request(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_NETWORK_STATE,
).subscribe { granted ->
if (!granted) {
return@subscribe
}
// open the album
PhotoSelector.openVideoSelector(
this,
100,
PhotoSelector.ID_REPEATABLE
) { photos ->
if (photos?.isNotEmpty() == true) {
val intent = Intent(this.activity, XhsPlayerActivity::class.java)
intent.putExtra(
XhsPlayerActivity.INTENT_KEY_URLS,
covertToVideoUrls(photos) as Serializable
)
startActivity(intent)
}
}
}
}
private fun openFeedPage() {
val intent = Intent(this.activity, XhsFeedActivity::class.java)
startActivity(intent)
}
private fun openWindow() {
val activity = this.activity ?: return
// service has stared: play the video url
if (XhsFloatingService.serviceHasStarted) {
val intent = Intent(XhsFloatingService.ACTION_SHOW_VIDEO).apply {
putExtra(XhsFloatingService.INTENT_KEY_VIDEO_URLS, VIDEO_ONE)
putExtra(XhsFloatingService.INTENT_KEY_SHOW_LOADING, false)
}
LocalBroadcastManager.getInstance(activity).sendBroadcast(intent)
return
}
// service is not start:has permissionstart the service and then play the video url
if (XhsFloatingWindowHelper.checkHasFloatingPermission(this.activity)) {
val intent = Intent(activity, XhsFloatingService::class.java).apply {
putExtra(XhsFloatingService.INTENT_KEY_VIDEO_URLS, VIDEO_ONE)
putExtra(XhsFloatingService.INTENT_KEY_SHOW_LOADING, false)
}
activity.startService(intent)
return
}
// open the setting page and request the alert permission
XhsFloatingWindowHelper.startSettingPage(activity)
}
companion object {
fun newInstance(): XhsHomeFragment {
return XhsHomeFragment()
}
}
}

View File

@ -0,0 +1,17 @@
package com.xingin.openredplayer.home
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
class XhsHomePagerAdapter(fm: FragmentManager, private val mFragments: List<Fragment>) :
FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return mFragments[position]
}
override fun getCount(): Int {
return mFragments.size
}
}

View File

@ -0,0 +1,65 @@
package com.xingin.openredplayer.input
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.xingin.openredplayer.R
import com.xingin.openredplayer.feed.model.JSON_DATA_SOURCE
import com.xingin.openredplayer.feed.model.VIDEO_ONE
import com.xingin.openredplayer.player.XhsPlayerActivity
import java.io.Serializable
class XhsInputActivity : AppCompatActivity() {
private lateinit var backView: ImageView
private lateinit var titleView: TextView
private lateinit var editText: EditText
private lateinit var urlButton: TextView
private lateinit var jsonButton: TextView
private lateinit var clearButton: TextView
private lateinit var playButton: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_xhs_input_layout)
initView()
}
private fun initView() {
backView = findViewById(R.id.top_action_back_view)
backView.setOnClickListener {
finish()
}
titleView = findViewById(R.id.video_title_view)
titleView.setText(R.string.input_url_title)
editText = findViewById(R.id.edit_text_view)
urlButton = findViewById(R.id.url_button)
urlButton.setOnClickListener {
editText.setText(VIDEO_ONE)
}
jsonButton = findViewById(R.id.json_button)
jsonButton.setOnClickListener {
editText.setText(JSON_DATA_SOURCE)
}
playButton = findViewById(R.id.play_button)
playButton.setOnClickListener {
val url = editText.text.toString()
if (url.isEmpty()) {
return@setOnClickListener
}
val intent = Intent(this, XhsPlayerActivity::class.java)
intent.putExtra(
XhsPlayerActivity.INTENT_KEY_URLS,
listOf(url) as Serializable
)
intent.putExtra(XhsPlayerActivity.INTENT_KEY_SHOW_LOADING, true)
startActivity(intent)
}
clearButton = findViewById(R.id.clear_button)
clearButton.setOnClickListener {
editText.setText("")
}
}
}

View File

@ -0,0 +1,667 @@
package com.xingin.openredplayer.player
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xingin.openredplayer.R
import com.xingin.openredplayer.floating.XhsFloatingService
import com.xingin.openredplayer.floating.XhsFloatingWindowHelper
import com.xingin.openredplayer.player.progress.XhsProgressBar
import com.xingin.openredplayer.player.section.XhsSectionAdapter
import com.xingin.openredplayer.player.section.XhsSectionSpaceItemDecoration
import com.xingin.openredplayer.player.sensor.XhsOrientationListener
import com.xingin.openredplayer.setting.XhsPlayerSettings
import com.xingin.openredplayer.utils.Utils
import com.xingin.openredplayercore.core.api.IMediaPlayer
import kotlin.math.max
import kotlin.math.min
class XhsPlayerActivity : AppCompatActivity(), XhsSectionAdapter.OnSectionItemClickListener {
companion object {
private const val TAG = "XhsPlayerActivity"
const val INTENT_KEY_URLS = "video_urls"
const val INTENT_KEY_INDEX = "video_index"
const val INTENT_KEY_SHOW_LOADING = "show_loading"
}
/** DrawerLayout UI */
private lateinit var drawerLayout: DrawerLayout
private lateinit var drawerContentLayout: LinearLayout
private lateinit var playerContentRV: RecyclerView
private lateinit var sectionAdapter: XhsSectionAdapter
/** loading */
private lateinit var loadingView: RelativeLayout
private lateinit var backPressedCallback: OnBackPressedCallback
/** player controller UI */
private lateinit var videoPlayerView: XhsVideoPlayerView
private lateinit var videoFrameLayout: RelativeLayout
private lateinit var videoTopActionLayout: RelativeLayout
private lateinit var moreView: ImageView
private lateinit var backView: ImageView
private lateinit var shareView: ImageView
private lateinit var likeView: ImageView
private lateinit var videoBottomActionLayout: RelativeLayout
private lateinit var progressSeekBar: XhsProgressBar
private lateinit var playPauseButton: ImageView
private lateinit var playNextButton: ImageView
private lateinit var playSectionButton: TextView
private lateinit var playHVSwitchBtn: ImageView
private lateinit var lightLayout: RelativeLayout
private lateinit var lightSeekBar: XhsProgressBar
private lateinit var voiceLayout: RelativeLayout
private lateinit var voiceSeekBar: XhsProgressBar
private lateinit var speedLayout: RelativeLayout
/** debug info UI **/
private lateinit var debugContentLayout: View
private lateinit var debugInfoLayout: LinearLayout
private lateinit var debugInfoNameView: TextView
private lateinit var debugInfoValueView: TextView
private lateinit var debugInfoHideView: TextView
/** data **/
private var isShowLoading = false
private var videoUrls = arrayListOf<String>()
private var playIndex = 0
/** scale **/
private var scaleFactor = 1.0f
private var oldScaleFactor = 1.0f
private var startX = 0f
private var startY = 0f
private var maxWidthTranslation = 0f
private var mIsLandscape = false
private var downX = 0f
private var downY = 0f
private var firstTouch = true
private var changePosition = false
private var changeBrightness = false
private var changeVolume = false
private lateinit var settingConfig: XhsPlayerSettings
private lateinit var sensorManager: SensorManager
private var xhsOrientationListener: XhsOrientationListener? = null
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER
setContentView(R.layout.activity_xhs_player_layout)
initData()
initView()
tryHideSmallWindow()
}
private fun initData() {
playIndex = intent.getIntExtra(INTENT_KEY_INDEX, 0)
isShowLoading = intent.getBooleanExtra(INTENT_KEY_SHOW_LOADING, false)
val list = intent.getSerializableExtra(INTENT_KEY_URLS) as List<String>
videoUrls.addAll(list)
// init config
settingConfig = XhsPlayerSettings(this@XhsPlayerActivity)
}
private fun initView() {
initDrawerLayout()
initVideoViewScale()
initVideoProgressView()
initVideoControllerView()
initDebugInfoView()
backPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
tryShowSmallWindow()
finish()
}
}
onBackPressedDispatcher.addCallback(this, backPressedCallback)
}
/** init the gravity sensor */
private fun initSensor() {
sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
xhsOrientationListener =
XhsOrientationListener(object : XhsOrientationListener.OnOrientationChangeListener {
override fun orientationChanged(newOrientation: Int) {
// update the screen orientation
requestedOrientation = newOrientation
}
})
sensorManager.registerListener(
xhsOrientationListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL
)
}
private fun removeSensor() {
sensorManager.unregisterListener(xhsOrientationListener)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
mIsLandscape = true
// 1.0 set the activity full screen: hide the status bar
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
// 1.1 video view fill the screen width and height
videoPlayerView.requestLayout()
shareView.visibility = View.VISIBLE
likeView.visibility = View.VISIBLE
// 1.2 register the gravity sensor
initSensor()
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
mIsLandscape = false
// 1.0 restore the status bar
val attrs = window.attributes
attrs.flags = attrs.flags and WindowManager.LayoutParams.FLAG_FULLSCREEN.inv()
window.attributes = attrs
window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
// 1.1 restore the video view origin width height
videoPlayerView.requestLayout()
shareView.visibility = View.GONE
likeView.visibility = View.GONE
// 1.2 remove the gravity sensor
removeSensor()
}
}
override fun onResume() {
super.onResume()
videoPlayerView.start()
}
override fun onPause() {
super.onPause()
videoPlayerView.pause()
}
override fun onDestroy() {
super.onDestroy()
videoPlayerView.release()
backPressedCallback.isEnabled = false
}
/** pause or resume media player */
private fun pauseOrResume() {
if (videoPlayerView.isPlaying) {
videoPlayerView.pause()
playPauseButton.setBackgroundResource(R.drawable.icon_play)
} else {
videoPlayerView.start()
playPauseButton.setBackgroundResource(R.drawable.icon_pause)
}
}
/** update activity orientation */
private fun changeScreenOrientation() {
requestedOrientation = if (!mIsLandscape) {
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
} else {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
/** update the video play progress */
private fun initVideoProgressView() {
progressSeekBar = findViewById(R.id.video_view_seekbar)
progressSeekBar.setOnProgressChangedListener(object :
XhsProgressBar.OnProgressChangedListener {
override fun onProgressChanged(
signSeekBar: XhsProgressBar, progress: Int, progressFloat: Float, fromUser: Boolean
) {
}
override fun getProgressOnActionUp(
signSeekBar: XhsProgressBar, progress: Int, progressFloat: Float
) {
val percentage = progress / 1000.0
videoPlayerView.seekTo((percentage * videoPlayerView.duration).toInt())
progressSeekBar.setProgress(progressFloat)
}
override fun getProgressOnFinally(
signSeekBar: XhsProgressBar, progress: Int, progressFloat: Float, fromUser: Boolean
) {
}
})
// update the seekbar
val handler = Handler(Looper.getMainLooper())
var position: Int
var duration: Int
val updateSeekBar = object : Runnable {
override fun run() {
position = videoPlayerView.currentPosition
duration = videoPlayerView.duration
if (duration > 0) {
progressSeekBar.setProgress((1000L * position / duration).toFloat())
}
videoPlayerView.mediaPlayer?.let { updateDebugInfo(it) }
handler.postDelayed(this, 200)
}
}
handler.post(updateSeekBar)
}
/** init the media player controller and logic */
private fun initVideoControllerView() {
loadingView = findViewById(R.id.loading_layout)
loadingView.visibility = if (isShowLoading) View.VISIBLE else View.GONE
videoTopActionLayout = findViewById(R.id.player_top_action_layout)
backView = findViewById(R.id.top_action_back_view)
backView.setOnClickListener {
if (mIsLandscape) {
changeScreenOrientation()
} else {
// try show pop window and play
tryShowSmallWindow()
finish()
}
}
moreView = findViewById(R.id.top_action_more_view)
moreView.setOnClickListener {
showOrHideActionBar()
drawerLayout.openDrawer(drawerContentLayout)
}
shareView = findViewById(R.id.top_action_share_view)
likeView = findViewById(R.id.top_action_like_view)
likeView.setOnClickListener {
likeView.setBackgroundResource(R.drawable.icon_liked)
}
videoBottomActionLayout = findViewById(R.id.player_bottom_action_layout)
lightLayout = findViewById(R.id.light_layout)
lightSeekBar = findViewById(R.id.battery_seek_bar)
voiceLayout = findViewById(R.id.voice_layout)
voiceSeekBar = findViewById(R.id.voice_seek_bar)
speedLayout = findViewById(R.id.seep_layout)
playPauseButton = findViewById(R.id.play_pause_button)
playNextButton = findViewById(R.id.play_next_button)
playSectionButton = findViewById(R.id.video_section_view)
playHVSwitchBtn = findViewById(R.id.video_screen_switch_btn)
playHVSwitchBtn.setOnClickListener {
changeScreenOrientation()
}
playPauseButton.setOnClickListener {
pauseOrResume()
}
playNextButton.setOnClickListener {
playNext()
}
playSectionButton.setOnClickListener {
showOrHideActionBar()
drawerLayout.openDrawer(drawerContentLayout)
}
videoPlayerView = findViewById(R.id.single_video_view)
// 1.0 set the media player necessary listener
videoPlayerView.setOnPreparedListener { mp, event -> handleVideoPreparedEvent(mp) }
videoPlayerView.setOnInfoListener { mp, what, extra, event ->
handleVideoInfoEvent(what, extra)
}
videoPlayerView.setOnSeekCompleteListenerListener { handleVideoSeekCompleteEvent() }
videoPlayerView.setOnStartPlayListener { _, isPlaying, url ->
handleVideoStartPlayEvent(isPlaying, url)
}
videoPlayerView.setOnBufferingUpdateListener { _, _ -> handleVideoBufferingUpdateEvent() }
videoPlayerView.setOnVideoSizeChangedListener { _, width, height, sar_num, sar_den ->
handleVideoSizeChangedEvent(width, height)
}
videoPlayerView.setOnCompletionListener {
playPauseButton.setBackgroundResource(R.drawable.icon_play)
handleVideoPlayCompleteEvent()
}
videoPlayerView.setOnErrorListener { _, what, extra -> handleVideoErrorEvent(what, extra) }
// 1.1 set the video url and wait play
videoPlayerView.setVideoPath(getCurrentPlayUrl())
}
/** init the video debug info view */
private fun initDebugInfoView() {
debugContentLayout = findViewById(R.id.debug_info_layout)
debugInfoLayout = findViewById(R.id.debug_content_view)
debugInfoHideView = findViewById(R.id.debug_show_or_hide_btn)
debugInfoHideView.setOnClickListener {
debugInfoLayout.visibility = if (debugInfoLayout.isVisible) View.GONE else View.VISIBLE
}
debugInfoNameView = findViewById(R.id.player_debug_info_name_view)
debugInfoValueView = findViewById(R.id.player_debug_info_value_view)
debugContentLayout.visibility =
if (settingConfig.enableDebugInfoView) View.VISIBLE else View.GONE
}
private fun getCurrentPlayUrl(): String {
val index = playIndex % videoUrls.size
return videoUrls[index]
}
/** init the side layout */
private fun initDrawerLayout() {
drawerLayout = findViewById(R.id.player_drawer_layout)
drawerLayout.setScrimColor(Color.TRANSPARENT)
drawerContentLayout = findViewById(R.id.player_drawer_content_layout)
playerContentRV = findViewById(R.id.player_content_recyclerview)
playerContentRV.layoutManager = LinearLayoutManager(this)
playerContentRV.addItemDecoration(XhsSectionSpaceItemDecoration(Utils.dp2px(5)))
sectionAdapter = XhsSectionAdapter(this, videoUrls, getCurrentPlayUrl())
playerContentRV.adapter = sectionAdapter
playerContentRV.itemAnimator = null
playerContentRV.setHasFixedSize(true)
playerContentRV.addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {})
sectionAdapter.setOnSectionItemClickListener(this)
}
override fun onClick(holder: RecyclerView.ViewHolder?, position: Int, model: String?) {
drawerLayout.closeDrawer(drawerContentLayout)
playPosition(position)
}
@SuppressLint("ClickableViewAccessibility")
private fun initVideoViewScale() {
videoFrameLayout = findViewById(R.id.video_frame_layout)
val scaleGestureDetector = ScaleGestureDetector(
this,
object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
oldScaleFactor = scaleFactor
scaleFactor *= detector.scaleFactor
scaleFactor = max(1.0f, min(scaleFactor, 5.0f))
videoPlayerView.setViewScale(scaleFactor)
return true
}
})
val gestureDetector =
GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
downX = e.x
downY = e.y
firstTouch = true
changePosition = false
changeBrightness = false
changeVolume = false
return true
}
override fun onScroll(
e1: MotionEvent?, e2: MotionEvent, distanceX: Float, distanceY: Float
): Boolean {
if (scaleFactor != 1.0f) {
startX -= distanceX
startY -= distanceY
maxWidthTranslation = videoPlayerView.width * (scaleFactor - 1.0F) / 2
startX = max(-maxWidthTranslation, min(maxWidthTranslation, startX))
startY =
max(-maxWidthTranslation * 2, min(maxWidthTranslation * 2, startY))
videoPlayerView.setViewTranslation(startX, startY)
return true
}
if (e1?.pointerCount == 1 && e2.pointerCount == 1) {
handleChangeVolumeOrBrightness(downX - e2.x, downY - e2.y)
}
return true
}
override fun onLongPress(e: MotionEvent) {
handleVideoSpeedPlay(settingConfig.getVideoPlayerSpeed, true)
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
showOrHideActionBar()
return true
}
})
videoFrameLayout.setOnTouchListener { _, event ->
scaleGestureDetector.onTouchEvent(event)
gestureDetector.onTouchEvent(event)
if (event.action == MotionEvent.ACTION_UP) {
handleVideoSpeedPlay(1.0f, false)
voiceLayout.visibility = View.GONE
lightLayout.visibility = View.GONE
downX = 0f
downY = 0f
firstTouch = false
changePosition = false
changeBrightness = false
changeVolume = false
}
true
}
}
private fun handleChangeVolumeOrBrightness(deltaX: Float, deltaY: Float) {
if (firstTouch) {
when {
Utils.beyondHalfScreenWidth(this@XhsPlayerActivity, downX) -> {
changeVolume = true
}
else -> {
changeBrightness = true
}
}
firstTouch = false
}
when {
changeBrightness -> {
Utils.slideToChangeBrightness(this@XhsPlayerActivity, deltaY) { progress, max ->
showLightLayout(progress!!, max!!)
}
}
changeVolume -> {
Utils.slideToChangeVolume(this@XhsPlayerActivity, deltaY) { progress, max ->
showVoiceLayout(progress!!, max!!)
}
}
}
}
/** play next video */
private fun playNext() {
playIndex += 1
if (playIndex > (videoUrls.size - 1)) {
playIndex = 0
}
videoPlayerView.switchVideo(getCurrentPlayUrl())
}
/** play the special index video */
private fun playPosition(index: Int) {
playIndex = index
videoPlayerView.switchVideo(getCurrentPlayUrl())
}
private fun showOrHideActionBar() {
if (videoBottomActionLayout.isVisible) {
videoBottomActionLayout.visibility = View.GONE
videoTopActionLayout.visibility = View.GONE
debugContentLayout.visibility = View.GONE
} else {
videoBottomActionLayout.visibility = View.VISIBLE
videoTopActionLayout.visibility = View.VISIBLE
// 由配置控制是否可见
debugContentLayout.visibility =
if (settingConfig.enableDebugInfoView) View.VISIBLE else View.GONE
}
}
private fun showVoiceLayout(progress: Int, max: Int) {
voiceLayout.visibility = View.VISIBLE
voiceSeekBar.setProgress(progress.toFloat())
}
private fun showLightLayout(progress: Int, max: Int) {
lightLayout.visibility = View.VISIBLE
lightSeekBar.setProgress(progress.toFloat())
}
/** update the debug info */
private fun updateDebugInfo(mediaPlayer: IMediaPlayer) {
val debugInfo =
Utils.getVideoDebugInfo(this, mediaPlayer, settingConfig.enableSurfaceView)
debugInfoNameView.text = debugInfo.first
debugInfoValueView.text = debugInfo.second
}
/** handle the media player prepared event */
private fun handleVideoPreparedEvent(mediaPlayer: IMediaPlayer) {
Log.d(TAG, "the media player is ready, can start.")
}
/** handle video speed play: support 0.751.01.251.52.0 */
private fun handleVideoSpeedPlay(speed: Float, isShow: Boolean) {
if (!videoPlayerView.isPlaying) {
return
}
videoPlayerView.setSpeed(speed)
if (isShow) {
speedLayout.visibility = View.VISIBLE
Utils.vibrate(this@XhsPlayerActivity)
} else {
speedLayout.visibility = View.GONE
}
}
/** handle video play complete event */
private fun handleVideoPlayCompleteEvent() {
videoPlayerView.seekTo(0)
handleVideoSpeedPlay(1.0f, false)
voiceLayout.visibility = View.GONE
lightLayout.visibility = View.GONE
speedLayout.visibility = View.GONE
val autoPlayNext =
settingConfig.enableVideoAutoPlayerNext && settingConfig.enableVideoAutoLoop
val autoLoop = settingConfig.enableVideoAutoLoop
when {
autoPlayNext -> {
playNext()
}
autoLoop -> {
videoPlayerView.start()
}
}
}
/** handle video size change event */
private fun handleVideoSizeChangedEvent(width: Int, height: Int) {
Log.d(TAG, "the new video width is:$width, height is: $height")
}
private fun handleVideoErrorEvent(what: Int, extra: Int): Boolean {
Log.d(TAG, "the video errorCode is:$what, errorMsg is: $extra")
return false
}
/** handle video seek complete event */
private fun handleVideoSeekCompleteEvent() {
Log.d(TAG, "the current video progress is: ${videoPlayerView.currentPosition}")
}
/** handle media player start event */
private fun handleVideoStartPlayEvent(isPlaying: Boolean, url: String) {
if (isPlaying) {
playPauseButton.setBackgroundResource(R.drawable.icon_pause)
sectionAdapter.updateCurrentPlayUrl(url)
} else {
playPauseButton.setBackgroundResource(R.drawable.icon_play)
}
// 开播后隐藏loading布局
loadingView.visibility = View.GONE
}
private fun handleVideoBufferingUpdateEvent() {}
/** handle media player from prepare to play all event */
private fun handleVideoInfoEvent(what: Int, extra: Int): Boolean {
when (what) {
// video stream connection success event
IMediaPlayer.MEDIA_INFO_OPEN_INPUT -> {
// videoTrackManager.onDidConnect(event?.tcpCount ?: 0L, currTime)
}
// video format check finished event
IMediaPlayer.MEDIA_INFO_FIND_STREAM_INFO -> {
// videoTrackManager.onStreamInfoFound(currTime)
}
// media codec init event
IMediaPlayer.MEDIA_INFO_COMPONENT_OPEN -> {
// videoTrackManager.onComponentOpen(currTime)
}
// first video package input the codec event
IMediaPlayer.MEDIA_INFO_VIDEO_FIRST_PACKET_IN_DECODER -> {
// videoTrackManager.onPlayerFirstPacketInDecoder(currTime)
}
// video first frame decode finished event
IMediaPlayer.MEDIA_INFO_VIDEO_DECODED_START -> {
// videoTrackManager.onPlayerDecodedStart(currTime)
}
// video first frame render success event
IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> {
// videoTrackManager.onPlayerRenderStart(extra == 0, currTime)
}
// video start playing event
IMediaPlayer.MEDIA_INFO_VIDEO_START_ON_PLAYING -> {
// videoTrackManager.onVideoStartOnPlaying(currTime)
}
}
return true
}
/** try show small window */
private fun tryShowSmallWindow() {
if (XhsFloatingService.serviceHasStarted) {
val intent = Intent(XhsFloatingService.ACTION_SHOW_VIDEO).apply {
putExtra(XhsFloatingService.INTENT_KEY_VIDEO_URLS, getCurrentPlayUrl())
putExtra(XhsFloatingService.INTENT_KEY_SHOW_LOADING, isShowLoading)
}
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
return
}
if (XhsFloatingWindowHelper.checkHasFloatingPermission(this)) {
val intent = Intent(this, XhsFloatingService::class.java).apply {
putExtra(XhsFloatingService.INTENT_KEY_VIDEO_URLS, getCurrentPlayUrl())
putExtra(XhsFloatingService.INTENT_KEY_SHOW_LOADING, isShowLoading)
}
startService(intent)
return
}
}
private fun tryHideSmallWindow() {
if (XhsFloatingService.serviceHasStarted) {
LocalBroadcastManager.getInstance(this)
.sendBroadcast(Intent(XhsFloatingService.ACTION_HIDE_VIDEO))
}
}
}

View File

@ -0,0 +1,577 @@
package com.xingin.openredplayer.player;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.MediaController;
import androidx.annotation.NonNull;
import com.xingin.openredplayer.setting.XhsPlayerSettings;
import com.xingin.openredplayercore.core.impl.android.AndroidMediaPlayer;
import com.xingin.openredplayercore.core.renderview.IRenderView;
import com.xingin.openredplayercore.core.renderview.SurfaceRenderView;
import com.xingin.openredplayercore.core.renderview.TextureRenderView;
import com.xingin.openredplayer.utils.Utils;
import com.xingin.openredplayercore.core.api.IMediaPlayer;
import com.xingin.openredplayercore.core.impl.RedPlayerEvent;
import com.xingin.openredplayercore.core.impl.redplayer.RedMediaPlayer;
import java.io.IOException;
public class XhsVideoPlayerView extends FrameLayout implements MediaController.MediaPlayerControl {
private String TAG = "VideoPlayerView";
private String mUrl;
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
private IRenderView.ISurfaceHolder mSurfaceHolder = null;
private IMediaPlayer mMediaPlayer = null;
private int mVideoWidth;
private int mVideoHeight;
private int mSurfaceWidth;
private int mSurfaceHeight;
private int mVideoRotationDegree;
private IMediaPlayer.OnPreparedListener mOnPreparedListener;
private IMediaPlayer.OnInfoListener mOnInfoListener;
private IMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener;
private IMediaPlayer.OnCompletionListener mOnCompletionListener;
private IMediaPlayer.OnErrorListener mOnErrorListener;
private IMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener;
private IMediaPlayer.OnStartOrPauseListener mOnStartPlayListener;
private IMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener;
private int mCurrentBufferPercentage;
private int mSeekWhenPrepared;
private boolean mCanPause = true;
private boolean mCanSeekBack = true;
private boolean mCanSeekForward = true;
private Context mAppContext;
private IRenderView mRenderView;
private int mVideoSarNum;
private int mVideoSarDen;
private final XhsPlayerSettings mSettings = new XhsPlayerSettings(getContext());
public XhsVideoPlayerView(Context context) {
super(context);
initVideoView(context);
}
public XhsVideoPlayerView(Context context, AttributeSet attrs) {
super(context, attrs);
initVideoView(context);
}
public XhsVideoPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initVideoView(context);
}
public XhsVideoPlayerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initVideoView(context);
}
private void initVideoView(Context context) {
mAppContext = context.getApplicationContext();
initRenders();
mVideoWidth = 0;
mVideoHeight = 0;
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void setRenderView(IRenderView renderView) {
if (mRenderView != null) {
if (mMediaPlayer != null) mMediaPlayer.setDisplay(null);
View renderUIView = mRenderView.getView();
mRenderView.removeRenderCallback(mSHCallback);
mRenderView = null;
removeView(renderUIView);
}
if (renderView == null) return;
mRenderView = renderView;
renderView.setAspectRatio(mCurrentAspectRatio);
if (mVideoWidth > 0 && mVideoHeight > 0) renderView.setVideoSize(mVideoWidth, mVideoHeight);
if (mVideoSarNum > 0 && mVideoSarDen > 0) {
renderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
}
View renderUIView = mRenderView.getView();
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER);
renderUIView.setLayoutParams(lp);
addView(renderUIView);
mRenderView.addRenderCallback(mSHCallback);
mRenderView.setVideoRotation(mVideoRotationDegree);
}
public void setRender() {
if (mSettings.getEnableSurfaceView()) {
SurfaceRenderView renderView = new SurfaceRenderView(getContext());
setRenderView(renderView);
} else {
TextureRenderView renderView = new TextureRenderView(getContext());
if (mMediaPlayer != null) {
renderView.getSurfaceHolder().bindToMediaPlayer(mMediaPlayer);
renderView.setVideoSize(mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight());
renderView.setVideoSampleAspectRatio(mMediaPlayer.getVideoSarNum(), mMediaPlayer.getVideoSarDen());
renderView.setAspectRatio(mCurrentAspectRatio);
}
setRenderView(renderView);
}
}
public void setVideoPath(String path) {
mUrl = path;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(null);
}
}
public void switchVideo(String path) {
setVideoPath(path);
}
private void openVideo() {
if (mUrl.isEmpty() || mSurfaceHolder == null) {
return;
}
release();
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
try {
mMediaPlayer = createMediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnInfoListener(mInfoListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
mCurrentBufferPercentage = 0;
// json多档位
if (Utils.isValidJsonString(mUrl)) {
mMediaPlayer.setDataSourceJson(mAppContext, mUrl);
}
// 单个地址: 在线或本地
else {
mMediaPlayer.setDataSource(mUrl);
}
bindSurfaceHolder(mMediaPlayer, mSurfaceHolder);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
mCurrentState = STATE_PREPARING;
} catch (Exception e) {
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
}
}
private final IMediaPlayer.OnVideoSizeChangedListener mSizeChangedListener = new IMediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
mVideoSarNum = mp.getVideoSarNum();
mVideoSarDen = mp.getVideoSarDen();
if (mVideoWidth != 0 && mVideoHeight != 0) {
if (mRenderView != null) {
mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
}
requestLayout();
}
if (mOnVideoSizeChangedListener != null) {
mOnVideoSizeChangedListener.onVideoSizeChanged(mp, width, height, sarNum, sarDen);
}
}
};
private IMediaPlayer createMediaPlayer() {
IMediaPlayer mediaPlayer = mSettings.getEnableAndroidMediaPlayer() ? new AndroidMediaPlayer() : new RedMediaPlayer();
// 设置播放器使用硬解: 具体是否有硬解可用,内核来决定
mediaPlayer.setEnableMediaCodec(mSettings.getUsingMediaCodec());
// 设置视频缓存路径: 边播边下的视频缓存路径设置后无网可播播过的视频
mediaPlayer.setVideoCacheDir(Utils.INSTANCE.getVideCacheDir());
return mediaPlayer;
}
private final IMediaPlayer.OnPreparedListener mPreparedListener = new IMediaPlayer.OnPreparedListener() {
public void onPrepared(IMediaPlayer mp, RedPlayerEvent event) {
mCurrentState = STATE_PREPARED;
mTargetState = STATE_PLAYING;
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mMediaPlayer, event);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared;
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if (mVideoWidth != 0 && mVideoHeight != 0) {
if (mRenderView != null) {
mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
if (!mRenderView.shouldWaitForResize() || mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
} else {
if (mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private final IMediaPlayer.OnCompletionListener mCompletionListener = new IMediaPlayer.OnCompletionListener() {
public void onCompletion(IMediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}
};
private final IMediaPlayer.OnInfoListener mInfoListener = new IMediaPlayer.OnInfoListener() {
public boolean onInfo(IMediaPlayer mp, int arg1, int arg2, RedPlayerEvent event) {
if (mOnInfoListener != null) {
mOnInfoListener.onInfo(mp, arg1, arg2, event);
}
switch (arg1) {
case IMediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
Log.d(TAG, "MEDIA_INFO_VIDEO_TRACK_LAGGING:");
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
Log.d(TAG, "MEDIA_INFO_VIDEO_RENDERING_START:");
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
Log.d(TAG, "MEDIA_INFO_BUFFERING_START:");
break;
case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
Log.d(TAG, "MEDIA_INFO_BUFFERING_END:");
break;
case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
Log.d(TAG, "MEDIA_INFO_NETWORK_BANDWIDTH: " + arg2);
break;
case IMediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
Log.d(TAG, "MEDIA_INFO_BAD_INTERLEAVING:");
break;
case IMediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
Log.d(TAG, "MEDIA_INFO_NOT_SEEKABLE:");
break;
case IMediaPlayer.MEDIA_INFO_METADATA_UPDATE:
Log.d(TAG, "MEDIA_INFO_METADATA_UPDATE:");
break;
case IMediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE:
Log.d(TAG, "MEDIA_INFO_UNSUPPORTED_SUBTITLE:");
break;
case IMediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT:
Log.d(TAG, "MEDIA_INFO_SUBTITLE_TIMED_OUT:");
break;
case IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
mVideoRotationDegree = arg2;
Log.d(TAG, "MEDIA_INFO_VIDEO_ROTATION_CHANGED: " + arg2);
if (mRenderView != null) mRenderView.setVideoRotation(arg2);
break;
case IMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START:
Log.d(TAG, "MEDIA_INFO_AUDIO_RENDERING_START:");
break;
}
return true;
}
};
private final IMediaPlayer.OnErrorListener mErrorListener = new IMediaPlayer.OnErrorListener() {
public boolean onError(IMediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
return true;
}
};
private final IMediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new IMediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(IMediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
if (mOnBufferingUpdateListener != null) {
mOnBufferingUpdateListener.onBufferingUpdate(mp, percent);
}
}
};
private final IMediaPlayer.OnSeekCompleteListener mSeekCompleteListener = mp -> {
if (mOnSeekCompleteListener != null) {
mOnSeekCompleteListener.onSeekComplete(mp);
}
};
public void setOnPreparedListener(IMediaPlayer.OnPreparedListener l) {
mOnPreparedListener = l;
}
public void setOnCompletionListener(IMediaPlayer.OnCompletionListener l) {
mOnCompletionListener = l;
}
public void setOnErrorListener(IMediaPlayer.OnErrorListener l) {
mOnErrorListener = l;
}
public void setOnInfoListener(IMediaPlayer.OnInfoListener l) {
mOnInfoListener = l;
}
public void setOnBufferingUpdateListener(IMediaPlayer.OnBufferingUpdateListener l) {
mOnBufferingUpdateListener = l;
}
public void setOnSeekCompleteListenerListener(IMediaPlayer.OnSeekCompleteListener l) {
mOnSeekCompleteListener = l;
}
public void setOnVideoSizeChangedListener(IMediaPlayer.OnVideoSizeChangedListener l) {
mOnVideoSizeChangedListener = l;
}
public void setOnStartPlayListener(IMediaPlayer.OnStartOrPauseListener l) {
mOnStartPlayListener = l;
}
private void bindSurfaceHolder(IMediaPlayer mp, IRenderView.ISurfaceHolder holder) {
if (mp == null) return;
if (holder == null) {
mp.setDisplay(null);
return;
}
holder.bindToMediaPlayer(mp);
}
IRenderView.IRenderCallback mSHCallback = new IRenderView.IRenderCallback() {
@Override
public void onSurfaceChanged(@NonNull IRenderView.ISurfaceHolder holder, int format, int w, int h) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceChanged: unmatched render callback\n");
return;
}
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = !mRenderView.shouldWaitForResize() || (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
@Override
public void onSurfaceCreated(@NonNull IRenderView.ISurfaceHolder holder, int width, int height) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceCreated: unmatched render callback\n");
return;
}
mSurfaceHolder = holder;
if (mMediaPlayer != null) bindSurfaceHolder(mMediaPlayer, holder);
else openVideo();
}
@Override
public void onSurfaceDestroyed(@NonNull IRenderView.ISurfaceHolder holder) {
if (holder.getRenderView() != mRenderView) {
Log.e(TAG, "onSurfaceDestroyed: unmatched render callback\n");
return;
}
mSurfaceHolder = null;
releaseWithoutStop();
}
};
public void releaseWithoutStop() {
if (mMediaPlayer != null) mMediaPlayer.setDisplay(null);
}
public void release() {
if (mMediaPlayer != null) {
mMediaPlayer.pause();
mMediaPlayer.release();
mMediaPlayer = null;
}
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
AudioManager am = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);
am.abandonAudioFocus(null);
}
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
if (mOnStartPlayListener != null) {
mOnStartPlayListener.onVideoStartOrPause(mMediaPlayer, true, mUrl);
}
}
mTargetState = STATE_PLAYING;
}
@Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
if (mOnStartPlayListener != null) {
mOnStartPlayListener.onVideoStartOrPause(mMediaPlayer, false, mUrl);
}
}
}
mTargetState = STATE_PAUSED;
}
public void stop() {
if (isInPlaybackState()) {
mMediaPlayer.stop();
}
}
public void setSpeed(float speed) {
if (isInPlaybackState()) {
mMediaPlayer.setSpeed(speed);
}
}
public void setVolume(float left, float right) {
if (mMediaPlayer != null) {
mMediaPlayer.setVolume(left, right);
}
}
public void setLoop(boolean isLoop) {
if (mMediaPlayer != null) {
mMediaPlayer.setLooping(isLoop);
}
}
@Override
public int getDuration() {
if (isInPlaybackState()) {
return (int) mMediaPlayer.getDuration();
}
return -1;
}
@Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
return (int) mMediaPlayer.getCurrentPosition();
}
return 0;
}
@Override
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
@Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null && mCurrentState != STATE_ERROR && mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
@Override
public boolean canPause() {
return mCanPause;
}
@Override
public boolean canSeekBackward() {
return mCanSeekBack;
}
@Override
public boolean canSeekForward() {
return mCanSeekForward;
}
@Override
public int getAudioSessionId() {
return 0;
}
public IMediaPlayer getMediaPlayer() {
return mMediaPlayer;
}
private static final int[] s_allAspectRatio = {IRenderView.AR_ASPECT_FIT_PARENT, IRenderView.AR_ASPECT_FILL_PARENT, IRenderView.AR_ASPECT_WRAP_CONTENT, IRenderView.AR_16_9_FIT_PARENT, IRenderView.AR_4_3_FIT_PARENT};
private final int mCurrentAspectRatio = s_allAspectRatio[0];
private void initRenders() {
setRender();
}
public void setViewScale(float scale) {
mRenderView.getView().setScaleX(scale);
mRenderView.getView().setScaleY(scale);
}
public void setViewTranslation(float translationX, float translationY) {
mRenderView.getView().setTranslationX(translationX);
mRenderView.getView().setTranslationY(translationY);
}
}

View File

@ -0,0 +1,486 @@
package com.xingin.openredplayer.player.progress;
import androidx.annotation.ColorInt;
import androidx.annotation.IntRange;
import java.text.NumberFormat;
public class XhsProgressBuilder {
float min;
float max;
float progress;
boolean floatType;
int trackSize;
int secondTrackSize;
int thumbRadius;
int thumbRadiusOnDragging;
int trackColor;
int secondTrackColor;
int thumbColor;
int sectionCount;
boolean showSectionMark;
boolean autoAdjustSectionMark;
boolean showSectionText;
int sectionTextSize;
int sectionTextColor;
@XhsProgressBar.TextPosition
int sectionTextPosition;
int sectionTextInterval;
boolean showThumbText;
int thumbTextSize;
int thumbTextColor;
boolean showProgressInFloat;
long animDuration;
boolean touchToSeek;
boolean seekBySection;
int signColor;
int signTextSize;
int signTextColor;
boolean showSign;
String[] bottomSidesLabels;
float thumbBgAlpha; // alpha of thumb shadow
float thumbRatio; // ratio of thumb shadow
boolean showThumbShadow;
XhsProgressBar mSignSeekBar;
String unit;
int signArrowHeight;
int signArrowWidth;
int signRound;
int signHeight; //sign Height
int signWidth; //sign width
int signBorderSize; // border size
boolean showSignBorder; // show sign border
boolean signArrowAutofloat;
int signBorderColor;// color of border color
NumberFormat format;
boolean reverse;
XhsProgressBuilder(XhsProgressBar xhsSeekBar) {
mSignSeekBar = xhsSeekBar;
}
public void build() {
mSignSeekBar.config(this);
}
public XhsProgressBuilder min(float min) {
this.min = min;
this.progress = min;
return this;
}
public XhsProgressBuilder max(float max) {
this.max = max;
return this;
}
public XhsProgressBuilder progress(float progress) {
this.progress = progress;
return this;
}
public XhsProgressBuilder floatType() {
this.floatType = true;
return this;
}
public XhsProgressBuilder trackSize(int dp) {
this.trackSize = XhsProgressUtils.dp2px(dp);
return this;
}
public XhsProgressBuilder secondTrackSize(int dp) {
this.secondTrackSize = XhsProgressUtils.dp2px(dp);
return this;
}
public XhsProgressBuilder thumbRadius(int dp) {
this.thumbRadius = XhsProgressUtils.dp2px(dp);
return this;
}
public XhsProgressBuilder thumbRadiusOnDragging(int dp) {
this.thumbRadiusOnDragging = XhsProgressUtils.dp2px(dp);
return this;
}
public XhsProgressBuilder trackColor(@ColorInt int color) {
this.trackColor = color;
this.sectionTextColor = color;
return this;
}
public XhsProgressBuilder secondTrackColor(@ColorInt int color) {
this.secondTrackColor = color;
this.thumbColor = color;
this.thumbTextColor = color;
this.signColor = color;
return this;
}
public XhsProgressBuilder thumbColor(@ColorInt int color) {
this.thumbColor = color;
return this;
}
public XhsProgressBuilder sectionCount(@IntRange(from = 1) int count) {
this.sectionCount = count;
return this;
}
public XhsProgressBuilder showSectionMark() {
this.showSectionMark = true;
return this;
}
public XhsProgressBuilder autoAdjustSectionMark() {
this.autoAdjustSectionMark = true;
return this;
}
public XhsProgressBuilder showSectionText() {
this.showSectionText = true;
return this;
}
public XhsProgressBuilder sectionTextSize(int sp) {
this.sectionTextSize = XhsProgressUtils.sp2px(sp);
return this;
}
public XhsProgressBuilder sectionTextColor(@ColorInt int color) {
this.sectionTextColor = color;
return this;
}
public XhsProgressBuilder sectionTextPosition(@XhsProgressBar.TextPosition int position) {
this.sectionTextPosition = position;
return this;
}
public XhsProgressBuilder sectionTextInterval(@IntRange(from = 1) int interval) {
this.sectionTextInterval = interval;
return this;
}
public XhsProgressBuilder showThumbText() {
this.showThumbText = true;
return this;
}
public XhsProgressBuilder thumbTextSize(int sp) {
this.thumbTextSize = XhsProgressUtils.sp2px(sp);
return this;
}
public XhsProgressBuilder thumbTextColor(@ColorInt int color) {
thumbTextColor = color;
return this;
}
public XhsProgressBuilder showProgressInFloat() {
this.showProgressInFloat = true;
return this;
}
public XhsProgressBuilder animDuration(long duration) {
animDuration = duration;
return this;
}
public XhsProgressBuilder touchToSeek() {
this.touchToSeek = true;
return this;
}
public XhsProgressBuilder seekBySection() {
this.seekBySection = true;
return this;
}
public XhsProgressBuilder bottomSidesLabels(String[] bottomSidesLabels) {
this.bottomSidesLabels = bottomSidesLabels;
return this;
}
public XhsProgressBuilder thumbBgAlpha(float thumbBgAlpha) {
this.thumbBgAlpha = thumbBgAlpha;
return this;
}
public XhsProgressBuilder thumbRatio(float thumbRatio) {
this.thumbRatio = thumbRatio;
return this;
}
public XhsProgressBuilder showThumbShadow(boolean showThumbShadow) {
this.showThumbShadow = showThumbShadow;
return this;
}
public XhsProgressBuilder signColor(@ColorInt int color) {
this.signColor = color;
return this;
}
public XhsProgressBuilder signTextSize(int sp) {
this.signTextSize = XhsProgressUtils.sp2px(sp);
return this;
}
public XhsProgressBuilder signTextColor(@ColorInt int color) {
this.signTextColor = color;
return this;
}
public XhsProgressBuilder showSign() {
this.showSign = true;
return this;
}
public XhsProgressBuilder signArrowHeight(int signArrowHeight) {
this.signArrowHeight = signArrowHeight;
return this;
}
public XhsProgressBuilder signArrowWidth(int signArrowWidth) {
this.signArrowWidth = signArrowWidth;
return this;
}
public XhsProgressBuilder signRound(int signRound) {
this.signRound = signRound;
return this;
}
public XhsProgressBuilder signHeight(int signHeight) {
this.signHeight = signHeight;
return this;
}
public XhsProgressBuilder signWidth(int signWidth) {
this.signWidth = signWidth;
return this;
}
public XhsProgressBuilder signBorderSize(int signBorderSize) {
this.signBorderSize = signBorderSize;
return this;
}
public XhsProgressBuilder showSignBorder(boolean showSignBorder) {
this.showSignBorder = showSignBorder;
return this;
}
public XhsProgressBuilder signBorderColor(int signBorderColor) {
this.signBorderColor = signBorderColor;
return this;
}
public XhsProgressBuilder signArrowAutofloat(boolean signArrowAutofloat) {
this.signArrowAutofloat = signArrowAutofloat;
return this;
}
public float getMin() {
return min;
}
public float getMax() {
return max;
}
public float getProgress() {
return progress;
}
public boolean isFloatType() {
return floatType;
}
public int getTrackSize() {
return trackSize;
}
public int getSecondTrackSize() {
return secondTrackSize;
}
public int getThumbRadius() {
return thumbRadius;
}
public int getThumbRadiusOnDragging() {
return thumbRadiusOnDragging;
}
public int getTrackColor() {
return trackColor;
}
public int getSecondTrackColor() {
return secondTrackColor;
}
public int getThumbColor() {
return thumbColor;
}
public int getSectionCount() {
return sectionCount;
}
public boolean isShowSectionMark() {
return showSectionMark;
}
public boolean isAutoAdjustSectionMark() {
return autoAdjustSectionMark;
}
public boolean isShowSectionText() {
return showSectionText;
}
public int getSectionTextSize() {
return sectionTextSize;
}
public int getSectionTextColor() {
return sectionTextColor;
}
public int getSectionTextPosition() {
return sectionTextPosition;
}
public int getSectionTextInterval() {
return sectionTextInterval;
}
public boolean isShowThumbText() {
return showThumbText;
}
public int getThumbTextSize() {
return thumbTextSize;
}
public int getThumbTextColor() {
return thumbTextColor;
}
public boolean isShowProgressInFloat() {
return showProgressInFloat;
}
public long getAnimDuration() {
return animDuration;
}
public boolean isTouchToSeek() {
return touchToSeek;
}
public boolean isSeekBySection() {
return seekBySection;
}
public String[] getBottomSidesLabels() {
return bottomSidesLabels;
}
public float getThumbBgAlpha() {
return thumbBgAlpha;
}
public float getThumbRatio() {
return thumbRatio;
}
public boolean isShowThumbShadow() {
return showThumbShadow;
}
public XhsProgressBuilder setUnit(String unit) {
this.unit = unit;
return this;
}
public int getSignColor() {
return signColor;
}
public int getSignTextSize() {
return signTextSize;
}
public int getSignTextColor() {
return signTextColor;
}
public boolean isshowSign() {
return showSign;
}
public String getUnit() {
return unit;
}
public int getSignArrowHeight() {
return signArrowHeight;
}
public int getSignArrowWidth() {
return signArrowWidth;
}
public int getSignRound() {
return signRound;
}
public int getSignHeight() {
return signHeight;
}
public int getSignWidth() {
return signWidth;
}
public int getSignBorderSize() {
return signBorderSize;
}
public boolean isShowSignBorder() {
return showSignBorder;
}
public int getSignBorderColor() {
return signBorderColor;
}
public boolean isSignArrowAutofloat() {
return signArrowAutofloat;
}
public XhsProgressBuilder format(NumberFormat format) {
this.format = format;
return this;
}
public NumberFormat getFormat() {
return format;
}
public boolean isReverse() {
return reverse;
}
public XhsProgressBuilder reverse() {
this.reverse = true;
return this;
}
}

View File

@ -0,0 +1,17 @@
package com.xingin.openredplayer.player.progress;
import android.content.res.Resources;
import android.util.TypedValue;
public class XhsProgressUtils {
static int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
Resources.getSystem().getDisplayMetrics());
}
static int sp2px(int sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
Resources.getSystem().getDisplayMetrics());
}
}

View File

@ -0,0 +1,62 @@
package com.xingin.openredplayer.player.section
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.xingin.openredplayer.R
class XhsSectionAdapter(
private val context: Activity,
private val models: List<String>,
private var currentUrl: String
) : RecyclerView.Adapter<XhsSectionViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): XhsSectionViewHolder {
val item =
LayoutInflater.from(parent.context).inflate(R.layout.item_section_layout, parent, false)
return XhsSectionViewHolder(item)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: XhsSectionViewHolder, position: Int) {
val model = models[position]
holder.textView.text =
context.getString(R.string.detail_play_section_item_title) + (position + 1)
if (model == currentUrl) {
holder.itemView.setBackgroundResource(R.drawable.item_corners_5_background_fb7299)
holder.textView.setTextColor(context.resources.getColor(R.color.color_FB7299))
holder.loadingIndicatorView.visibility = View.VISIBLE
} else {
holder.itemView.setBackgroundResource(R.drawable.item_corners_5_background_ffffff)
holder.textView.setTextColor(context.resources.getColor(R.color.white))
holder.loadingIndicatorView.visibility = View.GONE
}
holder.textView.setOnClickListener {
mOnItemClickListener?.onClick(holder, position, model)
}
}
override fun getItemCount(): Int {
return models.size
}
private var mOnItemClickListener: OnSectionItemClickListener? = null
fun setOnSectionItemClickListener(onItemClickListener: OnSectionItemClickListener?) {
mOnItemClickListener = onItemClickListener
}
@SuppressLint("NotifyDataSetChanged")
fun updateCurrentPlayUrl(url: String) {
currentUrl = url
notifyDataSetChanged()
}
interface OnSectionItemClickListener {
fun onClick(holder: RecyclerView.ViewHolder?, position: Int, model: String?)
}
}

Some files were not shown because too many files have changed in this diff Show More