add ffmpeg implementation

pull/7/head
Taner Sener 5 years ago
parent 3ebe1ee8ec
commit d1b916a7ab
  1. 3
      .gitignore
  2. 674
      LICENSE.GPLv3
  3. 165
      LICENSE.LGPLv3
  4. 586
      README.md
  5. 227
      android.sh
  6. 7
      android/.gitignore
  7. 2549
      android/app/Doxyfile
  8. 44
      android/app/build.gradle
  9. 16
      android/app/proguard-rules.pro
  10. 2
      android/app/src/main/AndroidManifest.xml
  11. 2
      android/app/src/main/cpp/.gitignore
  12. 69
      android/app/src/main/cpp/android_lts_support.c
  13. 945
      android/app/src/main/cpp/ffmpegkit.c
  14. 141
      android/app/src/main/cpp/ffmpegkit.h
  15. 144
      android/app/src/main/cpp/ffmpegkit_abidetect.c
  16. 75
      android/app/src/main/cpp/ffmpegkit_abidetect.h
  17. 24
      android/app/src/main/cpp/ffmpegkit_exception.c
  18. 29
      android/app/src/main/cpp/ffmpegkit_exception.h
  19. 96
      android/app/src/main/cpp/ffprobekit.c
  20. 32
      android/app/src/main/cpp/ffprobekit.h
  21. 2403
      android/app/src/main/cpp/fftools_cmdutils.c
  22. 636
      android/app/src/main/cpp/fftools_cmdutils.h
  23. 5582
      android/app/src/main/cpp/fftools_ffmpeg.c
  24. 764
      android/app/src/main/cpp/fftools_ffmpeg.h
  25. 1228
      android/app/src/main/cpp/fftools_ffmpeg_filter.c
  26. 491
      android/app/src/main/cpp/fftools_ffmpeg_hw.c
  27. 3391
      android/app/src/main/cpp/fftools_ffmpeg_opt.c
  28. 3830
      android/app/src/main/cpp/fftools_ffprobe.c
  29. 108
      android/app/src/main/java/com/arthenica/ffmpegkit/Abi.java
  30. 94
      android/app/src/main/java/com/arthenica/ffmpegkit/AbiDetect.java
  31. 62
      android/app/src/main/java/com/arthenica/ffmpegkit/AsyncFFmpegExecuteTask.java
  32. 53
      android/app/src/main/java/com/arthenica/ffmpegkit/AsyncFFprobeExecuteTask.java
  33. 48
      android/app/src/main/java/com/arthenica/ffmpegkit/AsyncGetMediaInformationTask.java
  34. 75
      android/app/src/main/java/com/arthenica/ffmpegkit/CameraSupport.java
  35. 37
      android/app/src/main/java/com/arthenica/ffmpegkit/ExecuteCallback.java
  36. 50
      android/app/src/main/java/com/arthenica/ffmpegkit/FFmpegExecution.java
  37. 274
      android/app/src/main/java/com/arthenica/ffmpegkit/FFmpegKit.java
  38. 769
      android/app/src/main/java/com/arthenica/ffmpegkit/FFmpegKitConfig.java
  39. 130
      android/app/src/main/java/com/arthenica/ffmpegkit/FFprobeKit.java
  40. 30
      android/app/src/main/java/com/arthenica/ffmpegkit/GetMediaInformationCallback.java
  41. 132
      android/app/src/main/java/com/arthenica/ffmpegkit/Level.java
  42. 30
      android/app/src/main/java/com/arthenica/ffmpegkit/LogCallback.java
  43. 66
      android/app/src/main/java/com/arthenica/ffmpegkit/LogMessage.java
  44. 208
      android/app/src/main/java/com/arthenica/ffmpegkit/MediaInformation.java
  45. 73
      android/app/src/main/java/com/arthenica/ffmpegkit/MediaInformationParser.java
  46. 273
      android/app/src/main/java/com/arthenica/ffmpegkit/Packages.java
  47. 43
      android/app/src/main/java/com/arthenica/ffmpegkit/Signal.java
  48. 180
      android/app/src/main/java/com/arthenica/ffmpegkit/Statistics.java
  49. 30
      android/app/src/main/java/com/arthenica/ffmpegkit/StatisticsCallback.java
  50. 281
      android/app/src/main/java/com/arthenica/ffmpegkit/StreamInformation.java
  51. 186
      android/app/src/test/java/com/arthenica/ffmpegkit/FFmpegKitConfigTest.java
  52. 746
      android/app/src/test/java/com/arthenica/ffmpegkit/FFmpegKitTest.java
  53. 25
      android/build.gradle
  54. 19
      android/gradle.properties
  55. BIN
      android/gradle/wrapper/gradle-wrapper.jar
  56. 5
      android/gradle/wrapper/gradle-wrapper.properties
  57. 183
      android/gradlew
  58. 103
      android/gradlew.bat
  59. 2
      android/jni/.gitignore
  60. 104
      android/jni/Android.mk
  61. 12
      android/jni/cpu-features/Android.mk
  62. 46
      android/jni/ffmpeg/Android.mk
  63. 61
      android/jni/ffmpeg/neon/Android.mk
  64. 4
      android/settings.gradle
  65. BIN
      docs/assets/ffmpeg-kit-icon-v4.png
  66. 439
      ios.sh
  67. 600
      macos.sh
  68. 10
      objc/.gitignore
  69. 2549
      objc/Doxyfile
  70. 3
      objc/Makefile.am
  71. 806
      objc/Makefile.in
  72. 1238
      objc/aclocal.m4
  73. 271
      objc/ar-lib
  74. 3
      objc/autogen.sh
  75. 348
      objc/compile
  76. 1667
      objc/config.guess
  77. 1793
      objc/config.sub
  78. 16076
      objc/configure
  79. 64
      objc/configure.ac
  80. 791
      objc/depcomp
  81. 529
      objc/install-sh
  82. 11642
      objc/libtool
  83. 11147
      objc/ltmain.sh
  84. 8364
      objc/m4/libtool.m4
  85. 437
      objc/m4/ltoptions.m4
  86. 124
      objc/m4/ltsugar.m4
  87. 23
      objc/m4/ltversion.m4
  88. 99
      objc/m4/lt~obsolete.m4
  89. 215
      objc/missing
  90. 6
      objc/src/.gitignore
  91. 51
      objc/src/ArchDetect.h
  92. 184
      objc/src/ArchDetect.m
  93. 31
      objc/src/AtomicLong.h
  94. 47
      objc/src/AtomicLong.m
  95. 26
      objc/src/ExecuteDelegate.h
  96. 35
      objc/src/FFmpegExecution.h
  97. 52
      objc/src/FFmpegExecution.m
  98. 137
      objc/src/FFmpegKit.h
  99. 310
      objc/src/FFmpegKit.m
  100. 266
      objc/src/FFmpegKitConfig.h
  101. Some files were not shown because too many files have changed in this diff Show More

3
.gitignore vendored

@ -1 +1,4 @@
/.tmp/
/*.log /*.log
/prebuilt/
.DS_Store

@ -0,0 +1,674 @@
GNU 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.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state 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 program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

@ -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.

@ -0,0 +1,586 @@
# FFmpegKit ![GitHub release](https://img.shields.io/badge/release-v4.4-blue.svg) ![Bintray](https://img.shields.io/badge/bintray-v4.4-blue.svg) ![CocoaPods](https://img.shields.io/badge/pod-v4.4-blue.svg) [![Build Status](https://travis-ci.org/tanersener/ffmpeg-kit.svg?branch=master)](https://travis-ci.org/tanersener/ffmpeg-kit)
FFmpeg kit for applications. Supports Android, iOS, tvOS.
<img src="https://github.com/tanersener/ffmpeg-kit/blob/development/docs/assets/ffmpeg-kit-icon-v4.png" width="240">
### 1. Features
- Includes both `FFmpeg` and `FFprobe`
- Use binaries available at `Github`/`JCenter`/`CocoaPods` or build your own version with external libraries you need
- Supports
- Android, iOS and tvOS
- FFmpeg `v4.4-dev` releases
- 29 external libraries
`chromaprint`, `fontconfig`, `freetype`, `fribidi`, `gmp`, `gnutls`, `kvazaar`, `lame`, `libaom`, `libass`, `libiconv`, `libilbc`, `libtheora`, `libvorbis`, `libvpx`, `libwebp`, `libxml2`, `opencore-amr`, `openh264`, `opus`, `sdl`, `shine`, `snappy`, `soxr`, `speex`, `tesseract`, `twolame`, `vo-amrwbenc`, `wavpack`
- 5 external libraries with GPL license
`rubberband`, `vid.stab`, `x264`, `x265`, `xvidcore`
- Concurrent execution
- Exposes both FFmpeg library and FFmpegKit wrapper library capabilities
- Includes cross-compile instructions for 47 open-source libraries
`chromaprint`, `expat`, `ffmpeg`, `fontconfig`, `freetype`, `fribidi`, `giflib`, `gmp`, `gnutls`, `kvazaar`, `lame`, `leptonica`, `libaom`, `libass`, `libiconv`, `libilbc`, `libjpeg`, `libjpeg-turbo`, `libogg`, `libpng`, `libsamplerate`, `libsndfile`, `libtheora`, `libuuid`, `libvorbis`, `libvpx`, `libwebp`, `libxml2`, `nettle`, `opencore-amr`, `openh264`, `opus`, `rubberband`, `sdl`, `shine`, `snappy`, `soxr`, `speex`, `tesseract`, `tiff`, `twolame`, `vid.stab`, `vo-amrwbenc`, `wavpack`, `x264`, `x265`, `xvidcore`
- Licensed under LGPL 3.0, can be customized to support GPL v3.0
#### 1.1 Android
- Builds `arm-v7a`, `arm-v7a-neon`, `arm64-v8a`, `x86` and `x86_64` architectures
- Supports `zlib` and `MediaCodec` system libraries
- Camera access on [supported devices](https://developer.android.com/ndk/guides/stable_apis#camera)
- Builds shared native libraries (.so)
- Creates Android archives with .aar extension
- Supports `API Level 16+`
#### 1.2 iOS
- Builds `armv7`, `armv7s`, `arm64`, `arm64e`, `i386`, `x86_64` and `x86_64` (Mac Catalyst) architectures
- Supports `bzip2`, `iconv`, `libuuid`, `zlib` system libraries and `AudioToolbox`, `VideoToolbox`, `AVFoundation` system frameworks
- Objective-C API
- Camera access
- `ARC` enabled library
- Built with `-fembed-bitcode` flag
- Creates static frameworks, static xcframeworks and static universal (fat) libraries (.a)
- Supports `iOS SDK 9.3` or later
#### 1.3 tvOS
- Builds `arm64` and `x86_64` architectures
- Supports `bzip2`, `iconv`, `libuuid`, `zlib` system libraries and `AudioToolbox`, `VideoToolbox` system frameworks
- Objective-C API
- `ARC` enabled library
- Built with `-fembed-bitcode` flag
- Creates static frameworks and static universal (fat) libraries (.a)
- Supports `tvOS SDK 9.2` or later
### 2. Using
Prebuilt binaries are available at [Github](https://github.com/tanersener/ffmpeg-kit/releases), [JCenter](https://bintray.com/bintray/jcenter) and [CocoaPods](https://cocoapods.org).
#### 2.1 Packages
There are eight different `ffmpeg-kit` packages. Below you can see which system libraries and external libraries are enabled in each of package.
Please remember that some parts of `FFmpeg` are licensed under the `GPL` and only `GPL` licensed `ffmpeg-kit` packages include them.
<table>
<thead>
<tr>
<th align="center"></th>
<th align="center"><sup>min</sup></th>
<th align="center"><sup>min-gpl</sup></th>
<th align="center"><sup>https</sup></th>
<th align="center"><sup>https-gpl</sup></th>
<th align="center"><sup>audio</sup></th>
<th align="center"><sup>video</sup></th>
<th align="center"><sup>full</sup></th>
<th align="center"><sup>full-gpl</sup></th>
</tr>
</thead>
<tbody>
<tr>
<td align="center"><sup>external libraries</sup></td>
<td align="center">-</td>
<td align="center"><sup>vid.stab</sup><br><sup>x264</sup><br><sup>x265</sup><br><sup>xvidcore</sup></td>
<td align="center"><sup>gmp</sup><br><sup>gnutls</sup></td>
<td align="center"><sup>gmp</sup><br><sup>gnutls</sup><br><sup>vid.stab</sup><br><sup>x264</sup><br><sup>x265</sup><br><sup>xvidcore</sup></td>
<td align="center"><sup>lame</sup><br><sup>libilbc</sup><br><sup>libvorbis</sup><br><sup>opencore-amr</sup><br><sup>opus</sup><br><sup>shine</sup><br><sup>soxr</sup><br><sup>speex</sup><br><sup>twolame</sup><br><sup>vo-amrwbenc</sup><br><sup>wavpack</sup></td>
<td align="center"><sup>fontconfig</sup><br><sup>freetype</sup><br><sup>fribidi</sup><br><sup>kvazaar</sup><br><sup>libaom</sup><br><sup>libass</sup><br><sup>libiconv</sup><br><sup>libtheora</sup><br><sup>libvpx</sup><br><sup>libwebp</sup><br><sup>snappy</sup></td>
<td align="center"><sup>fontconfig</sup><br><sup>freetype</sup><br><sup>fribidi</sup><br><sup>gmp</sup><br><sup>gnutls</sup><br><sup>kvazaar</sup><br><sup>lame</sup><br><sup>libaom</sup><br><sup>libass</sup><br><sup>libiconv</sup><br><sup>libilbc</sup><br><sup>libtheora</sup><br><sup>libvorbis</sup><br><sup>libvpx</sup><br><sup>libwebp</sup><br><sup>libxml2</sup><br><sup>opencore-amr</sup><br><sup>opus</sup><br><sup>shine</sup><br><sup>snappy</sup><br><sup>soxr</sup><br><sup>speex</sup><br><sup>twolame</sup><br><sup>vo-amrwbenc</sup><br><sup>wavpack</sup></td>
<td align="center"><sup>fontconfig</sup><br><sup>freetype</sup><br><sup>fribidi</sup><br><sup>gmp</sup><br><sup>gnutls</sup><br><sup>kvazaar</sup><br><sup>lame</sup><br><sup>libaom</sup><br><sup>libass</sup><br><sup>libiconv</sup><br><sup>libilbc</sup><br><sup>libtheora</sup><br><sup>libvorbis</sup><br><sup>libvpx</sup><br><sup>libwebp</sup><br><sup>libxml2</sup><br><sup>opencore-amr</sup><br><sup>opus</sup><br><sup>shine</sup><br><sup>snappy</sup><br><sup>soxr</sup><br><sup>speex</sup><br><sup>twolame</sup><br><sup>vid.stab</sup><br><sup>vo-amrwbenc</sup><br><sup>wavpack</sup><br><sup>x264</sup><br><sup>x265</sup><br><sup>xvidcore</sup></td>
</tr>
<tr>
<td align="center"><sup>android system libraries</sup></td>
<td align="center" colspan=8><sup>zlib</sup><br><sup>MediaCodec</sup></td>
</tr>
<tr>
<td align="center"><sup>ios system libraries</sup></td>
<td align="center" colspan=8><sup>zlib</sup><br><sup>AudioToolbox</sup><br><sup>AVFoundation</sup><br><sup>iconv</sup><br><sup>VideoToolbox</sup><br><sup>bzip2</sup></td>
</tr>
<tr>
<td align="center"><sup>tvos system libraries</sup></td>
<td align="center" colspan=8><sup>zlib</sup><br><sup>AudioToolbox</sup><br><sup>iconv</sup><br><sup>VideoToolbox</sup><br><sup>bzip2</sup></td>
</tr>
</tbody>
</table>
- `AVFoundation` is not available on `tvOS`, `VideoToolbox` is not available on `tvOS` LTS releases
#### 2.2 Android
1. Add FFmpegKit dependency to your `build.gradle` in `ffmpeg-kit-<package name>` pattern.
```
dependencies {
implementation 'com.arthenica:ffmpeg-kit-full:4.4'
}
```
2. Execute synchronous FFmpeg commands.
```
import com.arthenica.ffmpegkit.Config;
import com.arthenica.ffmpegkit.FFmpeg;
int rc = FFmpeg.execute("-i file1.mp4 -c:v mpeg4 file2.mp4");
if (rc == RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "Command execution completed successfully.");
} else if (rc == RETURN_CODE_CANCEL) {
Log.i(Config.TAG, "Command execution cancelled by user.");
} else {
Log.i(Config.TAG, String.format("Command execution failed with rc=%d and the output below.", rc));
Config.printLastCommandOutput(Log.INFO);
}
```
3. Execute asynchronous FFmpeg commands.
```
import com.arthenica.ffmpegkit.Config;
import com.arthenica.ffmpegkit.FFmpeg;
long executionId = FFmpeg.executeAsync("-i file1.mp4 -c:v mpeg4 file2.mp4", new ExecuteCallback() {
@Override
public void apply(final long executionId, final int returnCode) {
if (rc == RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "Async command execution completed successfully.");
} else if (rc == RETURN_CODE_CANCEL) {
Log.i(Config.TAG, "Async command execution cancelled by user.");
} else {
Log.i(Config.TAG, String.format("Async command execution failed with rc=%d.", rc));
}
}
});
```
4. Execute FFprobe commands.
```
import com.arthenica.ffmpegkit.Config;
import com.arthenica.ffmpegkit.FFprobe;
int rc = FFprobe.execute("-i file1.mp4");
if (rc == RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "Command execution completed successfully.");
} else {
Log.i(Config.TAG, String.format("Command execution failed with rc=%d and the output below.", rc));
Config.printLastCommandOutput(Log.INFO);
}
```
5. Check execution output later.
```
int rc = Config.getLastReturnCode();
if (rc == RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "Command execution completed successfully.");
} else if (rc == RETURN_CODE_CANCEL) {
Log.i(Config.TAG, "Command execution cancelled by user.");
} else {
Log.i(Config.TAG, String.format("Command execution failed with rc=%d and the output below.", rc));
Config.printLastCommandOutput(Log.INFO);
}
```
6. Stop ongoing FFmpeg operations.
- Stop all executions
```
FFmpeg.cancel();
```
- Stop a specific execution
```
FFmpeg.cancel(executionId);
```
7. Get media information for a file.
```
MediaInformation info = FFprobe.getMediaInformation("<file path or uri>");
```
8. Record video using Android camera.
```
FFmpeg.execute("-f android_camera -i 0:0 -r 30 -pixel_format bgr0 -t 00:00:05 <record file path>");
```
9. Enable log callback.
```
Config.enableLogCallback(new LogCallback() {
public void apply(LogMessage message) {
Log.d(Config.TAG, message.getText());
}
});
```
10. Enable statistics callback.
```
Config.enableStatisticsCallback(new StatisticsCallback() {
public void apply(Statistics newStatistics) {
Log.d(Config.TAG, String.format("frame: %d, time: %d", newStatistics.getVideoFrameNumber(), newStatistics.getTime()));
}
});
```
11. Ignore the handling of a signal.
```
Config.ignoreSignal(Signal.SIGXCPU);
```
12. List ongoing executions.
```
final List<FFmpegExecution> ffmpegExecutions = FFmpeg.listExecutions();
for (int i = 0; i < ffmpegExecutions.size(); i++) {
FFmpegExecution execution = ffmpegExecutions.get(i);
Log.d(TAG, String.format("Execution %d = id:%d, startTime:%s, command:%s.", i, execution.getExecutionId(), execution.getStartTime(), execution.getCommand()));
}
```
13. Set default log level.
```
Config.setLogLevel(Level.AV_LOG_FATAL);
```
14. Register custom fonts directory.
```
Config.setFontDirectory(this, "<folder with fonts>", Collections.EMPTY_MAP);
```
#### 2.3 iOS / tvOS
1. Add FFmpegKit dependency to your `Podfile` in `ffmpeg-kit-<package name>` pattern.
- iOS
```
pod 'ffmpeg-kit-full', '~> 4.4'
```
- tvOS
```
pod 'ffmpeg-kit-tvos-full', '~> 4.4'
```
2. Execute synchronous FFmpeg commands.
```
#import <ffmpegkit/FFmpegKitConfig.h>
#import <ffmpegkit/FFmpegKit.h>
int rc = [FFmpegKit execute: @"-i file1.mp4 -c:v mpeg4 file2.mp4"];
if (rc == RETURN_CODE_SUCCESS) {
NSLog(@"Command execution completed successfully.\n");
} else if (rc == RETURN_CODE_CANCEL) {
NSLog(@"Command execution cancelled by user.\n");
} else {
NSLog(@"Command execution failed with rc=%d and output=%@.\n", rc, [FFmpegKitConfig getLastCommandOutput]);
}
```
3. Execute asynchronous FFmpeg commands.
```
#import <ffmpegkit/FFmpegKitConfig.h>
#import <ffmpegkit/FFmpegKit.h>
long executionId = [FFmpegKit executeAsync:@"-i file1.mp4 -c:v mpeg4 file2.mp4" withCallback:self];
- (void)executeCallback:(long)executionId :(int)returnCode {
if (rc == RETURN_CODE_SUCCESS) {
NSLog(@"Async command execution completed successfully.\n");
} else if (rc == RETURN_CODE_CANCEL) {
NSLog(@"Async command execution cancelled by user.\n");
} else {
NSLog(@"Async command execution failed with rc=%d.\n", rc);
}
}
```
4. Execute FFprobe commands.
```
#import <ffmpegkit/FFmpegKitConfig.h>
#import <ffmpegkit/FFprobeKit.h>
int rc = [FFprobeKit execute: @"-i file1.mp4"];
if (rc == RETURN_CODE_SUCCESS) {
NSLog(@"Command execution completed successfully.\n");
} else if (rc == RETURN_CODE_CANCEL) {
NSLog(@"Command execution cancelled by user.\n");
} else {
NSLog(@"Command execution failed with rc=%d and output=%@.\n", rc, [FFmpegKitConfig getLastCommandOutput]);
}
```
5. Check execution output later.
```
int rc = [FFmpegKitConfig getLastReturnCode];
NSString *output = [FFmpegKitConfig getLastCommandOutput];
if (rc == RETURN_CODE_SUCCESS) {
NSLog(@"Command execution completed successfully.\n");
} else if (rc == RETURN_CODE_CANCEL) {
NSLog(@"Command execution cancelled by user.\n");
} else {
NSLog(@"Command execution failed with rc=%d and output=%@.\n", rc, output);
}
```
6. Stop ongoing FFmpeg operations.
- Stop all executions
```
[FFmpegKit cancel];
```
- Stop a specific execution
```
[FFmpegKit cancel:executionId];
```
7. Get media information for a file.
```
MediaInformation *mediaInformation = [FFprobeKit getMediaInformation:@"<file path or uri>"];
```
8. Record video and audio using iOS camera. This operation is not supported on `tvOS` since `AVFoundation` is not available on `tvOS`.
```
[FFmpegKit execute: @"-f avfoundation -r 30 -video_size 1280x720 -pixel_format bgr0 -i 0:0 -vcodec h264_videotoolbox -vsync 2 -f h264 -t 00:00:05 %@", recordFilePath];
```
9. Enable log callback.
```
[FFmpegKitConfig setLogDelegate:self];
- (void)logCallback:(long)executionId :(int)level :(NSString*)message {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@", message);
});
}
```
10. Enable statistics callback.
```
[FFmpegKitConfig setStatisticsDelegate:self];
- (void)statisticsCallback:(Statistics *)newStatistics {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"frame: %d, time: %d\n", newStatistics.getVideoFrameNumber, newStatistics.getTime);
});
}
```
11. Ignore the handling of a signal.
```
[FFmpegKitConfig ignoreSignal:SIGXCPU];
```
12. List ongoing executions.
```
NSArray* ffmpegExecutions = [FFmpegKit listExecutions];
for (int i = 0; i < [ffmpegExecutions count]; i++) {
FFmpegExecution* execution = [ffmpegExecutions objectAtIndex:i];
NSLog(@"Execution %d = id: %ld, startTime: %@, command: %@.\n", i, [execution getExecutionId], [execution getStartTime], [execution getCommand]);
}
```
13. Set default log level.
```
[FFmpegKitConfig setLogLevel:AV_LOG_FATAL];
```
14. Register custom fonts directory.
```
[FFmpegKitConfig setFontDirectory:@"<folder with fonts>" with:nil];
```
#### 2.4 Manual Installation
##### 2.4.1 Android
You can import `FFmpegKit` aar packages in `Android Studio` using the `File` -> `New` -> `New Module` -> `Import .JAR/.AAR Package` menu.
##### 2.4.2 iOS / tvOS
iOS and tvOS frameworks can be installed manually using the [Importing Frameworks](https://github.com/tanersener/ffmpeg-kit/wiki/Importing-Frameworks) guide.
If you want to use universal binaries please refer to [Using Universal Binaries](https://github.com/tanersener/ffmpeg-kit/wiki/Using-Universal-Binaries) guide.
#### 2.5 Test Application
You can see how FFmpegKit is used inside an application by running test applications provided.
There is an `Android` test application under the `android/test-app` folder, an `iOS` test application under the
`ios/test-app` folder and a `tvOS` test application under the `tvos/test-app` folder.
All applications are identical and supports command execution, video encoding, accessing https, encoding audio,
burning subtitles, video stabilisation, pipe operations and concurrent command execution.
<img src="https://github.com/tanersener/ffmpeg-kit/blob/master/docs/assets/android_test_app.gif" width="240">
### 3. Versions
- `dev` part in `FFmpeg` version number indicates that `FFmpeg` source is pulled from the `FFmpeg` `master` branch.
Exact version number is obtained using `git describe --tags`.
| FFmpegKit Version | FFmpeg Version | Release Date |
| :----: | :----: |:----: |
| [4.4](https://github.com/tanersener/ffmpeg-kit/releases/tag/v4.4) | 4.4-dev-416 | Jul 25, 2020 |
| [4.4.LTS](https://github.com/tanersener/ffmpeg-kit/releases/tag/v4.4.LTS) | 4.4-dev-416 | Jul 24, 2020 |
### 4. LTS Releases
`FFmpegKit` binaries are published in two release variants: `Main Release` and `LTS Release`.
- Main releases include complete functionality of the library and support the latest SDK/API features.
- LTS releases are customized to support a wider range of devices. They are built using older API/SDK versions, so some features are not available on them.
This table shows the differences between two variants.
| | Main Release | LTS Release |
| :----: | :----: | :----: |
| Android API Level | 24 | 16 |
| Android Camera Access | Yes | - |
| Android Architectures | arm-v7a-neon<br/>arm64-v8a<br/>x86<br/>x86-64 | arm-v7a<br/>arm-v7a-neon<br/>arm64-v8a<br/>x86<br/>x86-64 |
| Xcode Support | 10.1 | 7.3.1 |
| iOS SDK | 12.1 | 9.3 |
| iOS AVFoundation | Yes | - |
| iOS Architectures | arm64<br/>x86-64<br/>x86-64-mac-catalyst | armv7<br/>arm64<br/>i386<br/>x86-64 |
| tvOS SDK | 10.2 | 9.2 |
| tvOS Architectures | arm64<br/>x86-64 | arm64<br/>x86-64 |
### 5. Building
Build scripts from `master` and `development` branches are tested periodically. See the latest status from the table below.
| branch | status |
| :---: | :---: |
| master | [![Build Status](https://travis-ci.org/tanersener/ffmpeg-kit.svg?branch=master)](https://travis-ci.org/tanersener/ffmpeg-kit) |
| development | [![Build Status](https://travis-ci.org/tanersener/ffmpeg-kit.svg?branch=development)](https://travis-ci.org/tanersener/ffmpeg-kit) |
#### 5.1 Prerequisites
1. Use your package manager (apt, yum, dnf, brew, etc.) to install the following packages.
```
autoconf automake libtool pkg-config curl cmake gcc gperf texinfo yasm nasm bison autogen patch git
```
Some of these packages are not mandatory for the default build.
Please visit [Android Prerequisites](https://github.com/tanersener/ffmpeg-kit/wiki/Android-Prerequisites),
[iOS Prerequisites](https://github.com/tanersener/ffmpeg-kit/wiki/iOS-Prerequisites) and
[tvOS Prerequisites](https://github.com/tanersener/ffmpeg-kit/wiki/tvOS-Prerequisites) for the details.
2. Android builds require these additional packages.
- **Android SDK 4.1 Jelly Bean (API Level 16)** or later
- **Android NDK r21** or later with LLDB and CMake
3. iOS builds need these extra packages and tools.
- **Xcode 7.3.1** or later
- **iOS SDK 9.3** or later
- **Command Line Tools**
4. tvOS builds need these extra packages and tools.
- **Xcode 7.3.1** or later
- **tvOS SDK 9.2** or later
- **Command Line Tools**
#### 5.2 Build Scripts
Use `android.sh`, `ios.sh` and `tvos.sh` to build FFmpegKit for each platform.
All three scripts support additional options and
can be customized to enable/disable specific external libraries and/or architectures. Please refer to wiki pages of
[android.sh](https://github.com/tanersener/ffmpeg-kit/wiki/android.sh),
[ios.sh](https://github.com/tanersener/ffmpeg-kit/wiki/ios.sh) and
[tvos.sh](https://github.com/tanersener/ffmpeg-kit/wiki/tvos.sh) to see all available build options.
##### 5.2.1 Android
```
export ANDROID_SDK_ROOT=<Android SDK Path>
export ANDROID_NDK_ROOT=<Android NDK Path>
./android.sh
```
<img src="https://github.com/tanersener/ffmpeg-kit/blob/master/docs/assets/android_custom.gif" width="600">
##### 5.2.2 iOS
```
./ios.sh
```
<img src="https://github.com/tanersener/ffmpeg-kit/blob/master/docs/assets/ios_custom.gif" width="600">
##### 5.2.3 tvOS
```
./tvos.sh
```
<img src="https://github.com/tanersener/ffmpeg-kit/blob/master/docs/assets/tvos_custom.gif" width="600">
##### 5.2.4 Building LTS Binaries
Use `--lts` option to build lts binaries for each platform.
#### 5.3 Build Output
All libraries created by the top level build scripts (`android.sh`, `ios.sh` and `tvos.sh`) can be found under
the `prebuilt` directory.
- `Android` archive (.aar file) is located under the `android-aar` folder
- `iOS` frameworks are located under the `ios-framework` folder
- `iOS` xcframeworks are located under the `ios-xcframework` folder
- `iOS` universal binaries are located under the `ios-universal` folder
- `tvOS` frameworks are located under the `tvos-framework` folder
- `tvOS` universal binaries are located under the `tvos-universal` folder
#### 5.4 GPL Support
It is possible to enable GPL licensed libraries `x264`, `xvidcore`, `vid.stab`, `x265` and`rubberband` from the top
level build scripts. Their source code is not included in the repository and downloaded when enabled.
#### 5.5 External Libraries
`build` directory includes build scripts of all external libraries. Two scripts exist for each external library,
one for `Android` and one for `iOS / tvOS`. Each of these two scripts contains options/flags used to cross-compile the
library on the specified platform.
CPU optimizations (`ASM`) are enabled for most of the external libraries. Details and exceptions can be found under the
[ASM Support](https://github.com/tanersener/ffmpeg-kit/wiki/ASM-Support) wiki page.
### 6. Documentation
A more detailed documentation is available at [Wiki](https://github.com/tanersener/ffmpeg-kit/wiki).
### 8. License
`FFmpegKit` is licensed under the LGPL v3.0. However, if source code is built using the optional `--enable-gpl` flag
or prebuilt binaries with `-gpl` postfix are used, then FFmpegKit is subject to the GPL v3.0 license.
The source code of all external libraries included is in compliance with their individual licenses.
`openh264` source code included in this repository is licensed under the 2-clause BSD License but this license does
not cover the `MPEG LA` licensing fees. If you build `ffmpeg-kit` with `openh264` and distribute that library, then
you are subject to pay `MPEG LA` licensing fees. Refer to [OpenH264 FAQ](https://www.openh264.org/faq.html) page for
the details. Please note that `ffmpeg-kit` does not publish a binary with `openh264` inside.
`strip-frameworks.sh` script included and distributed (until v4.x) is published under the
[Apache License version 2.0](https://www.apache.org/licenses/LICENSE-2.0).
In test applications; embedded fonts are licensed under the
[SIL Open Font License](https://opensource.org/licenses/OFL-1.1), other digital assets are published in the public
domain.
Please visit [License](https://github.com/tanersener/ffmpeg-kit/wiki/License) page for the details.
### 9. Patents
It is not clearly explained in their documentation but it is believed that `FFmpeg`, `kvazaar`, `x264` and `x265`
include algorithms which are subject to software patents. If you live in a country where software algorithms are
patentable then you'll probably need to pay royalty fees to patent holders. We are not lawyers though, so we recommend
that you seek legal advice first. See [FFmpeg Patent Mini-FAQ](https://ffmpeg.org/legal.html).
`openh264` clearly states that it uses patented algorithms. Therefore, if you build ffmpeg-kit with openh264 and
distribute that library, then you are subject to pay MPEG LA licensing fees. Refer to
[OpenH264 FAQ](https://www.openh264.org/faq.html) page for the details.
### 10. Contributing
Feel free to submit issues or pull requests.
Please note that `master` includes only the latest released source code. Changes planned for the next release are
implemented under the `development` branch. Therefore, if you want to create a pull request, please open it against
the `development`.
### 11. See Also
- [libav gas-preprocessor](https://github.com/libav/gas-preprocessor/raw/master/gas-preprocessor.pl)
- [FFmpeg API Documentation](https://ffmpeg.org/doxygen/4.0/index.html)
- [FFmpeg Wiki](https://trac.ffmpeg.org/wiki/WikiStart)
- [FFmpeg External Library Licenses](https://www.ffmpeg.org/doxygen/4.0/md_LICENSE.html)

@ -1,119 +1,51 @@
#!/bin/bash #!/bin/bash
export FFMPEG_KIT_BUILD_TYPE="android"
export BASEDIR="$(pwd)"
source "${BASEDIR}"/scripts/common-${FFMPEG_KIT_BUILD_TYPE}.sh
# ENABLE ARCH
ENABLED_ARCHITECTURES=(1 1 0 0 1 0 0 0 1 1 0)
# ENABLE LIBRARIES
ENABLED_LIBRARIES=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
# USING API LEVEL 24 / Android 7.0 (NOUGAT)
export API=24
RECONF_LIBRARIES=()
REBUILD_LIBRARIES=()
REDOWNLOAD_LIBRARIES=()
get_ffmpeg_kit_version() {
local FFMPEG_KIT_VERSION=$(grep '#define FFMPEG_KIT_VERSION' "${BASEDIR}"/android/app/src/main/cpp/ffmpegkit.h | grep -Eo '\".*\"' | sed -e 's/\"//g')
echo "${FFMPEG_KIT_VERSION}"
}
display_help() {
local COMMAND=$(echo "$0" | sed -e 's/\.\///g')
echo -e "\n'$COMMAND' builds FFmpegKit for Android platform. By default five Android ABIs (armeabi-v7a, \
armeabi-v7a-neon, arm64-v8a, x86 and x86_64) are built without any external libraries enabled. Options can be used to \
disable ABIs and/or enable external libraries. Please note that GPL libraries (external libraries with GPL license) \
need --enable-gpl flag to be set explicitly. When compilation ends an Android Archive (AAR) file is created under the \
prebuilt folder.\n"
echo -e "Usage: ./$COMMAND [OPTION]... [VAR=VALUE]...\n"
echo -e "Specify environment variables as VARIABLE=VALUE to override default build options.\n"
display_help_options " --api-level=api\t\tset Android api level [${API}]"
display_help_licensing
echo -e "Architectures:"
echo -e " --disable-arm-v7a\t\tdo not build arm-v7a architecture [yes]"
echo -e " --disable-arm-v7a-neon\tdo not build arm-v7a-neon architecture [yes]"
echo -e " --disable-arm64-v8a\t\tdo not build arm64-v8a architecture [yes]"
echo -e " --disable-x86\t\t\tdo not build x86 architecture [yes]"
echo -e " --disable-x86-64\t\tdo not build x86-64 architecture [yes]\n"
echo -e "Libraries:"
echo -e " --full\t\t\tenables all external libraries"
echo -e " --enable-android-media-codec\tbuild with built-in Android MediaCodec support[no]"
echo -e " --enable-android-zlib\t\tbuild with built-in zlib support[no]"
display_help_common_libraries
display_help_gpl_libraries
display_help_advanced_options
}
enable_lts_build() {
export FFMPEG_KIT_LTS_BUILD="1"
# USING API LEVEL 16 / Android 4.1 (JELLY BEAN)
export API=16
}
build_application_mk() {
if [[ -n ${FFMPEG_KIT_LTS_BUILD} ]]; then
local LTS_BUILD_FLAG="-DFFMPEG_KIT_LTS "
fi
if [[ ${ENABLED_LIBRARIES[$LIBRARY_X265]} -eq 1 ]] || [[ ${ENABLED_LIBRARIES[$LIBRARY_TESSERACT]} -eq 1 ]] || [[ ${ENABLED_LIBRARIES[$LIBRARY_OPENH264]} -eq 1 ]] || [[ ${ENABLED_LIBRARIES[$LIBRARY_SNAPPY]} -eq 1 ]] || [[ ${ENABLED_LIBRARIES[$LIBRARY_RUBBERBAND]} -eq 1 ]]; then
local APP_STL="c++_shared"
else
local APP_STL="none"
fi
local BUILD_DATE="-DFFMPEG_KIT_BUILD_DATE=$(date +%Y%m%d 2>>"${BASEDIR}"/build.log)"
rm -f "${BASEDIR}/android/jni/Application.mk"
cat >"${BASEDIR}/android/jni/Application.mk" <<EOF
APP_OPTIM := release
APP_ABI := ${ANDROID_ARCHITECTURES}
APP_STL := ${APP_STL}
APP_PLATFORM := android-${API}
APP_CFLAGS := -O3 -DANDROID ${LTS_BUILD_FLAG}${BUILD_DATE} -Wall -Wno-deprecated-declarations -Wno-pointer-sign -Wno-switch -Wno-unused-result -Wno-unused-variable
APP_LDFLAGS := -Wl,--hash-style=both
EOF
}
if [[ -z ${ANDROID_SDK_ROOT} ]]; then if [[ -z ${ANDROID_SDK_ROOT} ]]; then
echo -e "(*) ANDROID_SDK_ROOT not defined\n" echo -e "\n(*) ANDROID_SDK_ROOT not defined\n"
exit 1 exit 1
fi fi
if [[ -z ${ANDROID_NDK_ROOT} ]]; then if [[ -z ${ANDROID_NDK_ROOT} ]]; then
echo -e "(*) ANDROID_NDK_ROOT not defined\n" echo -e "\n(*) ANDROID_NDK_ROOT not defined\n"
exit 1 exit 1
fi fi
DETECTED_NDK_VERSION=$(grep -Eo "Revision.*" "${ANDROID_NDK_ROOT}"/source.properties | sed 's/Revision//g;s/=//g;s/ //g') # LOAD INITIAL SETTINGS
export BASEDIR="$(pwd)"
export FFMPEG_KIT_BUILD_TYPE="android"
source "${BASEDIR}"/scripts/variable.sh
source "${BASEDIR}"/scripts/function-${FFMPEG_KIT_BUILD_TYPE}.sh
# SET DEFAULTS SETTINGS
enable_default_android_architectures
enable_default_android_libraries
enable_main_build
# DETECT ANDROID NDK VERSION
DETECTED_NDK_VERSION=$(grep -Eo "Revision.*" "${ANDROID_NDK_ROOT}"/source.properties | sed 's/Revision//g;s/=//g;s/ //g')
echo -e "\nINFO: Using Android NDK v${DETECTED_NDK_VERSION} provided at ${ANDROID_NDK_ROOT}\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "\nINFO: Using Android NDK v${DETECTED_NDK_VERSION} provided at ${ANDROID_NDK_ROOT}\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "INFO: Build options: $*\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "INFO: Build options: $*\n" 1>>"${BASEDIR}"/build.log 2>&1
# SET DEFAULT BUILD OPTIONS
GPL_ENABLED="no" GPL_ENABLED="no"
DISPLAY_HELP="" DISPLAY_HELP=""
BUILD_LTS=""
BUILD_FULL="" BUILD_FULL=""
BUILD_TYPE_ID="" BUILD_TYPE_ID=""
BUILD_VERSION=$(git describe --tags 2>>"${BASEDIR}"/build.log) BUILD_VERSION=$(git describe --tags --always 2>>"${BASEDIR}"/build.log)
# PROCESS LTS BUILD OPTION FIRST AND SET BUILD TYPE: MAIN OR LTS
rm -f "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/tools/release/android/build.gradle "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
for argument in "$@"; do
if [[ "$argument" == "-l" ]] || [[ "$argument" == "--lts" ]]; then
enable_lts_build
BUILD_TYPE_ID+="LTS "
rm -f "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/tools/release/android/build.lts.gradle "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
fi
done
# PROCESS BUILD OPTIONS
while [ ! $# -eq 0 ]; do while [ ! $# -eq 0 ]; do
case $1 in case $1 in
@ -146,11 +78,9 @@ while [ ! $# -eq 0 ]; do
-s | --speed) -s | --speed)
optimize_for_speed optimize_for_speed
;; ;;
-l | --lts) -l | --lts) ;;
BUILD_LTS="1"
;;
-f | --force) -f | --force)
BUILD_FORCE="1" export BUILD_FORCE="1"
;; ;;
--reconf-*) --reconf-*)
CONF_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g') CONF_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
@ -200,39 +130,28 @@ if [[ -z ${BUILD_VERSION} ]]; then
exit 1 exit 1
fi fi
# DETECT BUILD TYPE # PROCESS FULL OPTION AS LAST OPTION
rm -f "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
if [[ -n ${BUILD_LTS} ]]; then
enable_lts_build
BUILD_TYPE_ID+="LTS "
cp "${BASEDIR}"/tools/release/android/build.lts.gradle "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
else
cp "${BASEDIR}"/tools/release/android/build.gradle "${BASEDIR}"/android/app/build.gradle 1>>"${BASEDIR}"/build.log 2>&1
fi
# HELP DISPLAYED AFTER SETTING LTS FLAG
if [[ -n ${DISPLAY_HELP} ]]; then
display_help
exit 0
fi
# PROCESS FULL FLAG
if [[ -n ${BUILD_FULL} ]]; then if [[ -n ${BUILD_FULL} ]]; then
for library in {0..60}; do for library in {0..57}; do
if [ ${GPL_ENABLED} == "yes" ]; then if [ ${GPL_ENABLED} == "yes" ]; then
enable_library "$(get_library_name $library)" enable_library "$(get_library_name $library)" 1
else else
if [[ $library -ne $LIBRARY_X264 ]] && [[ $library -ne $LIBRARY_XVIDCORE ]] && [[ $library -ne $LIBRARY_X265 ]] && [[ $library -ne $LIBRARY_LIBVIDSTAB ]] && [[ $library -ne $LIBRARY_RUBBERBAND ]]; then if [[ $(is_gpl_licensed $library) -eq 1 ]]; then
enable_library "$(get_library_name $library)" enable_library "$(get_library_name $library)" 1
fi fi
fi fi
done done
fi fi
# IF HELP DISPLAYED EXIT
if [[ -n ${DISPLAY_HELP} ]]; then
display_help
exit 0
fi
echo -e "\nBuilding ffmpeg-kit ${BUILD_TYPE_ID}library for Android\n" echo -e "\nBuilding ffmpeg-kit ${BUILD_TYPE_ID}library for Android\n"
echo -e -n "INFO: Building ffmpeg-kit ${BUILD_VERSION} ${BUILD_TYPE_ID}library for Android: " 1>>"${BASEDIR}"/build.log 2>&1 echo -e -n "INFO: Building ffmpeg-kit ${BUILD_VERSION} ${BUILD_TYPE_ID}library for Android: " 1>>"${BASEDIR}"/build.log 2>&1
echo -e "$(date)" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "$(date)\n" 1>>"${BASEDIR}"/build.log 2>&1
# PRINT BUILD SUMMARY # PRINT BUILD SUMMARY
print_enabled_architectures print_enabled_architectures
@ -241,7 +160,7 @@ print_reconfigure_requested_libraries
print_rebuild_requested_libraries print_rebuild_requested_libraries
print_redownload_requested_libraries print_redownload_requested_libraries
# CHECK GPL FLAG AND DOWNLOAD LIBRARIES # VALIDATE GPL FLAGS
for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVIDSTAB,$LIBRARY_RUBBERBAND}; do for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVIDSTAB,$LIBRARY_RUBBERBAND}; do
if [[ ${ENABLED_LIBRARIES[$gpl_library]} -eq 1 ]]; then if [[ ${ENABLED_LIBRARIES[$gpl_library]} -eq 1 ]]; then
library_name=$(get_library_name ${gpl_library}) library_name=$(get_library_name ${gpl_library})
@ -250,21 +169,20 @@ for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVI
echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n"
echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" 1>>"${BASEDIR}"/build.log 2>&1
exit 1 exit 1
else
DOWNLOAD_RESULT=$(download_gpl_library_source "${library_name}")
if [[ ${DOWNLOAD_RESULT} -ne 0 ]]; then
echo -e "\n(*) Failed to download GPL library ${library_name} source. Please check build.log file for details. If the problem persists refer to offline building instructions.\n"
echo -e "\n(*) Failed to download GPL library ${library_name} source.\n" 1>>"${BASEDIR}"/build.log 2>&1
exit 1
fi
fi fi
fi fi
done done
# SAVE API VALUE echo -n -e "\nDownloading sources: "
echo -e "INFO: Downloading source code of ffmpeg and enabled external libraries.\n" 1>>"${BASEDIR}"/build.log 2>&1
# DOWNLOAD LIBRARY SOURCES
downloaded_enabled_library_sources "${ENABLED_LIBRARIES[@]}"
# SAVE ORIGINAL API LEVEL = NECESSARY TO BUILD 64bit ARCHITECTURES
export ORIGINAL_API=${API} export ORIGINAL_API=${API}
# BUILD ALL ENABLED ARCHITECTURES # BUILD ENABLED LIBRARIES ON ENABLED ARCHITECTURES
for run_arch in {0..10}; do for run_arch in {0..10}; do
if [[ ${ENABLED_ARCHITECTURES[$run_arch]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[$run_arch]} -eq 1 ]]; then
if [[ (${run_arch} -eq ${ARCH_ARM64_V8A} || ${run_arch} -eq ${ARCH_X86_64}) && ${API} -lt 21 ]]; then if [[ (${run_arch} -eq ${ARCH_ARM64_V8A} || ${run_arch} -eq ${ARCH_X86_64}) && ${API} -lt 21 ]]; then
@ -279,10 +197,11 @@ for run_arch in {0..10}; do
export TOOLCHAIN=$(get_toolchain) export TOOLCHAIN=$(get_toolchain)
export TOOLCHAIN_ARCH=$(get_toolchain_arch) export TOOLCHAIN_ARCH=$(get_toolchain_arch)
# EXECUTE MAIN BUILD SCRIPT
. "${BASEDIR}"/scripts/main-android.sh "${ENABLED_LIBRARIES[@]}" || exit 1 . "${BASEDIR}"/scripts/main-android.sh "${ENABLED_LIBRARIES[@]}" || exit 1
# CLEAR FLAGS # CLEAR FLAGS
for library in {0..60}; do for library in {0..57}; do
library_name=$(get_library_name ${library}) library_name=$(get_library_name ${library})
unset "$(echo "OK_${library_name}" | sed "s/\-/\_/g")" unset "$(echo "OK_${library_name}" | sed "s/\-/\_/g")"
unset "$(echo "DEPENDENCY_REBUILT_${library_name}" | sed "s/\-/\_/g")" unset "$(echo "DEPENDENCY_REBUILT_${library_name}" | sed "s/\-/\_/g")"
@ -290,56 +209,52 @@ for run_arch in {0..10}; do
fi fi
done done
# GET BACK THE ORIGINAL API LEVEL
export API=${ORIGINAL_API} export API=${ORIGINAL_API}
# SET ARCHITECTURES INSIDE Application.mk # SET ARCHITECTURES TO BUILD
rm -f "${BASEDIR}"/android/build/.armv7 1>>"${BASEDIR}"/build.log 2>&1 rm -f "${BASEDIR}"/android/build/.armv7 1>>"${BASEDIR}"/build.log 2>&1
rm -f "${BASEDIR}"/android/build/.armv7neon 1>>"${BASEDIR}"/build.log 2>&1 rm -f "${BASEDIR}"/android/build/.armv7neon 1>>"${BASEDIR}"/build.log 2>&1
ANDROID_ARCHITECTURES="" ANDROID_ARCHITECTURES=""
if [[ ${ENABLED_ARCHITECTURES[0]} -eq 1 ]] || [[ ${ENABLED_ARCHITECTURES[1]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[ARCH_ARM_V7A]} -eq 1 ]] || [[ ${ENABLED_ARCHITECTURES[ARCH_ARM_V7A_NEON]} -eq 1 ]]; then
ANDROID_ARCHITECTURES+="$(get_android_arch 0) " ANDROID_ARCHITECTURES+="$(get_android_arch 0) "
fi fi
if [[ ${ENABLED_ARCHITECTURES[0]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[ARCH_ARM_V7A]} -eq 1 ]]; then
mkdir -p "${BASEDIR}"/android/build 1>>"${BASEDIR}"/build.log 2>&1 mkdir -p "${BASEDIR}"/android/build 1>>"${BASEDIR}"/build.log 2>&1
cat >"${BASEDIR}"/android/build/.armv7 <<EOF cat >"${BASEDIR}"/android/build/.armv7 <<EOF
EOF EOF
fi fi
if [[ ${ENABLED_ARCHITECTURES[1]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[ARCH_ARM_V7A_NEON]} -eq 1 ]]; then
mkdir -p "${BASEDIR}"/android/build 1>>"${BASEDIR}"/build.log 2>&1 mkdir -p "${BASEDIR}"/android/build 1>>"${BASEDIR}"/build.log 2>&1
cat >"${BASEDIR}"/android/build/.armv7neon <<EOF cat >"${BASEDIR}"/android/build/.armv7neon <<EOF
EOF EOF
fi fi
if [[ ${ENABLED_ARCHITECTURES[2]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[ARCH_ARM64_V8A]} -eq 1 ]]; then
ANDROID_ARCHITECTURES+="$(get_android_arch 2) " ANDROID_ARCHITECTURES+="$(get_android_arch 2) "
fi fi
if [[ ${ENABLED_ARCHITECTURES[3]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[ARCH_X86]} -eq 1 ]]; then
ANDROID_ARCHITECTURES+="$(get_android_arch 3) " ANDROID_ARCHITECTURES+="$(get_android_arch 3) "
fi fi
if [[ ${ENABLED_ARCHITECTURES[4]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[ARCH_X86_64]} -eq 1 ]]; then
ANDROID_ARCHITECTURES+="$(get_android_arch 4) " ANDROID_ARCHITECTURES+="$(get_android_arch 4) "
fi fi
# BUILD FFMPEG-KIT
if [[ -n ${ANDROID_ARCHITECTURES} ]]; then if [[ -n ${ANDROID_ARCHITECTURES} ]]; then
echo -n -e "\nffmpeg-kit: " echo -n -e "\nffmpeg-kit: "
# CREATE Application.mk FILE BEFORE STARTING THE NATIVE BUILD
build_application_mk build_application_mk
FFMPEG_KIT_AAR="${BASEDIR}"/prebuilt/android-aar/ffmpeg-kit # CLEAR OLD NATIVE LIBRARIES
# BUILDING ANDROID ARCHIVE LIBRARY
rm -rf "${BASEDIR}"/android/libs 1>>"${BASEDIR}"/build.log 2>&1 rm -rf "${BASEDIR}"/android/libs 1>>"${BASEDIR}"/build.log 2>&1
rm -rf "${BASEDIR}"/android/obj 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_KIT_AAR}" 1>>"${BASEDIR}"/build.log 2>&1
cd "${BASEDIR}"/android 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 cd "${BASEDIR}"/android 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# CLEAR OLD NDK LIBS # BUILD NATIVE LIBRARY
rm -rf "${BASEDIR}"/android/libs 1>>"${BASEDIR}"/build.log 2>&1
rm -rf "${BASEDIR}"/android/obj 1>>"${BASEDIR}"/build.log 2>&1
"${ANDROID_NDK_ROOT}"/ndk-build -B 1>>"${BASEDIR}"/build.log 2>&1 "${ANDROID_NDK_ROOT}"/ndk-build -B 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
echo "ok" echo "ok"
else else
@ -349,21 +264,23 @@ if [[ -n ${ANDROID_ARCHITECTURES} ]]; then
echo -e -n "\n\nCreating Android archive under prebuilt/android-aar: " echo -e -n "\n\nCreating Android archive under prebuilt/android-aar: "
# BUILD ANDROID ARCHIVE
./gradlew app:clean app:assembleRelease app:testReleaseUnitTest 1>>"${BASEDIR}"/build.log 2>&1 ./gradlew app:clean app:assembleRelease app:testReleaseUnitTest 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo -e "failed\n" echo -e "failed\n"
exit 1 exit 1
fi fi
# COPY ANDROID ARCHIVE TO PREBUILT DIRECTORY
FFMPEG_KIT_AAR="${BASEDIR}"/prebuilt/android-aar/ffmpeg-kit
rm -rf "${FFMPEG_KIT_AAR}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_KIT_AAR}" 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/android/app/build/outputs/aar/ffmpeg-kit-release.aar "${FFMPEG_KIT_AAR}"/ffmpeg-kit.aar 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}"/android/app/build/outputs/aar/ffmpeg-kit-release.aar "${FFMPEG_KIT_AAR}"/ffmpeg-kit.aar 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo -e "failed\n" echo -e "failed\n"
exit 1 exit 1
fi fi
echo -e "Created ffmpeg-kit Android archive successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "Created ffmpeg-kit Android archive successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "ok\n" echo -e "ok\n"
fi fi

@ -0,0 +1,7 @@
/build
/local.properties
/.idea/
/.gradle/
/libs/
/obj/
/app/build/

File diff suppressed because it is too large Load Diff

@ -0,0 +1,44 @@
apply plugin: 'com.android.library'
android {
compileSdkVersion 30
ndkVersion "21.3.6528147"
defaultConfig {
minSdkVersion 24
targetSdkVersion 30
versionCode 240440
versionName "4.4"
project.archivesBaseName = "ffmpeg-kit"
consumerProguardFiles 'proguard-rules.pro'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ["../libs"]
}
}
testOptions {
unitTests.returnDefaultValues = true
}
}
task javadoc(type: Javadoc) {
title = 'FFmpegKit'
destinationDir = file("${projectDir}/../../docs/android/javadoc")
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
source = android.sourceSets.main.java.srcDirs
}
dependencies {
testImplementation "androidx.test.ext:junit:1.1.1"
testImplementation "org.json:json:20190722"
}

@ -0,0 +1,16 @@
# 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
-keep class com.arthenica.ffmpegkit.FFmpegKitConfig {
native <methods>;
void log(long, int, byte[]);
void statistics(long, int, float, float, long , int, double, double);
}
-keep class com.arthenica.ffmpegkit.AbiDetect {
native <methods>;
}

@ -0,0 +1,2 @@
<manifest package="com.arthenica.ffmpegkit">
</manifest>

@ -0,0 +1,2 @@
/android_lts_support.o
/libandroidltssupport.a

@ -0,0 +1,69 @@
/*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <math.h>
#include <errno.h>
#include <malloc.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
#if __ANDROID_API__ < 17
int posix_memalign(void** memptr, size_t alignment, size_t size) {
if ((alignment & (alignment - 1)) != 0 || alignment == 0) {
return EINVAL;
}
if (alignment % sizeof(void*) != 0) {
return EINVAL;
}
*memptr = memalign(alignment, size);
if (*memptr == NULL) {
return errno;
}
return 0;
}
#endif /* __ANDROID_API__ < 17 */
double log2(double x) {
return (log(x) / M_LN2);
}
float log2f(float x) {
return (float) log2((double) x);
}
#ifdef __cplusplus
}; /* end of extern "C" */
#endif

@ -0,0 +1,945 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "config.h"
#include "libavcodec/jni.h"
#include "libavutil/bprint.h"
#include "fftools_ffmpeg.h"
#include "ffmpegkit.h"
#include "ffprobekit.h"
/** Callback data structure */
struct CallbackData {
int type; // 1 (log callback) or 2 (statistics callback)
long executionId; // execution id
int logLevel; // log level
AVBPrint logData; // log data
int statisticsFrameNumber; // statistics frame number
float statisticsFps; // statistics fps
float statisticsQuality; // statistics quality
int64_t statisticsSize; // statistics size
int statisticsTime; // statistics time
double statisticsBitrate; // statistics bitrate
double statisticsSpeed; // statistics speed
struct CallbackData *next;
};
/** Execution map variables */
const int EXECUTION_MAP_SIZE = 1000;
static volatile int executionMap[EXECUTION_MAP_SIZE];
static pthread_mutex_t executionMapMutex;
/** Redirection control variables */
static pthread_mutex_t lockMutex;
static pthread_mutex_t monitorMutex;
static pthread_cond_t monitorCondition;
/** Last command output variables */
static pthread_mutex_t logMutex;
static AVBPrint lastCommandOutput;
pthread_t callbackThread;
int redirectionEnabled;
struct CallbackData *callbackDataHead;
struct CallbackData *callbackDataTail;
/** Global reference to the virtual machine running */
static JavaVM *globalVm;
/** Global reference of Config class in Java */
static jclass configClass;
/** Global reference of log redirection method in Java */
static jmethodID logMethod;
/** Global reference of statistics redirection method in Java */
static jmethodID statisticsMethod;
/** Global reference of String class in Java */
static jclass stringClass;
/** Global reference of String constructor in Java */
static jmethodID stringConstructor;
/** Full name of the Config class */
const char *configClassName = "com/arthenica/ffmpegkit/Config";
/** Full name of String class */
const char *stringClassName = "java/lang/String";
/** Fields that control the handling of SIGNALs */
volatile int handleSIGQUIT = 1;
volatile int handleSIGINT = 1;
volatile int handleSIGTERM = 1;
volatile int handleSIGXCPU = 1;
volatile int handleSIGPIPE = 1;
/** Holds the id of the current execution */
__thread volatile long executionId = 0;
/** Holds the default log level */
int configuredLogLevel = AV_LOG_INFO;
/** Prototypes of native functions defined by Config class. */
JNINativeMethod configMethods[] = {
{"enableNativeRedirection", "()V", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_enableNativeRedirection},
{"disableNativeRedirection", "()V", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_disableNativeRedirection},
{"setNativeLogLevel", "(I)V", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_setNativeLogLevel},
{"getNativeLogLevel", "()I", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeLogLevel},
{"getNativeFFmpegVersion", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeFFmpegVersion},
{"getNativeVersion", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeVersion},
{"nativeFFmpegExecute", "(J[Ljava/lang/String;)I", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFmpegExecute},
{"nativeFFmpegCancel", "(J)V", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFmpegCancel},
{"nativeFFprobeExecute", "([Ljava/lang/String;)I", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFprobeExecute},
{"registerNewNativeFFmpegPipe", "(Ljava/lang/String;)I", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_registerNewNativeFFmpegPipe},
{"getNativeBuildDate", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeBuildDate},
{"setNativeEnvironmentVariable", "(Ljava/lang/String;Ljava/lang/String;)I", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_setNativeEnvironmentVariable},
{"getNativeLastCommandOutput", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeLastCommandOutput},
{"ignoreNativeSignal", "(I)V", (void*) Java_com_arthenica_ffmpegkit_FFmpegKitConfig_ignoreNativeSignal}
};
/** Forward declaration for function defined in fftools_ffmpeg.c */
int ffmpeg_execute(int argc, char **argv);
static const char *avutil_log_get_level_str(int level) {
switch (level) {
case AV_LOG_STDERR:
return "stderr";
case AV_LOG_QUIET:
return "quiet";
case AV_LOG_DEBUG:
return "debug";
case AV_LOG_VERBOSE:
return "verbose";
case AV_LOG_INFO:
return "info";
case AV_LOG_WARNING:
return "warning";
case AV_LOG_ERROR:
return "error";
case AV_LOG_FATAL:
return "fatal";
case AV_LOG_PANIC:
return "panic";
default:
return "";
}
}
static void avutil_log_format_line(void *avcl, int level, const char *fmt, va_list vl, AVBPrint part[4], int *print_prefix) {
int flags = av_log_get_flags();
AVClass* avc = avcl ? *(AVClass **) avcl : NULL;
av_bprint_init(part+0, 0, 1);
av_bprint_init(part+1, 0, 1);
av_bprint_init(part+2, 0, 1);
av_bprint_init(part+3, 0, 65536);
if (*print_prefix && avc) {
if (avc->parent_log_context_offset) {
AVClass** parent = *(AVClass ***) (((uint8_t *) avcl) +
avc->parent_log_context_offset);
if (parent && *parent) {
av_bprintf(part+0, "[%s @ %p] ",
(*parent)->item_name(parent), parent);
}
}
av_bprintf(part+1, "[%s @ %p] ",
avc->item_name(avcl), avcl);
}
if (*print_prefix && (level > AV_LOG_QUIET) && (flags & AV_LOG_PRINT_LEVEL))
av_bprintf(part+2, "[%s] ", avutil_log_get_level_str(level));
av_vbprintf(part+3, fmt, vl);
if(*part[0].str || *part[1].str || *part[2].str || *part[3].str) {
char lastc = part[3].len && part[3].len <= part[3].size ? part[3].str[part[3].len - 1] : 0;
*print_prefix = lastc == '\n' || lastc == '\r';
}
}
static void avutil_log_sanitize(uint8_t *line) {
while(*line){
if(*line < 0x08 || (*line > 0x0D && *line < 0x20))
*line='?';
line++;
}
}
void mutexInit() {
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&lockMutex, &attributes);
pthread_mutexattr_destroy(&attributes);
}
void monitorInit() {
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_condattr_t cattributes;
pthread_condattr_init(&cattributes);
pthread_condattr_setpshared(&cattributes, PTHREAD_PROCESS_PRIVATE);
pthread_mutex_init(&monitorMutex, &attributes);
pthread_mutexattr_destroy(&attributes);
pthread_cond_init(&monitorCondition, &cattributes);
pthread_condattr_destroy(&cattributes);
}
void logInit() {
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&logMutex, &attributes);
pthread_mutexattr_destroy(&attributes);
av_bprint_init(&lastCommandOutput, 0, AV_BPRINT_SIZE_UNLIMITED);
}
void executionMapLockInit() {
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&executionMapMutex, &attributes);
pthread_mutexattr_destroy(&attributes);
}
void mutexUnInit() {
pthread_mutex_destroy(&lockMutex);
}
void monitorUnInit() {
pthread_mutex_destroy(&monitorMutex);
pthread_cond_destroy(&monitorCondition);
}
void logUnInit() {
pthread_mutex_destroy(&logMutex);
}
void executionMapLockUnInit() {
pthread_mutex_destroy(&executionMapMutex);
}
void mutexLock() {
pthread_mutex_lock(&lockMutex);
}
void lastCommandOutputLock() {
pthread_mutex_lock(&logMutex);
}
void executionMapLock() {
pthread_mutex_lock(&executionMapMutex);
}
void mutexUnlock() {
pthread_mutex_unlock(&lockMutex);
}
void lastCommandOutputUnlock() {
pthread_mutex_unlock(&logMutex);
}
void executionMapUnlock() {
pthread_mutex_unlock(&executionMapMutex);
}
void clearLastCommandOutput() {
lastCommandOutputLock();
av_bprint_clear(&lastCommandOutput);
lastCommandOutputUnlock();
}
void appendLastCommandOutput(AVBPrint *logMessage) {
if (logMessage->len <= 0) {
return;
}
lastCommandOutputLock();
av_bprintf(&lastCommandOutput, "%s", logMessage->str);
lastCommandOutputUnlock();
}
void monitorWait(int milliSeconds) {
struct timeval tp;
struct timespec ts;
int rc;
rc = gettimeofday(&tp, NULL);
if (rc) {
return;
}
ts.tv_sec = tp.tv_sec;
ts.tv_nsec = tp.tv_usec * 1000;
ts.tv_sec += milliSeconds / 1000;
ts.tv_nsec += (milliSeconds % 1000)*1000000;
ts.tv_sec += ts.tv_nsec / 1000000000L;
ts.tv_nsec = ts.tv_nsec % 1000000000L;
pthread_mutex_lock(&monitorMutex);
pthread_cond_timedwait(&monitorCondition, &monitorMutex, &ts);
pthread_mutex_unlock(&monitorMutex);
}
void monitorNotify() {
pthread_mutex_lock(&monitorMutex);
pthread_cond_signal(&monitorCondition);
pthread_mutex_unlock(&monitorMutex);
}
/**
* Adds log data to the end of callback data list.
*
* @param level log level
* @param data log data
*/
void logCallbackDataAdd(int level, AVBPrint *data) {
// CREATE DATA STRUCT FIRST
struct CallbackData *newData = (struct CallbackData*)av_malloc(sizeof(struct CallbackData));
newData->type = 1;
newData->executionId = executionId;
newData->logLevel = level;
av_bprint_init(&newData->logData, 0, AV_BPRINT_SIZE_UNLIMITED);
av_bprintf(&newData->logData, "%s", data->str);
newData->next = NULL;
mutexLock();
// INSERT IT TO THE END OF QUEUE
if (callbackDataTail == NULL) {
callbackDataTail = newData;
if (callbackDataHead != NULL) {
LOGE("Dangling callback data head detected. This can cause memory leak.");
} else {
callbackDataHead = newData;
}
} else {
struct CallbackData *oldTail = callbackDataTail;
oldTail->next = newData;
callbackDataTail = newData;
}
mutexUnlock();
monitorNotify();
}
/**
* Adds statistics data to the end of callback data list.
*/
void statisticsCallbackDataAdd(int frameNumber, float fps, float quality, int64_t size, int time, double bitrate, double speed) {
// CREATE DATA STRUCT FIRST
struct CallbackData *newData = (struct CallbackData*)av_malloc(sizeof(struct CallbackData));
newData->type = 2;
newData->executionId = executionId;
newData->statisticsFrameNumber = frameNumber;
newData->statisticsFps = fps;
newData->statisticsQuality = quality;
newData->statisticsSize = size;
newData->statisticsTime = time;
newData->statisticsBitrate = bitrate;
newData->statisticsSpeed = speed;
newData->next = NULL;
mutexLock();
// INSERT IT TO THE END OF QUEUE
if (callbackDataTail == NULL) {
callbackDataTail = newData;
if (callbackDataHead != NULL) {
LOGE("Dangling callback data head detected. This can cause memory leak.");
} else {
callbackDataHead = newData;
}
} else {
struct CallbackData *oldTail = callbackDataTail;
oldTail->next = newData;
callbackDataTail = newData;
}
mutexUnlock();
monitorNotify();
}
/**
* Adds an execution id to the execution map.
*
* @param id execution id
*/
void addExecution(long id) {
executionMapLock();
int key = id % EXECUTION_MAP_SIZE;
executionMap[key] = 1;
executionMapUnlock();
}
/**
* Removes head of callback data list.
*/
struct CallbackData *callbackDataRemove() {
struct CallbackData *currentData;
mutexLock();
if (callbackDataHead == NULL) {
currentData = NULL;
} else {
currentData = callbackDataHead;
struct CallbackData *nextHead = currentData->next;
if (nextHead == NULL) {
if (callbackDataHead != callbackDataTail) {
LOGE("Head and tail callback data pointers do not match for single callback data element. This can cause memory leak.");
} else {
callbackDataTail = NULL;
}
callbackDataHead = NULL;
} else {
callbackDataHead = nextHead;
}
}
mutexUnlock();
return currentData;
}
/**
* Removes an execution id from the execution map.
*
* @param id execution id
*/
void removeExecution(long id) {
executionMapLock();
int key = id % EXECUTION_MAP_SIZE;
executionMap[key] = 0;
executionMapUnlock();
}
/**
* Checks whether a cancel request for the given execution id exists in the execution map.
*
* @param id execution id
* @return 1 if exists, false otherwise
*/
int cancelRequested(long id) {
int found = 0;
executionMapLock();
int key = id % EXECUTION_MAP_SIZE;
if (executionMap[key] == 0) {
found = 1;
}
executionMapUnlock();
return found;
}
/**
* Callback function for FFmpeg logs.
*
* @param ptr pointer to AVClass struct
* @param level log level
* @param format format string
* @param vargs arguments
*/
void ffmpegkit_log_callback_function(void *ptr, int level, const char* format, va_list vargs) {
AVBPrint fullLine;
AVBPrint part[4];
int print_prefix = 1;
if (level >= 0) {
level &= 0xff;
}
int activeLogLevel = av_log_get_level();
// AV_LOG_STDERR logs are always redirected
if ((activeLogLevel == AV_LOG_QUIET && level != AV_LOG_STDERR) || (level > activeLogLevel)) {
return;
}
av_bprint_init(&fullLine, 0, AV_BPRINT_SIZE_UNLIMITED);
avutil_log_format_line(ptr, level, format, vargs, part, &print_prefix);
avutil_log_sanitize(part[0].str);
avutil_log_sanitize(part[1].str);
avutil_log_sanitize(part[2].str);
avutil_log_sanitize(part[3].str);
// COMBINE ALL 4 LOG PARTS
av_bprintf(&fullLine, "%s%s%s%s", part[0].str, part[1].str, part[2].str, part[3].str);
if (fullLine.len > 0) {
logCallbackDataAdd(level, &fullLine);
appendLastCommandOutput(&fullLine);
}
av_bprint_finalize(part, NULL);
av_bprint_finalize(part+1, NULL);
av_bprint_finalize(part+2, NULL);
av_bprint_finalize(part+3, NULL);
av_bprint_finalize(&fullLine, NULL);
}
/**
* Callback function for FFmpeg statistics.
*
* @param frameNumber last processed frame number
* @param fps frames processed per second
* @param quality quality of the output stream (video only)
* @param size size in bytes
* @param time processed output duration
* @param bitrate output bit rate in kbits/s
* @param speed processing speed = processed duration / operation duration
*/
void ffmpegkit_statistics_callback_function(int frameNumber, float fps, float quality, int64_t size, int time, double bitrate, double speed) {
statisticsCallbackDataAdd(frameNumber, fps, quality, size, time, bitrate, speed);
}
/**
* Forwards callback messages to Java classes.
*/
void *callbackThreadFunction() {
JNIEnv *env;
jint getEnvRc = (*globalVm)->GetEnv(globalVm, (void**) &env, JNI_VERSION_1_6);
if (getEnvRc != JNI_OK) {
if (getEnvRc != JNI_EDETACHED) {
LOGE("Callback thread failed to GetEnv for class %s with rc %d.\n", configClassName, getEnvRc);
return NULL;
}
if ((*globalVm)->AttachCurrentThread(globalVm, &env, NULL) != 0) {
LOGE("Callback thread failed to AttachCurrentThread for class %s.\n", configClassName);
return NULL;
}
}
LOGD("Callback thread started.\n");
while(redirectionEnabled) {
struct CallbackData *callbackData = callbackDataRemove();
if (callbackData != NULL) {
if (callbackData->type == 1) {
// LOG CALLBACK
int size = callbackData->logData.len;
jbyteArray byteArray = (jbyteArray) (*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, byteArray, 0, size, callbackData->logData.str);
(*env)->CallStaticVoidMethod(env, configClass, logMethod, (jlong) callbackData->executionId, callbackData->logLevel, byteArray);
(*env)->DeleteLocalRef(env, byteArray);
// CLEAN LOG DATA
av_bprint_finalize(&callbackData->logData, NULL);
} else {
// STATISTICS CALLBACK
(*env)->CallStaticVoidMethod(env, configClass, statisticsMethod,
(jlong) callbackData->executionId, callbackData->statisticsFrameNumber,
callbackData->statisticsFps, callbackData->statisticsQuality,
callbackData->statisticsSize, callbackData->statisticsTime,
callbackData->statisticsBitrate, callbackData->statisticsSpeed);
}
// CLEAN STRUCT
callbackData->next = NULL;
av_free(callbackData);
} else {
monitorWait(100);
}
}
(*globalVm)->DetachCurrentThread(globalVm);
LOGD("Callback thread stopped.\n");
return NULL;
}
/**
* Called when 'ffmpegkit' native library is loaded.
*
* @param vm pointer to the running virtual machine
* @param reserved reserved
* @return JNI version needed by 'ffmpegkit' library
*/
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env;
if ((*vm)->GetEnv(vm, (void**)(&env), JNI_VERSION_1_6) != JNI_OK) {
LOGE("OnLoad failed to GetEnv for class %s.\n", configClassName);
return JNI_FALSE;
}
jclass localConfigClass = (*env)->FindClass(env, configClassName);
if (localConfigClass == NULL) {
LOGE("OnLoad failed to FindClass %s.\n", configClassName);
return JNI_FALSE;
}
if ((*env)->RegisterNatives(env, localConfigClass, configMethods, 12) < 0) {
LOGE("OnLoad failed to RegisterNatives for class %s.\n", configClassName);
return JNI_FALSE;
}
jclass localStringClass = (*env)->FindClass(env, stringClassName);
if (localStringClass == NULL) {
LOGE("OnLoad failed to FindClass %s.\n", stringClassName);
return JNI_FALSE;
}
(*env)->GetJavaVM(env, &globalVm);
logMethod = (*env)->GetStaticMethodID(env, localConfigClass, "log", "(JI[B)V");
if (logMethod == NULL) {
LOGE("OnLoad thread failed to GetStaticMethodID for %s.\n", "log");
return JNI_FALSE;
}
statisticsMethod = (*env)->GetStaticMethodID(env, localConfigClass, "statistics", "(JIFFJIDD)V");
if (logMethod == NULL) {
LOGE("OnLoad thread failed to GetStaticMethodID for %s.\n", "statistics");
return JNI_FALSE;
}
stringConstructor = (*env)->GetMethodID(env, localStringClass, "<init>", "([BLjava/lang/String;)V");
if (stringConstructor == NULL) {
LOGE("OnLoad thread failed to GetMethodID for %s.\n", "<init>");
return JNI_FALSE;
}
av_jni_set_java_vm(vm, NULL);
configClass = (jclass) ((*env)->NewGlobalRef(env, localConfigClass));
stringClass = (jclass) ((*env)->NewGlobalRef(env, localStringClass));
redirectionEnabled = 0;
callbackDataHead = NULL;
callbackDataTail = NULL;
for(int i = 0; i<EXECUTION_MAP_SIZE; i++) {
executionMap[i] = 0;
}
mutexInit();
monitorInit();
logInit();
executionMapLockInit();
return JNI_VERSION_1_6;
}
/**
* Sets log level.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param level log level
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_setNativeLogLevel(JNIEnv *env, jclass object, jint level) {
configuredLogLevel = level;
}
/**
* Returns current log level.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
*/
JNIEXPORT jint JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeLogLevel(JNIEnv *env, jclass object) {
return configuredLogLevel;
}
/**
* Enables log and statistics redirection.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_enableNativeRedirection(JNIEnv *env, jclass object) {
mutexLock();
if (redirectionEnabled != 0) {
mutexUnlock();
return;
}
redirectionEnabled = 1;
mutexUnlock();
int rc = pthread_create(&callbackThread, 0, callbackThreadFunction, 0);
if (rc != 0) {
LOGE("Failed to create callback thread (rc=%d).\n", rc);
return;
}
av_log_set_callback(ffmpegkit_log_callback_function);
set_report_callback(ffmpegkit_statistics_callback_function);
}
/**
* Disables log and statistics redirection.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_disableNativeRedirection(JNIEnv *env, jclass object) {
mutexLock();
if (redirectionEnabled != 1) {
mutexUnlock();
return;
}
redirectionEnabled = 0;
mutexUnlock();
av_log_set_callback(av_log_default_callback);
set_report_callback(NULL);
monitorNotify();
}
/**
* Returns FFmpeg version bundled within the library natively.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return FFmpeg version string
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeFFmpegVersion(JNIEnv *env, jclass object) {
return (*env)->NewStringUTF(env, FFMPEG_VERSION);
}
/**
* Returns FFmpegKit library version natively.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return FFmpegKit version string
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeVersion(JNIEnv *env, jclass object) {
return (*env)->NewStringUTF(env, FFMPEG_KIT_VERSION);
}
/**
* Synchronously executes FFmpeg natively with arguments provided.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param id execution id
* @param stringArray reference to the object holding FFmpeg command arguments
* @return zero on successful execution, non-zero on error
*/
JNIEXPORT jint JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFmpegExecute(JNIEnv *env, jclass object, jlong id, jobjectArray stringArray) {
jstring *tempArray = NULL;
int argumentCount = 1;
char **argv = NULL;
// SETS DEFAULT LOG LEVEL BEFORE STARTING A NEW EXECUTION
av_log_set_level(configuredLogLevel);
if (stringArray != NULL) {
int programArgumentCount = (*env)->GetArrayLength(env, stringArray);
argumentCount = programArgumentCount + 1;
tempArray = (jstring *) av_malloc(sizeof(jstring) * programArgumentCount);
}
/* PRESERVE USAGE FORMAT
*
* ffmpeg <arguments>
*/
argv = (char **)av_malloc(sizeof(char*) * (argumentCount));
argv[0] = (char *)av_malloc(sizeof(char) * (strlen(LIB_NAME) + 1));
strcpy(argv[0], LIB_NAME);
// PREPARE
if (stringArray != NULL) {
for (int i = 0; i < (argumentCount - 1); i++) {
tempArray[i] = (jstring) (*env)->GetObjectArrayElement(env, stringArray, i);
if (tempArray[i] != NULL) {
argv[i + 1] = (char *) (*env)->GetStringUTFChars(env, tempArray[i], 0);
}
}
}
// LAST COMMAND OUTPUT SHOULD BE CLEARED BEFORE STARTING A NEW EXECUTION
clearLastCommandOutput();
// REGISTER THE ID BEFORE STARTING EXECUTION
executionId = (long) id;
addExecution((long) id);
// RUN
int retCode = ffmpeg_execute(argumentCount, argv);
// ALWAYS REMOVE THE ID FROM THE MAP
removeExecution((long) id);
// CLEANUP
if (tempArray != NULL) {
for (int i = 0; i < (argumentCount - 1); i++) {
(*env)->ReleaseStringUTFChars(env, tempArray[i], argv[i + 1]);
}
av_free(tempArray);
}
av_free(argv[0]);
av_free(argv);
return retCode;
}
/**
* Cancels an ongoing FFmpeg operation natively.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param id execution id
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFmpegCancel(JNIEnv *env, jclass object, jlong id) {
cancel_operation(id);
}
/**
* Creates natively a new named pipe to use in FFmpeg operations.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param ffmpegPipePath full path of ffmpeg pipe
* @return zero on successful creation, non-zero on error
*/
JNIEXPORT int JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_registerNewNativeFFmpegPipe(JNIEnv *env, jclass object, jstring ffmpegPipePath) {
const char *ffmpegPipePathString = (*env)->GetStringUTFChars(env, ffmpegPipePath, 0);
return mkfifo(ffmpegPipePathString, S_IRWXU | S_IRWXG | S_IROTH);
}
/**
* Returns FFmpegKit library build date natively.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return FFmpegKit library build date
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeBuildDate(JNIEnv *env, jclass object) {
char buildDate[10];
sprintf(buildDate, "%d", FFMPEG_KIT_BUILD_DATE);
return (*env)->NewStringUTF(env, buildDate);
}
/**
* Sets an environment variable natively
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param variableName environment variable name
* @param variableValue environment variable value
* @return zero on success, non-zero on error
*/
JNIEXPORT int JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_setNativeEnvironmentVariable(JNIEnv *env, jclass object, jstring variableName, jstring variableValue) {
const char *variableNameString = (*env)->GetStringUTFChars(env, variableName, 0);
const char *variableValueString = (*env)->GetStringUTFChars(env, variableValue, 0);
int rc = setenv(variableNameString, variableValueString, 1);
(*env)->ReleaseStringUTFChars(env, variableName, variableNameString);
(*env)->ReleaseStringUTFChars(env, variableValue, variableValueString);
return rc;
}
/**
* Returns log output of the last executed command natively.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return output of the last executed command
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeLastCommandOutput(JNIEnv *env, jclass object) {
int size = lastCommandOutput.len;
if (size > 0) {
jbyteArray byteArray = (*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, byteArray, 0, size, lastCommandOutput.str);
jstring charsetName = (*env)->NewStringUTF(env, "UTF-8");
return (jstring) (*env)->NewObject(env, stringClass, stringConstructor, byteArray, charsetName);
}
return (*env)->NewStringUTF(env, "");
}
/**
* Registers a new ignored signal. Ignored signals are not handled by the library.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param signum signal number
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_ignoreNativeSignal(JNIEnv *env, jclass object, jint signum) {
if (signum == SIGQUIT) {
handleSIGQUIT = 0;
} else if (signum == SIGINT) {
handleSIGINT = 0;
} else if (signum == SIGTERM) {
handleSIGTERM = 0;
} else if (signum == SIGXCPU) {
handleSIGXCPU = 0;
} else if (signum == SIGPIPE) {
handleSIGPIPE = 0;
}
}

@ -0,0 +1,141 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FFMPEG_KIT_H
#define FFMPEG_KIT_H
#include <jni.h>
#include <android/log.h>
#include "libavutil/log.h"
#include "libavutil/ffversion.h"
/** Library version string */
#define FFMPEG_KIT_VERSION "4.4"
/** Defines tag used for Android logging. */
#define LIB_NAME "ffmpeg-kit"
/** Verbose Android logging macro. */
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LIB_NAME, __VA_ARGS__)
/** Debug Android logging macro. */
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LIB_NAME, __VA_ARGS__)
/** Info Android logging macro. */
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LIB_NAME, __VA_ARGS__)
/** Warn Android logging macro. */
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LIB_NAME, __VA_ARGS__)
/** Error Android logging macro. */
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LIB_NAME, __VA_ARGS__)
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: enableNativeRedirection
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_enableNativeRedirection(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: disableNativeRedirection
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_disableNativeRedirection(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: setNativeLogLevel
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_setNativeLogLevel(JNIEnv *, jclass, jint);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: getNativeLogLevel
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeLogLevel(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: getNativeFFmpegVersion
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeFFmpegVersion(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: getNativeVersion
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeVersion(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: nativeFFmpegExecute
* Signature: (J[Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFmpegExecute(JNIEnv *, jclass, jlong id, jobjectArray);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: nativeFFmpegCancel
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFmpegCancel(JNIEnv *, jclass, jlong);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: registerNewNativeFFmpegPipe
* Signature: (Ljava/lang/String;)I
*/
JNIEXPORT int JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_registerNewNativeFFmpegPipe(JNIEnv *env, jclass object, jstring ffmpegPipePath);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: getNativeBuildDate
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeBuildDate(JNIEnv *env, jclass object);
/**
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: setNativeEnvironmentVariable
* Signature: (Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT int JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_setNativeEnvironmentVariable(JNIEnv *env, jclass object, jstring variableName, jstring variableValue);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: getNativeLastCommandOutput
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_getNativeLastCommandOutput(JNIEnv *env, jclass object);
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: ignoreNativeSignal
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_ignoreNativeSignal(JNIEnv *env, jclass object, jint signum);
#endif /* FFMPEG_KIT_H */

@ -0,0 +1,144 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cpu-features.h"
#include "fftools_ffmpeg.h"
#include "ffmpegkit_abidetect.h"
/** Full name of the Java class that owns native functions in this file. */
const char *abiDetectClassName = "com/arthenica/ffmpegkit/AbiDetect";
/** Prototypes of native functions defined by this file. */
JNINativeMethod abiDetectMethods[] = {
{"getNativeAbi", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_AbiDetect_getNativeAbi},
{"getNativeCpuAbi", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_AbiDetect_getNativeCpuAbi},
{"isNativeLTSBuild", "()Z", (void*) Java_com_arthenica_ffmpegkit_AbiDetect_isNativeLTSBuild},
{"getNativeBuildConf", "()Ljava/lang/String;", (void*) Java_com_arthenica_ffmpegkit_AbiDetect_getNativeBuildConf}
};
/**
* Called when 'abidetect' native library is loaded.
*
* @param vm pointer to the running virtual machine
* @param reserved reserved
* @return JNI version needed by 'abidetect' library
*/
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env;
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) {
LOGE("OnLoad failed to GetEnv for class %s.\n", abiDetectClassName);
return JNI_FALSE;
}
jclass abiDetectClass = (*env)->FindClass(env, abiDetectClassName);
if (abiDetectClass == NULL) {
LOGE("OnLoad failed to FindClass %s.\n", abiDetectClassName);
return JNI_FALSE;
}
if ((*env)->RegisterNatives(env, abiDetectClass, abiDetectMethods, 4) < 0) {
LOGE("OnLoad failed to RegisterNatives for class %s.\n", abiDetectClassName);
return JNI_FALSE;
}
return JNI_VERSION_1_6;
}
/**
* Returns loaded ABI name.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return loaded ABI name as UTF string
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_getNativeAbi(JNIEnv *env, jclass object) {
#ifdef FFMPEG_KIT_ARM_V7A
return (*env)->NewStringUTF(env, "arm-v7a");
#elif FFMPEG_KIT_ARM64_V8A
return (*env)->NewStringUTF(env, "arm64-v8a");
#elif FFMPEG_KIT_X86
return (*env)->NewStringUTF(env, "x86");
#elif FFMPEG_KIT_X86_64
return (*env)->NewStringUTF(env, "x86_64");
#else
return (*env)->NewStringUTF(env, "unknown");
#endif
}
/**
* Returns ABI name of the running cpu.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return ABI name of the running cpu as UTF string
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_getNativeCpuAbi(JNIEnv *env, jclass object) {
AndroidCpuFamily family = android_getCpuFamily();
if (family == ANDROID_CPU_FAMILY_ARM) {
uint64_t features = android_getCpuFeatures();
if (features & ANDROID_CPU_ARM_FEATURE_ARMv7) {
if (features & ANDROID_CPU_ARM_FEATURE_NEON) {
return (*env)->NewStringUTF(env, ABI_ARMV7A_NEON);
} else {
return (*env)->NewStringUTF(env, ABI_ARMV7A);
}
} else {
return (*env)->NewStringUTF(env, ABI_ARM);
}
} else if (family == ANDROID_CPU_FAMILY_ARM64) {
return (*env)->NewStringUTF(env, ABI_ARM64_V8A);
} else if (family == ANDROID_CPU_FAMILY_X86) {
return (*env)->NewStringUTF(env, ABI_X86);
} else if (family == ANDROID_CPU_FAMILY_X86_64) {
return (*env)->NewStringUTF(env, ABI_X86_64);
} else {
return (*env)->NewStringUTF(env, ABI_UNKNOWN);
}
}
/**
* Returns whether FFmpegKit release is a long term release or not.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return yes or no
*/
JNIEXPORT jboolean JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_isNativeLTSBuild(JNIEnv *env, jclass object) {
#if defined(FFMPEG_KIT_LTS)
return JNI_TRUE;
#else
return JNI_FALSE;
#endif
}
/**
* Returns build configuration for FFmpeg.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @return build configuration string
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_getNativeBuildConf(JNIEnv *env, jclass object) {
return (*env)->NewStringUTF(env, FFMPEG_CONFIGURATION);
}

@ -0,0 +1,75 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FFMPEG_KIT_ABIDETECT_H
#define FFMPEG_KIT_ABIDETECT_H
#include <jni.h>
#include "ffmpegkit.h"
/** Represents armeabi-v7a ABI with NEON support. */
#define ABI_ARMV7A_NEON "armeabi-v7a-neon"
/** Represents armeabi-v7a ABI. */
#define ABI_ARMV7A "armeabi-v7a"
/** Represents armeabi ABI. */
#define ABI_ARM "armeabi"
/** Represents x86 ABI. */
#define ABI_X86 "x86"
/** Represents x86_64 ABI. */
#define ABI_X86_64 "x86_64"
/** Represents arm64-v8a ABI. */
#define ABI_ARM64_V8A "arm64-v8a"
/** Represents not supported ABIs. */
#define ABI_UNKNOWN "unknown"
/*
* Class: com_arthenica_ffmpegkit_AbiDetect
* Method: getNativeAbi
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_getNativeAbi(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_AbiDetect
* Method: getNativeCpuAbi
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_getNativeCpuAbi(JNIEnv *, jclass);
/**
* Class: com_arthenica_ffmpegkit_AbiDetect
* Method: isNativeLTSBuild
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_isNativeLTSBuild(JNIEnv *, jclass);
/*
* Class: com_arthenica_ffmpegkit_AbiDetect
* Method: getNativeBuildConf
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_arthenica_ffmpegkit_AbiDetect_getNativeBuildConf(JNIEnv *, jclass);
#endif /* FFMPEG_KIT_ABIDETECT_H */

@ -0,0 +1,24 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <setjmp.h>
/** Holds information to implement exception handling. */
__thread jmp_buf ex_buf__;

@ -0,0 +1,29 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FFMPEG_KIT_EXCEPTION_H
#define FFMPEG_KIT_EXCEPTION_H
#include <stdio.h>
#include <setjmp.h>
/** Holds information to implement exception handling. */
extern __thread jmp_buf ex_buf__;
#endif // FFMPEG_KIT_EXCEPTION_H

@ -0,0 +1,96 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "config.h"
#include "libavcodec/jni.h"
#include "libavutil/bprint.h"
#include "ffmpegkit.h"
/** Forward declaration for function defined in fftools_ffprobe.c */
int ffprobe_execute(int argc, char **argv);
/** Forward declaration for function defined in ffmpegkit.c */
void clearLastCommandOutput();
extern int configuredLogLevel;
/**
* Synchronously executes FFprobe natively with arguments provided.
*
* @param env pointer to native method interface
* @param object reference to the class on which this method is invoked
* @param stringArray reference to the object holding FFprobe command arguments
* @return zero on successful execution, non-zero on error
*/
JNIEXPORT jint JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFprobeExecute(JNIEnv *env, jclass object, jobjectArray stringArray) {
jstring *tempArray = NULL;
int argumentCount = 1;
char **argv = NULL;
// SETS DEFAULT LOG LEVEL BEFORE STARTING A NEW EXECUTION
av_log_set_level(configuredLogLevel);
if (stringArray != NULL) {
int programArgumentCount = (*env)->GetArrayLength(env, stringArray);
argumentCount = programArgumentCount + 1;
tempArray = (jstring *) av_malloc(sizeof(jstring) * programArgumentCount);
}
/* PRESERVE USAGE FORMAT
*
* ffprobe <arguments>
*/
argv = (char **)av_malloc(sizeof(char*) * (argumentCount));
argv[0] = (char *)av_malloc(sizeof(char) * (strlen(LIB_NAME) + 1));
strcpy(argv[0], LIB_NAME);
// PREPARE
if (stringArray != NULL) {
for (int i = 0; i < (argumentCount - 1); i++) {
tempArray[i] = (jstring) (*env)->GetObjectArrayElement(env, stringArray, i);
if (tempArray[i] != NULL) {
argv[i + 1] = (char *) (*env)->GetStringUTFChars(env, tempArray[i], 0);
}
}
}
// LAST COMMAND OUTPUT SHOULD BE CLEARED BEFORE STARTING A NEW EXECUTION
clearLastCommandOutput();
// RUN
int retCode = ffprobe_execute(argumentCount, argv);
// CLEANUP
if (tempArray != NULL) {
for (int i = 0; i < (argumentCount - 1); i++) {
(*env)->ReleaseStringUTFChars(env, tempArray[i], argv[i + 1]);
}
av_free(tempArray);
}
av_free(argv[0]);
av_free(argv);
return retCode;
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FFPROBE_KIT_H
#define FFPROBE_KIT_H
#include <jni.h>
/*
* Class: com_arthenica_ffmpegkit_FFmpegKitConfig
* Method: nativeFFprobeExecute
* Signature: ([Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_arthenica_ffmpegkit_FFmpegKitConfig_nativeFFprobeExecute(JNIEnv *, jclass, jobjectArray);
#endif /* FFPROBE_KIT_H */

File diff suppressed because it is too large Load Diff

@ -0,0 +1,636 @@
/*
* Various utilities for command line tools
* copyright (c) 2003 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* CHANGES 01.2020
* - ffprobe support changes
* - AV_LOG_STDERR introduced
*
* CHANGES 12.2019
* - Concurrent execution support
*
* CHANGES 03.2019
* --------------------------------------------------------
* - config.h include removed
*
* CHANGES 08.2018
* --------------------------------------------------------
* - fftools_ prefix added to file name and include guards
*
* CHANGES 07.2018
* --------------------------------------------------------
* - Include guards renamed
* - Unused headers removed
*/
#ifndef FFTOOLS_CMDUTILS_H
#define FFTOOLS_CMDUTILS_H
#include <stdint.h>
#include "libavcodec/avcodec.h"
#include "libavfilter/avfilter.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#ifdef _WIN32
#undef main /* We don't want SDL to override our main() */
#endif
/**
* Defines logs printed to stderr by ffmpeg. They are not filtered and always redirected.
*/
#define AV_LOG_STDERR -16
/**
* program name, defined by the program for show_version().
*/
extern __thread char *program_name;
/**
* program birth year, defined by the program for show_banner()
*/
extern __thread int program_birth_year;
extern __thread AVCodecContext *avcodec_opts[AVMEDIA_TYPE_NB];
extern __thread AVFormatContext *avformat_opts;
extern __thread AVDictionary *sws_dict;
extern __thread AVDictionary *swr_opts;
extern __thread AVDictionary *format_opts, *codec_opts, *resample_opts;
extern __thread int hide_banner;
extern __thread int find_stream_info;
/**
* Register a program-specific cleanup routine.
*/
void register_exit(void (*cb)(int ret));
/**
* Wraps exit with a program-specific cleanup routine.
*/
void exit_program(int ret) av_noreturn;
/**
* Initialize dynamic library loading
*/
void init_dynload(void);
/**
* Initialize the cmdutils option system, in particular
* allocate the *_opts contexts.
*/
void init_opts(void);
/**
* Uninitialize the cmdutils option system, in particular
* free the *_opts contexts and their contents.
*/
void uninit_opts(void);
/**
* Trivial log callback.
* Only suitable for opt_help and similar since it lacks prefix handling.
*/
void log_callback_help(void* ptr, int level, const char* fmt, va_list vl);
/**
* Override the cpuflags.
*/
int opt_cpuflags(void *optctx, const char *opt, const char *arg);
/**
* Fallback for options that are not explicitly handled, these will be
* parsed through AVOptions.
*/
int opt_default(void *optctx, const char *opt, const char *arg);
/**
* Set the libav* libraries log level.
*/
int opt_loglevel(void *optctx, const char *opt, const char *arg);
int opt_report(void *optctx, const char *opt, const char *arg);
int opt_max_alloc(void *optctx, const char *opt, const char *arg);
int opt_codec_debug(void *optctx, const char *opt, const char *arg);
/**
* Limit the execution time.
*/
int opt_timelimit(void *optctx, const char *opt, const char *arg);
/**
* Parse a string and return its corresponding value as a double.
* Exit from the application if the string cannot be correctly
* parsed or the corresponding value is invalid.
*
* @param context the context of the value to be set (e.g. the
* corresponding command line option name)
* @param numstr the string to be parsed
* @param type the type (OPT_INT64 or OPT_FLOAT) as which the
* string should be parsed
* @param min the minimum valid accepted value
* @param max the maximum valid accepted value
*/
double parse_number_or_die(const char *context, const char *numstr, int type,
double min, double max);
/**
* Parse a string specifying a time and return its corresponding
* value as a number of microseconds. Exit from the application if
* the string cannot be correctly parsed.
*
* @param context the context of the value to be set (e.g. the
* corresponding command line option name)
* @param timestr the string to be parsed
* @param is_duration a flag which tells how to interpret timestr, if
* not zero timestr is interpreted as a duration, otherwise as a
* date
*
* @see av_parse_time()
*/
int64_t parse_time_or_die(const char *context, const char *timestr,
int is_duration);
typedef struct SpecifierOpt {
char *specifier; /**< stream/chapter/program/... specifier */
union {
uint8_t *str;
int i;
int64_t i64;
uint64_t ui64;
float f;
double dbl;
} u;
} SpecifierOpt;
typedef struct OptionDef {
const char *name;
int flags;
#define HAS_ARG 0x0001
#define OPT_BOOL 0x0002
#define OPT_EXPERT 0x0004
#define OPT_STRING 0x0008
#define OPT_VIDEO 0x0010
#define OPT_AUDIO 0x0020
#define OPT_INT 0x0080
#define OPT_FLOAT 0x0100
#define OPT_SUBTITLE 0x0200
#define OPT_INT64 0x0400
#define OPT_EXIT 0x0800
#define OPT_DATA 0x1000
#define OPT_PERFILE 0x2000 /* the option is per-file (currently ffmpeg-only).
implied by OPT_OFFSET or OPT_SPEC */
#define OPT_OFFSET 0x4000 /* option is specified as an offset in a passed optctx */
#define OPT_SPEC 0x8000 /* option is to be stored in an array of SpecifierOpt.
Implies OPT_OFFSET. Next element after the offset is
an int containing element count in the array. */
#define OPT_TIME 0x10000
#define OPT_DOUBLE 0x20000
#define OPT_INPUT 0x40000
#define OPT_OUTPUT 0x80000
union {
void *dst_ptr;
int (*func_arg)(void *, const char *, const char *);
size_t off;
} u;
const char *help;
const char *argname;
} OptionDef;
/**
* Print help for all options matching specified flags.
*
* @param options a list of options
* @param msg title of this group. Only printed if at least one option matches.
* @param req_flags print only options which have all those flags set.
* @param rej_flags don't print options which have any of those flags set.
* @param alt_flags print only options that have at least one of those flags set
*/
void show_help_options(const OptionDef *options, const char *msg, int req_flags,
int rej_flags, int alt_flags);
/**
* Show help for all options with given flags in class and all its
* children.
*/
void show_help_children(const AVClass *class, int flags);
/**
* Per-fftool specific help handlers. Implemented in each
* fftool, called by show_help().
*/
void show_help_default_ffmpeg(const char *opt, const char *arg);
void show_help_default_ffprobe(const char *opt, const char *arg);
/**
* Generic -h handler common to all fftools.
*/
int show_help(void *optctx, const char *opt, const char *arg);
/**
* Parse the command line arguments.
*
* @param optctx an opaque options context
* @param argc number of command line arguments
* @param argv values of command line arguments
* @param options Array with the definitions required to interpret every
* option of the form: -option_name [argument]
* @param parse_arg_function Name of the function called to process every
* argument without a leading option name flag. NULL if such arguments do
* not have to be processed.
*/
void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
void (* parse_arg_function)(void *optctx, const char*));
/**
* Parse one given option.
*
* @return on success 1 if arg was consumed, 0 otherwise; negative number on error
*/
int parse_option(void *optctx, const char *opt, const char *arg,
const OptionDef *options);
/**
* An option extracted from the commandline.
* Cannot use AVDictionary because of options like -map which can be
* used multiple times.
*/
typedef struct Option {
const OptionDef *opt;
const char *key;
const char *val;
} Option;
typedef struct OptionGroupDef {
/**< group name */
const char *name;
/**
* Option to be used as group separator. Can be NULL for groups which
* are terminated by a non-option argument (e.g. ffmpeg output files)
*/
const char *sep;
/**
* Option flags that must be set on each option that is
* applied to this group
*/
int flags;
} OptionGroupDef;
typedef struct OptionGroup {
const OptionGroupDef *group_def;
const char *arg;
Option *opts;
int nb_opts;
AVDictionary *codec_opts;
AVDictionary *format_opts;
AVDictionary *resample_opts;
AVDictionary *sws_dict;
AVDictionary *swr_opts;
} OptionGroup;
/**
* A list of option groups that all have the same group type
* (e.g. input files or output files)
*/
typedef struct OptionGroupList {
const OptionGroupDef *group_def;
OptionGroup *groups;
int nb_groups;
} OptionGroupList;
typedef struct OptionParseContext {
OptionGroup global_opts;
OptionGroupList *groups;
int nb_groups;
/* parsing state */
OptionGroup cur_group;
} OptionParseContext;
/**
* Parse an options group and write results into optctx.
*
* @param optctx an app-specific options context. NULL for global options group
* @param g option group
*/
int parse_optgroup(void *optctx, OptionGroup *g);
/**
* Split the commandline into an intermediate form convenient for further
* processing.
*
* The commandline is assumed to be composed of options which either belong to a
* group (those with OPT_SPEC, OPT_OFFSET or OPT_PERFILE) or are global
* (everything else).
*
* A group (defined by an OptionGroupDef struct) is a sequence of options
* terminated by either a group separator option (e.g. -i) or a parameter that
* is not an option (doesn't start with -). A group without a separator option
* must always be first in the supplied groups list.
*
* All options within the same group are stored in one OptionGroup struct in an
* OptionGroupList, all groups with the same group definition are stored in one
* OptionGroupList in OptionParseContext.groups. The order of group lists is the
* same as the order of group definitions.
*/
int split_commandline(OptionParseContext *octx, int argc, char *argv[],
const OptionDef *options,
const OptionGroupDef *groups, int nb_groups);
/**
* Free all allocated memory in an OptionParseContext.
*/
void uninit_parse_context(OptionParseContext *octx);
/**
* Find the '-loglevel' option in the command line args and apply it.
*/
void parse_loglevel(int argc, char **argv, const OptionDef *options);
/**
* Return index of option opt in argv or 0 if not found.
*/
int locate_option(int argc, char **argv, const OptionDef *options,
const char *optname);
/**
* Check if the given stream matches a stream specifier.
*
* @param s Corresponding format context.
* @param st Stream from s to be checked.
* @param spec A stream specifier of the [v|a|s|d]:[\<stream index\>] form.
*
* @return 1 if the stream matches, 0 if it doesn't, <0 on error
*/
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec);
/**
* Filter out options for given codec.
*
* Create a new options dictionary containing only the options from
* opts which apply to the codec with ID codec_id.
*
* @param opts dictionary to place options in
* @param codec_id ID of the codec that should be filtered for
* @param s Corresponding format context.
* @param st A stream from s for which the options should be filtered.
* @param codec The particular codec for which the options should be filtered.
* If null, the default one is looked up according to the codec id.
* @return a pointer to the created dictionary
*/
AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
AVFormatContext *s, AVStream *st, AVCodec *codec);
/**
* Setup AVCodecContext options for avformat_find_stream_info().
*
* Create an array of dictionaries, one dictionary for each stream
* contained in s.
* Each dictionary will contain the options from codec_opts which can
* be applied to the corresponding stream codec context.
*
* @return pointer to the created array of dictionaries, NULL if it
* cannot be created
*/
AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
AVDictionary *codec_opts);
/**
* Print an error message to stderr, indicating filename and a human
* readable description of the error code err.
*
* If strerror_r() is not available the use of this function in a
* multithreaded application may be unsafe.
*
* @see av_strerror()
*/
void print_error(const char *filename, int err);
/**
* Print the program banner to stderr. The banner contents depend on the
* current version of the repository and of the libav* libraries used by
* the program.
*/
void show_banner(int argc, char **argv, const OptionDef *options);
/**
* Print the version of the program to stdout. The version message
* depends on the current versions of the repository and of the libav*
* libraries.
* This option processing function does not utilize the arguments.
*/
int show_version(void *optctx, const char *opt, const char *arg);
/**
* Print the build configuration of the program to stdout. The contents
* depend on the definition of FFMPEG_CONFIGURATION.
* This option processing function does not utilize the arguments.
*/
int show_buildconf(void *optctx, const char *opt, const char *arg);
/**
* Print the license of the program to stdout. The license depends on
* the license of the libraries compiled into the program.
* This option processing function does not utilize the arguments.
*/
int show_license(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the formats supported by the
* program (including devices).
* This option processing function does not utilize the arguments.
*/
int show_formats(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the muxers supported by the
* program (including devices).
* This option processing function does not utilize the arguments.
*/
int show_muxers(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the demuxer supported by the
* program (including devices).
* This option processing function does not utilize the arguments.
*/
int show_demuxers(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the devices supported by the
* program.
* This option processing function does not utilize the arguments.
*/
int show_devices(void *optctx, const char *opt, const char *arg);
#if CONFIG_AVDEVICE
/**
* Print a listing containing autodetected sinks of the output device.
* Device name with options may be passed as an argument to limit results.
*/
int show_sinks(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing autodetected sources of the input device.
* Device name with options may be passed as an argument to limit results.
*/
int show_sources(void *optctx, const char *opt, const char *arg);
#endif
/**
* Print a listing containing all the codecs supported by the
* program.
* This option processing function does not utilize the arguments.
*/
int show_codecs(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the decoders supported by the
* program.
*/
int show_decoders(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the encoders supported by the
* program.
*/
int show_encoders(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the filters supported by the
* program.
* This option processing function does not utilize the arguments.
*/
int show_filters(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the bit stream filters supported by the
* program.
* This option processing function does not utilize the arguments.
*/
int show_bsfs(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the protocols supported by the
* program.
* This option processing function does not utilize the arguments.
*/
int show_protocols(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the pixel formats supported by the
* program.
* This option processing function does not utilize the arguments.
*/
int show_pix_fmts(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the standard channel layouts supported by
* the program.
* This option processing function does not utilize the arguments.
*/
int show_layouts(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the sample formats supported by the
* program.
*/
int show_sample_fmts(void *optctx, const char *opt, const char *arg);
/**
* Print a listing containing all the color names and values recognized
* by the program.
*/
int show_colors(void *optctx, const char *opt, const char *arg);
/**
* Return a positive value if a line read from standard input
* starts with [yY], otherwise return 0.
*/
int read_yesno(void);
/**
* Get a file corresponding to a preset file.
*
* If is_path is non-zero, look for the file in the path preset_name.
* Otherwise search for a file named arg.ffpreset in the directories
* $FFMPEG_DATADIR (if set), $HOME/.ffmpeg, and in the datadir defined
* at configuration time or in a "ffpresets" folder along the executable
* on win32, in that order. If no such file is found and
* codec_name is defined, then search for a file named
* codec_name-preset_name.avpreset in the above-mentioned directories.
*
* @param filename buffer where the name of the found filename is written
* @param filename_size size in bytes of the filename buffer
* @param preset_name name of the preset to search
* @param is_path tell if preset_name is a filename path
* @param codec_name name of the codec for which to look for the
* preset, may be NULL
*/
FILE *get_preset_file(char *filename, size_t filename_size,
const char *preset_name, int is_path, const char *codec_name);
/**
* Realloc array to hold new_size elements of elem_size.
* Calls exit() on failure.
*
* @param array array to reallocate
* @param elem_size size in bytes of each element
* @param size new element count will be written here
* @param new_size number of elements to place in reallocated array
* @return reallocated array
*/
void *grow_array(void *array, int elem_size, int *size, int new_size);
#define media_type_string av_get_media_type_string
#define GROW_ARRAY(array, nb_elems)\
array = grow_array(array, sizeof(*array), &nb_elems, nb_elems + 1)
#define GET_PIX_FMT_NAME(pix_fmt)\
const char *name = av_get_pix_fmt_name(pix_fmt);
#define GET_CODEC_NAME(id)\
const char *name = avcodec_descriptor_get(id)->name;
#define GET_SAMPLE_FMT_NAME(sample_fmt)\
const char *name = av_get_sample_fmt_name(sample_fmt)
#define GET_SAMPLE_RATE_NAME(rate)\
char name[16];\
snprintf(name, sizeof(name), "%d", rate);
#define GET_CH_LAYOUT_NAME(ch_layout)\
char name[16];\
snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
#define GET_CH_LAYOUT_DESC(ch_layout)\
char name[128];\
av_get_channel_layout_string(name, sizeof(name), 0, ch_layout);
double get_rotation(AVStream *st);
#endif /* FFTOOLS_CMDUTILS_H */

File diff suppressed because it is too large Load Diff

@ -0,0 +1,764 @@
/*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* CHANGES 06.2020
* - cancel_operation() method signature updated with id
*
* CHANGES 01.2020
* - ffprobe support changes
*
* CHANGES 12.2019
* - Concurrent execution support
*
* CHANGES 03.2019
* --------------------------------------------------------
* - config.h include removed
*
* CHANGES 08.2018
* --------------------------------------------------------
* - fftools_ prefix added to file name and include guards
* - set_report_callback() method declared
* - cancel_operation() method declared
*
* CHANGES 07.2018
* --------------------------------------------------------
* - Include guards renamed
*/
#ifndef FFTOOLS_FFMPEG_H
#define FFTOOLS_FFMPEG_H
#include <stdint.h>
#include <stdio.h>
#include <signal.h>
#include "fftools_cmdutils.h"
#include "libavformat/avformat.h"
#include "libavformat/avio.h"
#include "libavcodec/avcodec.h"
#include "libavfilter/avfilter.h"
#include "libavutil/avutil.h"
#include "libavutil/dict.h"
#include "libavutil/eval.h"
#include "libavutil/fifo.h"
#include "libavutil/hwcontext.h"
#include "libavutil/pixfmt.h"
#include "libavutil/rational.h"
#include "libavutil/thread.h"
#include "libavutil/threadmessage.h"
#include "libswresample/swresample.h"
#define VSYNC_AUTO -1
#define VSYNC_PASSTHROUGH 0
#define VSYNC_CFR 1
#define VSYNC_VFR 2
#define VSYNC_VSCFR 0xfe
#define VSYNC_DROP 0xff
#define MAX_STREAMS 1024 /* arbitrary sanity check value */
enum HWAccelID {
HWACCEL_NONE = 0,
HWACCEL_AUTO,
HWACCEL_GENERIC,
HWACCEL_VIDEOTOOLBOX,
HWACCEL_QSV,
HWACCEL_CUVID,
};
typedef struct HWAccel {
const char *name;
int (*init)(AVCodecContext *s);
enum HWAccelID id;
enum AVPixelFormat pix_fmt;
} HWAccel;
typedef struct HWDevice {
const char *name;
enum AVHWDeviceType type;
AVBufferRef *device_ref;
} HWDevice;
/* select an input stream for an output stream */
typedef struct StreamMap {
int disabled; /* 1 is this mapping is disabled by a negative map */
int file_index;
int stream_index;
int sync_file_index;
int sync_stream_index;
char *linklabel; /* name of an output link, for mapping lavfi outputs */
} StreamMap;
typedef struct {
int file_idx, stream_idx, channel_idx; // input
int ofile_idx, ostream_idx; // output
} AudioChannelMap;
typedef struct OptionsContext {
OptionGroup *g;
/* input/output options */
int64_t start_time;
int64_t start_time_eof;
int seek_timestamp;
const char *format;
SpecifierOpt *codec_names;
int nb_codec_names;
SpecifierOpt *audio_channels;
int nb_audio_channels;
SpecifierOpt *audio_sample_rate;
int nb_audio_sample_rate;
SpecifierOpt *frame_rates;
int nb_frame_rates;
SpecifierOpt *frame_sizes;
int nb_frame_sizes;
SpecifierOpt *frame_pix_fmts;
int nb_frame_pix_fmts;
/* input options */
int64_t input_ts_offset;
int loop;
int rate_emu;
int accurate_seek;
int thread_queue_size;
SpecifierOpt *ts_scale;
int nb_ts_scale;
SpecifierOpt *dump_attachment;
int nb_dump_attachment;
SpecifierOpt *hwaccels;
int nb_hwaccels;
SpecifierOpt *hwaccel_devices;
int nb_hwaccel_devices;
SpecifierOpt *hwaccel_output_formats;
int nb_hwaccel_output_formats;
SpecifierOpt *autorotate;
int nb_autorotate;
/* output options */
StreamMap *stream_maps;
int nb_stream_maps;
AudioChannelMap *audio_channel_maps; /* one info entry per -map_channel */
int nb_audio_channel_maps; /* number of (valid) -map_channel settings */
int metadata_global_manual;
int metadata_streams_manual;
int metadata_chapters_manual;
const char **attachments;
int nb_attachments;
int chapters_input_file;
int64_t recording_time;
int64_t stop_time;
uint64_t limit_filesize;
float mux_preload;
float mux_max_delay;
int shortest;
int bitexact;
int video_disable;
int audio_disable;
int subtitle_disable;
int data_disable;
/* indexed by output file stream index */
int *streamid_map;
int nb_streamid_map;
SpecifierOpt *metadata;
int nb_metadata;
SpecifierOpt *max_frames;
int nb_max_frames;
SpecifierOpt *bitstream_filters;
int nb_bitstream_filters;
SpecifierOpt *codec_tags;
int nb_codec_tags;
SpecifierOpt *sample_fmts;
int nb_sample_fmts;
SpecifierOpt *qscale;
int nb_qscale;
SpecifierOpt *forced_key_frames;
int nb_forced_key_frames;
SpecifierOpt *force_fps;
int nb_force_fps;
SpecifierOpt *frame_aspect_ratios;
int nb_frame_aspect_ratios;
SpecifierOpt *rc_overrides;
int nb_rc_overrides;
SpecifierOpt *intra_matrices;
int nb_intra_matrices;
SpecifierOpt *inter_matrices;
int nb_inter_matrices;
SpecifierOpt *chroma_intra_matrices;
int nb_chroma_intra_matrices;
SpecifierOpt *top_field_first;
int nb_top_field_first;
SpecifierOpt *metadata_map;
int nb_metadata_map;
SpecifierOpt *presets;
int nb_presets;
SpecifierOpt *copy_initial_nonkeyframes;
int nb_copy_initial_nonkeyframes;
SpecifierOpt *copy_prior_start;
int nb_copy_prior_start;
SpecifierOpt *filters;
int nb_filters;
SpecifierOpt *filter_scripts;
int nb_filter_scripts;
SpecifierOpt *reinit_filters;
int nb_reinit_filters;
SpecifierOpt *fix_sub_duration;
int nb_fix_sub_duration;
SpecifierOpt *canvas_sizes;
int nb_canvas_sizes;
SpecifierOpt *pass;
int nb_pass;
SpecifierOpt *passlogfiles;
int nb_passlogfiles;
SpecifierOpt *max_muxing_queue_size;
int nb_max_muxing_queue_size;
SpecifierOpt *guess_layout_max;
int nb_guess_layout_max;
SpecifierOpt *apad;
int nb_apad;
SpecifierOpt *discard;
int nb_discard;
SpecifierOpt *disposition;
int nb_disposition;
SpecifierOpt *program;
int nb_program;
SpecifierOpt *time_bases;
int nb_time_bases;
SpecifierOpt *enc_time_bases;
int nb_enc_time_bases;
} OptionsContext;
typedef struct InputFilter {
AVFilterContext *filter;
struct InputStream *ist;
struct FilterGraph *graph;
uint8_t *name;
enum AVMediaType type; // AVMEDIA_TYPE_SUBTITLE for sub2video
AVFifoBuffer *frame_queue;
// parameters configured for this input
int format;
int width, height;
AVRational sample_aspect_ratio;
int sample_rate;
int channels;
uint64_t channel_layout;
AVBufferRef *hw_frames_ctx;
int eof;
} InputFilter;
typedef struct OutputFilter {
AVFilterContext *filter;
struct OutputStream *ost;
struct FilterGraph *graph;
uint8_t *name;
/* temporary storage until stream maps are processed */
AVFilterInOut *out_tmp;
enum AVMediaType type;
/* desired output stream properties */
int width, height;
AVRational frame_rate;
int format;
int sample_rate;
uint64_t channel_layout;
// those are only set if no format is specified and the encoder gives us multiple options
int *formats;
uint64_t *channel_layouts;
int *sample_rates;
} OutputFilter;
typedef struct FilterGraph {
int index;
const char *graph_desc;
AVFilterGraph *graph;
int reconfiguration;
InputFilter **inputs;
int nb_inputs;
OutputFilter **outputs;
int nb_outputs;
} FilterGraph;
typedef struct InputStream {
int file_index;
AVStream *st;
int discard; /* true if stream data should be discarded */
int user_set_discard;
int decoding_needed; /* non zero if the packets must be decoded in 'raw_fifo', see DECODING_FOR_* */
#define DECODING_FOR_OST 1
#define DECODING_FOR_FILTER 2
AVCodecContext *dec_ctx;
AVCodec *dec;
AVFrame *decoded_frame;
AVFrame *filter_frame; /* a ref of decoded_frame, to be sent to filters */
int64_t start; /* time when read started */
/* predicted dts of the next packet read for this stream or (when there are
* several frames in a packet) of the next frame in current packet (in AV_TIME_BASE units) */
int64_t next_dts;
int64_t dts; ///< dts of the last packet read for this stream (in AV_TIME_BASE units)
int64_t next_pts; ///< synthetic pts for the next decode frame (in AV_TIME_BASE units)
int64_t pts; ///< current pts of the decoded frame (in AV_TIME_BASE units)
int wrap_correction_done;
int64_t filter_in_rescale_delta_last;
int64_t min_pts; /* pts with the smallest value in a current stream */
int64_t max_pts; /* pts with the higher value in a current stream */
// when forcing constant input framerate through -r,
// this contains the pts that will be given to the next decoded frame
int64_t cfr_next_pts;
int64_t nb_samples; /* number of samples in the last decoded audio frame before looping */
double ts_scale;
int saw_first_ts;
AVDictionary *decoder_opts;
AVRational framerate; /* framerate forced with -r */
int top_field_first;
int guess_layout_max;
int autorotate;
int fix_sub_duration;
struct { /* previous decoded subtitle and related variables */
int got_output;
int ret;
AVSubtitle subtitle;
} prev_sub;
struct sub2video {
int64_t last_pts;
int64_t end_pts;
AVFifoBuffer *sub_queue; ///< queue of AVSubtitle* before filter init
AVFrame *frame;
int w, h;
} sub2video;
int dr1;
/* decoded data from this stream goes into all those filters
* currently video and audio only */
InputFilter **filters;
int nb_filters;
int reinit_filters;
/* hwaccel options */
enum HWAccelID hwaccel_id;
enum AVHWDeviceType hwaccel_device_type;
char *hwaccel_device;
enum AVPixelFormat hwaccel_output_format;
/* hwaccel context */
void *hwaccel_ctx;
void (*hwaccel_uninit)(AVCodecContext *s);
int (*hwaccel_get_buffer)(AVCodecContext *s, AVFrame *frame, int flags);
int (*hwaccel_retrieve_data)(AVCodecContext *s, AVFrame *frame);
enum AVPixelFormat hwaccel_pix_fmt;
enum AVPixelFormat hwaccel_retrieved_pix_fmt;
AVBufferRef *hw_frames_ctx;
/* stats */
// combined size of all the packets read
uint64_t data_size;
/* number of packets successfully read for this stream */
uint64_t nb_packets;
// number of frames/samples retrieved from the decoder
uint64_t frames_decoded;
uint64_t samples_decoded;
int64_t *dts_buffer;
int nb_dts_buffer;
int got_output;
} InputStream;
typedef struct InputFile {
AVFormatContext *ctx;
int eof_reached; /* true if eof reached */
int eagain; /* true if last read attempt returned EAGAIN */
int ist_index; /* index of first stream in input_streams */
int loop; /* set number of times input stream should be looped */
int64_t duration; /* actual duration of the longest stream in a file
at the moment when looping happens */
AVRational time_base; /* time base of the duration */
int64_t input_ts_offset;
int64_t ts_offset;
int64_t last_ts;
int64_t start_time; /* user-specified start time in AV_TIME_BASE or AV_NOPTS_VALUE */
int seek_timestamp;
int64_t recording_time;
int nb_streams; /* number of stream that ffmpeg is aware of; may be different
from ctx.nb_streams if new streams appear during av_read_frame() */
int nb_streams_warn; /* number of streams that the user was warned of */
int rate_emu;
int accurate_seek;
#if HAVE_THREADS
AVThreadMessageQueue *in_thread_queue;
pthread_t thread; /* thread reading from this file */
int non_blocking; /* reading packets from the thread should not block */
int joined; /* the thread has been joined */
int thread_queue_size; /* maximum number of queued packets */
#endif
} InputFile;
enum forced_keyframes_const {
FKF_N,
FKF_N_FORCED,
FKF_PREV_FORCED_N,
FKF_PREV_FORCED_T,
FKF_T,
FKF_NB
};
#define ABORT_ON_FLAG_EMPTY_OUTPUT (1 << 0)
extern const char *const forced_keyframes_const_names[];
typedef enum {
ENCODER_FINISHED = 1,
MUXER_FINISHED = 2,
} OSTFinished ;
typedef struct OutputStream {
int file_index; /* file index */
int index; /* stream index in the output file */
int source_index; /* InputStream index */
AVStream *st; /* stream in the output file */
int encoding_needed; /* true if encoding needed for this stream */
int frame_number;
/* input pts and corresponding output pts
for A/V sync */
struct InputStream *sync_ist; /* input stream to sync against */
int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
/* pts of the first frame encoded for this stream, used for limiting
* recording time */
int64_t first_pts;
/* dts of the last packet sent to the muxer */
int64_t last_mux_dts;
// the timebase of the packets sent to the muxer
AVRational mux_timebase;
AVRational enc_timebase;
int nb_bitstream_filters;
AVBSFContext **bsf_ctx;
AVCodecContext *enc_ctx;
AVCodecParameters *ref_par; /* associated input codec parameters with encoders options applied */
AVCodec *enc;
int64_t max_frames;
AVFrame *filtered_frame;
AVFrame *last_frame;
int last_dropped;
int last_nb0_frames[3];
void *hwaccel_ctx;
/* video only */
AVRational frame_rate;
int is_cfr;
int force_fps;
int top_field_first;
int rotate_overridden;
double rotate_override_value;
AVRational frame_aspect_ratio;
/* forced key frames */
int64_t forced_kf_ref_pts;
int64_t *forced_kf_pts;
int forced_kf_count;
int forced_kf_index;
char *forced_keyframes;
AVExpr *forced_keyframes_pexpr;
double forced_keyframes_expr_const_values[FKF_NB];
/* audio only */
int *audio_channels_map; /* list of the channels id to pick from the source stream */
int audio_channels_mapped; /* number of channels in audio_channels_map */
char *logfile_prefix;
FILE *logfile;
OutputFilter *filter;
char *avfilter;
char *filters; ///< filtergraph associated to the -filter option
char *filters_script; ///< filtergraph script associated to the -filter_script option
AVDictionary *encoder_opts;
AVDictionary *sws_dict;
AVDictionary *swr_opts;
AVDictionary *resample_opts;
char *apad;
OSTFinished finished; /* no more packets should be written for this stream */
int unavailable; /* true if the steram is unavailable (possibly temporarily) */
int stream_copy;
// init_output_stream() has been called for this stream
// The encoder and the bitstream filters have been initialized and the stream
// parameters are set in the AVStream.
int initialized;
int inputs_done;
const char *attachment_filename;
int copy_initial_nonkeyframes;
int copy_prior_start;
char *disposition;
int keep_pix_fmt;
/* stats */
// combined size of all the packets written
uint64_t data_size;
// number of packets send to the muxer
uint64_t packets_written;
// number of frames/samples sent to the encoder
uint64_t frames_encoded;
uint64_t samples_encoded;
/* packet quality factor */
int quality;
int max_muxing_queue_size;
/* the packets are buffered here until the muxer is ready to be initialized */
AVFifoBuffer *muxing_queue;
/* packet picture type */
int pict_type;
/* frame encode sum of squared error values */
int64_t error[4];
} OutputStream;
typedef struct OutputFile {
AVFormatContext *ctx;
AVDictionary *opts;
int ost_index; /* index of the first stream in output_streams */
int64_t recording_time; ///< desired length of the resulting file in microseconds == AV_TIME_BASE units
int64_t start_time; ///< start time in microseconds == AV_TIME_BASE units
uint64_t limit_filesize; /* filesize limit expressed in bytes */
int shortest;
int header_written;
} OutputFile;
extern __thread InputStream **input_streams;
extern __thread int nb_input_streams;
extern __thread InputFile **input_files;
extern __thread int nb_input_files;
extern __thread OutputStream **output_streams;
extern __thread int nb_output_streams;
extern __thread OutputFile **output_files;
extern __thread int nb_output_files;
extern __thread FilterGraph **filtergraphs;
extern __thread int nb_filtergraphs;
extern __thread char *vstats_filename;
extern __thread char *sdp_filename;
extern __thread float audio_drift_threshold;
extern __thread float dts_delta_threshold;
extern __thread float dts_error_threshold;
extern __thread int audio_volume;
extern __thread int audio_sync_method;
extern __thread int video_sync_method;
extern __thread float frame_drop_threshold;
extern __thread int do_benchmark;
extern __thread int do_benchmark_all;
extern __thread int do_deinterlace;
extern __thread int do_hex_dump;
extern __thread int do_pkt_dump;
extern __thread int copy_ts;
extern __thread int start_at_zero;
extern __thread int copy_tb;
extern __thread int debug_ts;
extern __thread int exit_on_error;
extern __thread int abort_on_flags;
extern __thread int print_stats;
extern __thread int qp_hist;
extern __thread int stdin_interaction;
extern __thread int frame_bits_per_raw_sample;
extern __thread AVIOContext *progress_avio;
extern __thread float max_error_rate;
extern __thread char *videotoolbox_pixfmt;
extern __thread int filter_nbthreads;
extern __thread int filter_complex_nbthreads;
extern __thread int vstats_version;
extern __thread const AVIOInterruptCB int_cb;
extern const HWAccel hwaccels[];
extern __thread AVBufferRef *hw_device_ctx;
#if CONFIG_QSV
extern __thread char *qsv_device;
#endif
extern __thread HWDevice *filter_hw_device;
void term_init(void);
void term_exit(void);
void reset_options(OptionsContext *o, int is_input);
void show_usage(void);
void opt_output_file(void *optctx, const char *filename);
void remove_avoptions(AVDictionary **a, AVDictionary *b);
void assert_avoptions(AVDictionary *m);
int guess_input_channel_layout(InputStream *ist);
enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodecContext *avctx, AVCodec *codec, enum AVPixelFormat target);
void choose_sample_fmt(AVStream *st, AVCodec *codec);
int configure_filtergraph(FilterGraph *fg);
int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out);
void check_filter_outputs(void);
int ist_in_filtergraph(FilterGraph *fg, InputStream *ist);
int filtergraph_is_simple(FilterGraph *fg);
int init_simple_filtergraph(InputStream *ist, OutputStream *ost);
int init_complex_filtergraph(FilterGraph *fg);
void sub2video_update(InputStream *ist, AVSubtitle *sub);
int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame);
int ffmpeg_parse_options(int argc, char **argv);
int videotoolbox_init(AVCodecContext *s);
int qsv_init(AVCodecContext *s);
int cuvid_init(AVCodecContext *s);
HWDevice *hw_device_get_by_name(const char *name);
int hw_device_init_from_string(const char *arg, HWDevice **dev);
void hw_device_free_all(void);
int hw_device_setup_for_decode(InputStream *ist);
int hw_device_setup_for_encode(OutputStream *ost);
int hwaccel_decode_init(AVCodecContext *avctx);
void set_report_callback(void (*callback)(int, float, float, int64_t, int, double, double));
void cancel_operation(long id);
int opt_map(void *optctx, const char *opt, const char *arg);
int opt_map_channel(void *optctx, const char *opt, const char *arg);
int opt_recording_timestamp(void *optctx, const char *opt, const char *arg);
int opt_data_frames(void *optctx, const char *opt, const char *arg);
int opt_progress(void *optctx, const char *opt, const char *arg);
int opt_target(void *optctx, const char *opt, const char *arg);
int opt_vsync(void *optctx, const char *opt, const char *arg);
int opt_abort_on(void *optctx, const char *opt, const char *arg);
int opt_qscale(void *optctx, const char *opt, const char *arg);
int opt_profile(void *optctx, const char *opt, const char *arg);
int opt_filter_complex(void *optctx, const char *opt, const char *arg);
int opt_filter_complex_script(void *optctx, const char *opt, const char *arg);
int opt_attach(void *optctx, const char *opt, const char *arg);
int opt_video_frames(void *optctx, const char *opt, const char *arg);
int opt_video_codec(void *optctx, const char *opt, const char *arg);
int opt_sameq(void *optctx, const char *opt, const char *arg);
int opt_timecode(void *optctx, const char *opt, const char *arg);
int opt_vstats_file(void *optctx, const char *opt, const char *arg);
int opt_vstats(void *optctx, const char *opt, const char *arg);
int opt_video_frames(void *optctx, const char *opt, const char *arg);
int opt_old2new(void *optctx, const char *opt, const char *arg);
int opt_streamid(void *optctx, const char *opt, const char *arg);
int opt_bitrate(void *optctx, const char *opt, const char *arg);
int show_hwaccels(void *optctx, const char *opt, const char *arg);
int opt_video_filters(void *optctx, const char *opt, const char *arg);
int opt_audio_frames(void *optctx, const char *opt, const char *arg);
int opt_audio_qscale(void *optctx, const char *opt, const char *arg);
int opt_audio_codec(void *optctx, const char *opt, const char *arg);
int opt_channel_layout(void *optctx, const char *opt, const char *arg);
int opt_preset(void *optctx, const char *opt, const char *arg);
int opt_audio_filters(void *optctx, const char *opt, const char *arg);
int opt_subtitle_codec(void *optctx, const char *opt, const char *arg);
int opt_video_channel(void *optctx, const char *opt, const char *arg);
int opt_video_standard(void *optctx, const char *opt, const char *arg);
int opt_sdp_file(void *optctx, const char *opt, const char *arg);
int opt_data_codec(void *optctx, const char *opt, const char *arg);
int opt_init_hw_device(void *optctx, const char *opt, const char *arg);
int opt_filter_hw_device(void *optctx, const char *opt, const char *arg);
void add_input_streams(OptionsContext *o, AVFormatContext *ic);
void assert_file_overwrite(const char *filename);
void dump_attachment(AVStream *st, const char *filename);
uint8_t *get_line(AVIOContext *s);
void uninit_options(OptionsContext *o);
void init_options(OptionsContext *o);
AVDictionary *strip_specifiers(AVDictionary *dict);
void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec);
int fftools_copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o);
AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder);
AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st);
int open_input_file(OptionsContext *o, const char *filename);
int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s);
int choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost);
OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index);
void parse_matrix_coeffs(uint16_t *dest, const char *str);
uint8_t *fftools_read_file(const char *filename);
char *get_ost_filters(OptionsContext *o, AVFormatContext *oc, OutputStream *ost);
void check_streamcopy_filters(OptionsContext *o, AVFormatContext *oc, const OutputStream *ost, enum AVMediaType type);
OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index);
OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index);
OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index);
OutputStream *new_unknown_stream(OptionsContext *o, AVFormatContext *oc, int source_index);
OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index);
OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index);
int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata);
void init_output_filter(OutputFilter *ofilter, OptionsContext *o, AVFormatContext *oc);
int init_complex_filters(void);
int open_output_file(OptionsContext *o, const char *filename);
int opt_default_new(OptionsContext *o, const char *opt, const char *arg);
int open_files(OptionGroupList *l, const char *inout, int (*open_file)(OptionsContext*, const char*));
#endif /* FFTOOLS_FFMPEG_H */

File diff suppressed because it is too large Load Diff

@ -0,0 +1,491 @@
/*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* CHANGES 12.2019
* - Concurrent execution support
*
* CHANGES 08.2018
* --------------------------------------------------------
* - fftools_ prefix added to file name and parent header
*/
#include <string.h>
#include "libavutil/avstring.h"
#include "fftools_ffmpeg.h"
__thread int nb_hw_devices;
__thread HWDevice **hw_devices;
static HWDevice *hw_device_get_by_type(enum AVHWDeviceType type)
{
HWDevice *found = NULL;
int i;
for (i = 0; i < nb_hw_devices; i++) {
if (hw_devices[i]->type == type) {
if (found)
return NULL;
found = hw_devices[i];
}
}
return found;
}
HWDevice *hw_device_get_by_name(const char *name)
{
int i;
for (i = 0; i < nb_hw_devices; i++) {
if (!strcmp(hw_devices[i]->name, name))
return hw_devices[i];
}
return NULL;
}
static HWDevice *hw_device_add(void)
{
int err;
err = av_reallocp_array(&hw_devices, nb_hw_devices + 1,
sizeof(*hw_devices));
if (err) {
nb_hw_devices = 0;
return NULL;
}
hw_devices[nb_hw_devices] = av_mallocz(sizeof(HWDevice));
if (!hw_devices[nb_hw_devices])
return NULL;
return hw_devices[nb_hw_devices++];
}
static char *hw_device_default_name(enum AVHWDeviceType type)
{
// Make an automatic name of the form "type%d". We arbitrarily
// limit at 1000 anonymous devices of the same type - there is
// probably something else very wrong if you get to this limit.
const char *type_name = av_hwdevice_get_type_name(type);
char *name;
size_t index_pos;
int index, index_limit = 1000;
index_pos = strlen(type_name);
name = av_malloc(index_pos + 4);
if (!name)
return NULL;
for (index = 0; index < index_limit; index++) {
snprintf(name, index_pos + 4, "%s%d", type_name, index);
if (!hw_device_get_by_name(name))
break;
}
if (index >= index_limit) {
av_freep(&name);
return NULL;
}
return name;
}
int hw_device_init_from_string(const char *arg, HWDevice **dev_out)
{
// "type=name:device,key=value,key2=value2"
// "type:device,key=value,key2=value2"
// -> av_hwdevice_ctx_create()
// "type=name@name"
// "type@name"
// -> av_hwdevice_ctx_create_derived()
AVDictionary *options = NULL;
const char *type_name = NULL, *name = NULL, *device = NULL;
enum AVHWDeviceType type;
HWDevice *dev, *src;
AVBufferRef *device_ref = NULL;
int err;
const char *errmsg, *p, *q;
size_t k;
k = strcspn(arg, ":=@");
p = arg + k;
type_name = av_strndup(arg, k);
if (!type_name) {
err = AVERROR(ENOMEM);
goto fail;
}
type = av_hwdevice_find_type_by_name(type_name);
if (type == AV_HWDEVICE_TYPE_NONE) {
errmsg = "unknown device type";
goto invalid;
}
if (*p == '=') {
k = strcspn(p + 1, ":@");
name = av_strndup(p + 1, k);
if (!name) {
err = AVERROR(ENOMEM);
goto fail;
}
if (hw_device_get_by_name(name)) {
errmsg = "named device already exists";
goto invalid;
}
p += 1 + k;
} else {
name = hw_device_default_name(type);
if (!name) {
err = AVERROR(ENOMEM);
goto fail;
}
}
if (!*p) {
// New device with no parameters.
err = av_hwdevice_ctx_create(&device_ref, type,
NULL, NULL, 0);
if (err < 0)
goto fail;
} else if (*p == ':') {
// New device with some parameters.
++p;
q = strchr(p, ',');
if (q) {
if (q - p > 0) {
device = av_strndup(p, q - p);
if (!device) {
err = AVERROR(ENOMEM);
goto fail;
}
}
err = av_dict_parse_string(&options, q + 1, "=", ",", 0);
if (err < 0) {
errmsg = "failed to parse options";
goto invalid;
}
}
err = av_hwdevice_ctx_create(&device_ref, type,
q ? device : p[0] ? p : NULL,
options, 0);
if (err < 0)
goto fail;
} else if (*p == '@') {
// Derive from existing device.
src = hw_device_get_by_name(p + 1);
if (!src) {
errmsg = "invalid source device name";
goto invalid;
}
err = av_hwdevice_ctx_create_derived(&device_ref, type,
src->device_ref, 0);
if (err < 0)
goto fail;
} else {
errmsg = "parse error";
goto invalid;
}
dev = hw_device_add();
if (!dev) {
err = AVERROR(ENOMEM);
goto fail;
}
dev->name = name;
dev->type = type;
dev->device_ref = device_ref;
if (dev_out)
*dev_out = dev;
name = NULL;
err = 0;
done:
av_freep(&type_name);
av_freep(&name);
av_freep(&device);
av_dict_free(&options);
return err;
invalid:
av_log(NULL, AV_LOG_ERROR,
"Invalid device specification \"%s\": %s\n", arg, errmsg);
err = AVERROR(EINVAL);
goto done;
fail:
av_log(NULL, AV_LOG_ERROR,
"Device creation failed: %d.\n", err);
av_buffer_unref(&device_ref);
goto done;
}
static int hw_device_init_from_type(enum AVHWDeviceType type,
const char *device,
HWDevice **dev_out)
{
AVBufferRef *device_ref = NULL;
HWDevice *dev;
char *name;
int err;
name = hw_device_default_name(type);
if (!name) {
err = AVERROR(ENOMEM);
goto fail;
}
err = av_hwdevice_ctx_create(&device_ref, type, device, NULL, 0);
if (err < 0) {
av_log(NULL, AV_LOG_ERROR,
"Device creation failed: %d.\n", err);
goto fail;
}
dev = hw_device_add();
if (!dev) {
err = AVERROR(ENOMEM);
goto fail;
}
dev->name = name;
dev->type = type;
dev->device_ref = device_ref;
if (dev_out)
*dev_out = dev;
return 0;
fail:
av_freep(&name);
av_buffer_unref(&device_ref);
return err;
}
void hw_device_free_all(void)
{
int i;
for (i = 0; i < nb_hw_devices; i++) {
av_freep(&hw_devices[i]->name);
av_buffer_unref(&hw_devices[i]->device_ref);
av_freep(&hw_devices[i]);
}
av_freep(&hw_devices);
nb_hw_devices = 0;
}
static HWDevice *hw_device_match_by_codec(const AVCodec *codec)
{
const AVCodecHWConfig *config;
HWDevice *dev;
int i;
for (i = 0;; i++) {
config = avcodec_get_hw_config(codec, i);
if (!config)
return NULL;
if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
continue;
dev = hw_device_get_by_type(config->device_type);
if (dev)
return dev;
}
}
int hw_device_setup_for_decode(InputStream *ist)
{
const AVCodecHWConfig *config;
enum AVHWDeviceType type;
HWDevice *dev = NULL;
int err, auto_device = 0;
if (ist->hwaccel_device) {
dev = hw_device_get_by_name(ist->hwaccel_device);
if (!dev) {
if (ist->hwaccel_id == HWACCEL_AUTO) {
auto_device = 1;
} else if (ist->hwaccel_id == HWACCEL_GENERIC) {
type = ist->hwaccel_device_type;
err = hw_device_init_from_type(type, ist->hwaccel_device,
&dev);
} else {
// This will be dealt with by API-specific initialisation
// (using hwaccel_device), so nothing further needed here.
return 0;
}
} else {
if (ist->hwaccel_id == HWACCEL_AUTO) {
ist->hwaccel_device_type = dev->type;
} else if (ist->hwaccel_device_type != dev->type) {
av_log(ist->dec_ctx, AV_LOG_ERROR, "Invalid hwaccel device "
"specified for decoder: device %s of type %s is not "
"usable with hwaccel %s.\n", dev->name,
av_hwdevice_get_type_name(dev->type),
av_hwdevice_get_type_name(ist->hwaccel_device_type));
return AVERROR(EINVAL);
}
}
} else {
if (ist->hwaccel_id == HWACCEL_AUTO) {
auto_device = 1;
} else if (ist->hwaccel_id == HWACCEL_GENERIC) {
type = ist->hwaccel_device_type;
dev = hw_device_get_by_type(type);
if (!dev)
err = hw_device_init_from_type(type, NULL, &dev);
} else {
dev = hw_device_match_by_codec(ist->dec);
if (!dev) {
// No device for this codec, but not using generic hwaccel
// and therefore may well not need one - ignore.
return 0;
}
}
}
if (auto_device) {
int i;
if (!avcodec_get_hw_config(ist->dec, 0)) {
// Decoder does not support any hardware devices.
return 0;
}
for (i = 0; !dev; i++) {
config = avcodec_get_hw_config(ist->dec, i);
if (!config)
break;
type = config->device_type;
dev = hw_device_get_by_type(type);
if (dev) {
av_log(ist->dec_ctx, AV_LOG_INFO, "Using auto "
"hwaccel type %s with existing device %s.\n",
av_hwdevice_get_type_name(type), dev->name);
}
}
for (i = 0; !dev; i++) {
config = avcodec_get_hw_config(ist->dec, i);
if (!config)
break;
type = config->device_type;
// Try to make a new device of this type.
err = hw_device_init_from_type(type, ist->hwaccel_device,
&dev);
if (err < 0) {
// Can't make a device of this type.
continue;
}
if (ist->hwaccel_device) {
av_log(ist->dec_ctx, AV_LOG_INFO, "Using auto "
"hwaccel type %s with new device created "
"from %s.\n", av_hwdevice_get_type_name(type),
ist->hwaccel_device);
} else {
av_log(ist->dec_ctx, AV_LOG_INFO, "Using auto "
"hwaccel type %s with new default device.\n",
av_hwdevice_get_type_name(type));
}
}
if (dev) {
ist->hwaccel_device_type = type;
} else {
av_log(ist->dec_ctx, AV_LOG_INFO, "Auto hwaccel "
"disabled: no device found.\n");
ist->hwaccel_id = HWACCEL_NONE;
return 0;
}
}
if (!dev) {
av_log(ist->dec_ctx, AV_LOG_ERROR, "No device available "
"for decoder: device type %s needed for codec %s.\n",
av_hwdevice_get_type_name(type), ist->dec->name);
return err;
}
ist->dec_ctx->hw_device_ctx = av_buffer_ref(dev->device_ref);
if (!ist->dec_ctx->hw_device_ctx)
return AVERROR(ENOMEM);
return 0;
}
int hw_device_setup_for_encode(OutputStream *ost)
{
HWDevice *dev;
dev = hw_device_match_by_codec(ost->enc);
if (dev) {
ost->enc_ctx->hw_device_ctx = av_buffer_ref(dev->device_ref);
if (!ost->enc_ctx->hw_device_ctx)
return AVERROR(ENOMEM);
return 0;
} else {
// No device required, or no device available.
return 0;
}
}
static int hwaccel_retrieve_data(AVCodecContext *avctx, AVFrame *input)
{
InputStream *ist = avctx->opaque;
AVFrame *output = NULL;
enum AVPixelFormat output_format = ist->hwaccel_output_format;
int err;
if (input->format == output_format) {
// Nothing to do.
return 0;
}
output = av_frame_alloc();
if (!output)
return AVERROR(ENOMEM);
output->format = output_format;
err = av_hwframe_transfer_data(output, input, 0);
if (err < 0) {
av_log(avctx, AV_LOG_ERROR, "Failed to transfer data to "
"output frame: %d.\n", err);
goto fail;
}
err = av_frame_copy_props(output, input);
if (err < 0) {
av_frame_unref(output);
goto fail;
}
av_frame_unref(input);
av_frame_move_ref(input, output);
av_frame_free(&output);
return 0;
fail:
av_frame_free(&output);
return err;
}
int hwaccel_decode_init(AVCodecContext *avctx)
{
InputStream *ist = avctx->opaque;
ist->hwaccel_retrieve_data = &hwaccel_retrieve_data;
return 0;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,108 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Helper enumeration type for Android ABIs; includes only supported ABIs.
*/
public enum Abi {
/**
* Represents armeabi-v7a ABI with NEON support
*/
ABI_ARMV7A_NEON("armeabi-v7a-neon"),
/**
* Represents armeabi-v7a ABI
*/
ABI_ARMV7A("armeabi-v7a"),
/**
* Represents armeabi ABI
*/
ABI_ARM("armeabi"),
/**
* Represents x86 ABI
*/
ABI_X86("x86"),
/**
* Represents x86_64 ABI
*/
ABI_X86_64("x86_64"),
/**
* Represents arm64-v8a ABI
*/
ABI_ARM64_V8A("arm64-v8a"),
/**
* Represents not supported ABIs
*/
ABI_UNKNOWN("unknown");
private String name;
/**
* <p>Returns enumeration defined by ABI name.
*
* @param abiName ABI name
* @return enumeration defined by ABI name
*/
public static Abi from(final String abiName) {
if (abiName == null) {
return ABI_UNKNOWN;
} else if (abiName.equals(ABI_ARM.getName())) {
return ABI_ARM;
} else if (abiName.equals(ABI_ARMV7A.getName())) {
return ABI_ARMV7A;
} else if (abiName.equals(ABI_ARMV7A_NEON.getName())) {
return ABI_ARMV7A_NEON;
} else if (abiName.equals(ABI_ARM64_V8A.getName())) {
return ABI_ARM64_V8A;
} else if (abiName.equals(ABI_X86.getName())) {
return ABI_X86;
} else if (abiName.equals(ABI_X86_64.getName())) {
return ABI_X86_64;
} else {
return ABI_UNKNOWN;
}
}
/**
* Returns ABI name as defined in Android NDK documentation.
*
* @return ABI name
*/
public String getName() {
return name;
}
/**
* Creates new enum.
*
* @param abiName ABI name
*/
Abi(final String abiName) {
this.name = abiName;
}
}

@ -0,0 +1,94 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>This class is used to detect running ABI name using Google <code>cpu-features</code> library.
*/
public class AbiDetect {
static {
armV7aNeonLoaded = false;
System.loadLibrary("ffmpegkit_abidetect");
/* ALL LIBRARIES LOADED AT STARTUP */
FFmpegKitConfig.class.getName();
FFmpegKit.class.getName();
}
static final String ARM_V7A = "arm-v7a";
static final String ARM_V7A_NEON = "arm-v7a-neon";
private static boolean armV7aNeonLoaded;
/**
* Default constructor hidden.
*/
private AbiDetect() {
}
static void setArmV7aNeonLoaded(final boolean armV7aNeonLoaded) {
AbiDetect.armV7aNeonLoaded = armV7aNeonLoaded;
}
/**
* <p>Returns loaded ABI name.
*
* @return loaded ABI name
*/
public static String getAbi() {
if (armV7aNeonLoaded) {
return ARM_V7A_NEON;
} else {
return getNativeAbi();
}
}
/**
* <p>Returns loaded ABI name.
*
* @return loaded ABI name
*/
public native static String getNativeAbi();
/**
* <p>Returns ABI name of the running cpu.
*
* @return ABI name of the running cpu
*/
public native static String getNativeCpuAbi();
/**
* <p>Returns whether FFmpegKit release is a long term release or not.
*
* @return yes or no
*/
native static boolean isNativeLTSBuild();
/**
* <p>Returns build configuration for <code>FFmpeg</code>.
*
* @return build configuration string
*/
native static String getNativeBuildConf();
}

@ -0,0 +1,62 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.os.AsyncTask;
/**
* <p>Utility class to execute an FFmpeg command asynchronously.
*/
public class AsyncFFmpegExecuteTask extends AsyncTask<Void, Integer, Integer> {
private final String[] arguments;
private final ExecuteCallback executeCallback;
private final Long executionId;
public AsyncFFmpegExecuteTask(final String command, final ExecuteCallback executeCallback) {
this(FFmpegKit.parseArguments(command), executeCallback);
}
public AsyncFFmpegExecuteTask(final String[] arguments, final ExecuteCallback executeCallback) {
this(FFmpegKit.DEFAULT_EXECUTION_ID, arguments, executeCallback);
}
public AsyncFFmpegExecuteTask(final long executionId, final String command, final ExecuteCallback executeCallback) {
this(executionId, FFmpegKit.parseArguments(command), executeCallback);
}
public AsyncFFmpegExecuteTask(final long executionId, final String[] arguments, final ExecuteCallback executeCallback) {
this.executionId = executionId;
this.arguments = arguments;
this.executeCallback = executeCallback;
}
@Override
protected Integer doInBackground(final Void... unused) {
return FFmpegKitConfig.ffmpegExecute(executionId, this.arguments);
}
@Override
protected void onPostExecute(final Integer rc) {
if (executeCallback != null) {
executeCallback.apply(executionId, rc);
}
}
}

@ -0,0 +1,53 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.os.AsyncTask;
/**
* <p>Utility class to execute an FFprobe command asynchronously.
*/
public class AsyncFFprobeExecuteTask extends AsyncTask<Void, Integer, Integer> {
private final String[] arguments;
private final ExecuteCallback ExecuteCallback;
public AsyncFFprobeExecuteTask(final String command, final ExecuteCallback executeCallback) {
this.arguments = FFmpegKit.parseArguments(command);
this.ExecuteCallback = executeCallback;
}
public AsyncFFprobeExecuteTask(final String[] arguments, final ExecuteCallback executeCallback) {
this.arguments = arguments;
ExecuteCallback = executeCallback;
}
@Override
protected Integer doInBackground(final Void... unused) {
return FFprobeKit.execute(this.arguments);
}
@Override
protected void onPostExecute(final Integer rc) {
if (ExecuteCallback != null) {
ExecuteCallback.apply(FFmpegKit.DEFAULT_EXECUTION_ID, rc);
}
}
}

@ -0,0 +1,48 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.os.AsyncTask;
/**
* <p>Utility class to get media information asynchronously.
*/
public class AsyncGetMediaInformationTask extends AsyncTask<String, MediaInformation, MediaInformation> {
private final String path;
private final GetMediaInformationCallback getMediaInformationCallback;
public AsyncGetMediaInformationTask(final String path, final GetMediaInformationCallback getMediaInformationCallback) {
this.path = path;
this.getMediaInformationCallback = getMediaInformationCallback;
}
@Override
protected MediaInformation doInBackground(final String... arguments) {
return FFprobeKit.getMediaInformation(path);
}
@Override
protected void onPostExecute(final MediaInformation mediaInformation) {
if (getMediaInformationCallback != null) {
getMediaInformationCallback.apply(mediaInformation);
}
}
}

@ -0,0 +1,75 @@
/*
* Copyright (c) 2019-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.os.Build;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.CAMERA_SERVICE;
import static com.arthenica.ffmpegkit.FFmpegKitConfig.TAG;
/**
* Utility class for camera devices.
*/
class CameraSupport {
/**
* <p>Compatibility method for extracting supported camera ids.
*
* @param context application context
* @return returns the list of supported camera ids
*/
static List<String> extractSupportedCameraIds(final Context context) {
final List<String> detectedCameraIdList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
final CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
if (manager != null) {
final String[] cameraIdList = manager.getCameraIdList();
for (String cameraId : cameraIdList) {
final CameraCharacteristics chars = manager.getCameraCharacteristics(cameraId);
final Integer cameraSupport = chars.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (cameraSupport != null && cameraSupport == CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
Log.d(TAG, "Detected camera with id " + cameraId + " has LEGACY hardware level which is not supported by Android Camera2 NDK API.");
} else if (cameraSupport != null) {
detectedCameraIdList.add(cameraId);
}
}
}
} catch (final CameraAccessException e) {
Log.w(TAG, "Detecting camera ids failed.", e);
}
}
return detectedCameraIdList;
}
}

@ -0,0 +1,37 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Represents a callback function to receive an asynchronous execution result.
*/
@FunctionalInterface
public interface ExecuteCallback {
/**
* <p>Called when an asynchronous FFmpeg execution is completed.
*
* @param executionId id of the execution that completed
* @param returnCode return code of the execution completed, 0 on successful completion, 255
* on user cancel, other non-zero codes on error
*/
void apply(long executionId, int returnCode);
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import java.util.Date;
/**
* <p>Represents an ongoing FFmpeg execution.
*/
public class FFmpegExecution {
private final Date startTime;
private final long executionId;
private final String command;
public FFmpegExecution(final long executionId, final String[] arguments) {
this.startTime = new Date();
this.executionId = executionId;
this.command = FFmpegKit.argumentsToString(arguments);
}
public Date getStartTime() {
return startTime;
}
public long getExecutionId() {
return executionId;
}
public String getCommand() {
return command;
}
}

@ -0,0 +1,274 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
/**
* <p>Main class for FFmpeg operations. Supports synchronous {@link #execute(String...)} and
* asynchronous {@link #executeAsync(String, ExecuteCallback)} methods to execute FFmpeg commands.
* <pre>
* int rc = FFmpeg.execute("-i file1.mp4 -c:v libxvid file1.avi");
* Log.i(Config.TAG, String.format("Command execution %s.", (rc == 0?"completed successfully":"failed with rc=" + rc));
* </pre>
* <pre>
* long executionId = FFmpeg.executeAsync("-i file1.mp4 -c:v libxvid file1.avi", executeCallback);
* Log.i(Config.TAG, String.format("Asynchronous execution %d started.", executionId));
* </pre>
*/
public class FFmpegKit {
static final long DEFAULT_EXECUTION_ID = 0;
private static final AtomicLong executionIdCounter = new AtomicLong(3000);
static {
AbiDetect.class.getName();
FFmpegKitConfig.class.getName();
}
/**
* Default constructor hidden.
*/
private FFmpegKit() {
}
/**
* <p>Synchronously executes FFmpeg with arguments provided.
*
* @param arguments FFmpeg command options/arguments as string array
* @return 0 on successful execution, 255 on user cancel, other non-zero codes on error
*/
public static int execute(final String[] arguments) {
return FFmpegKitConfig.ffmpegExecute(DEFAULT_EXECUTION_ID, arguments);
}
/**
* <p>Asynchronously executes FFmpeg with arguments provided.
*
* @param arguments FFmpeg command options/arguments as string array
* @param executeCallback callback that will be notified when execution is completed
* @return returns a unique id that represents this execution
*/
public static long executeAsync(final String[] arguments, final ExecuteCallback executeCallback) {
final long newExecutionId = executionIdCounter.incrementAndGet();
AsyncFFmpegExecuteTask asyncFFmpegExecuteTask = new AsyncFFmpegExecuteTask(newExecutionId, arguments, executeCallback);
asyncFFmpegExecuteTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return newExecutionId;
}
/**
* <p>Asynchronously executes FFmpeg with arguments provided.
*
* @param arguments FFmpeg command options/arguments as string array
* @param executeCallback callback that will be notified when execution is completed
* @param executor executor that will be used to run this asynchronous operation
* @return returns a unique id that represents this execution
*/
public static long executeAsync(final String[] arguments, final ExecuteCallback executeCallback, final Executor executor) {
final long newExecutionId = executionIdCounter.incrementAndGet();
AsyncFFmpegExecuteTask asyncFFmpegExecuteTask = new AsyncFFmpegExecuteTask(newExecutionId, arguments, executeCallback);
asyncFFmpegExecuteTask.executeOnExecutor(executor);
return newExecutionId;
}
/**
* <p>Synchronously executes FFmpeg command provided. Command is split into arguments using
* provided delimiter character.
*
* @param command FFmpeg command
* @param delimiter delimiter used to split arguments
* @return 0 on successful execution, 255 on user cancel, other non-zero codes on error
* @since 3.0
* @deprecated argument splitting mechanism used in this method is pretty simple and prone to
* errors. Consider using a more advanced method like {@link #execute(String)} or
* {@link #execute(String[])}
*/
public static int execute(final String command, final String delimiter) {
return execute((command == null) ? new String[]{""} : command.split((delimiter == null) ? " " : delimiter));
}
/**
* <p>Synchronously executes FFmpeg command provided. Space character is used to split command
* into arguments. You can use single and double quote characters to specify arguments inside
* your command.
*
* @param command FFmpeg command
* @return 0 on successful execution, 255 on user cancel, other non-zero codes on error
*/
public static int execute(final String command) {
return execute(parseArguments(command));
}
/**
* <p>Asynchronously executes FFmpeg command provided. Space character is used to split command
* into arguments. You can use single and double quote characters to specify arguments inside
* your command.
*
* @param command FFmpeg command
* @param executeCallback callback that will be notified when execution is completed
* @return returns a unique id that represents this execution
*/
public static long executeAsync(final String command, final ExecuteCallback executeCallback) {
final long newExecutionId = executionIdCounter.incrementAndGet();
AsyncFFmpegExecuteTask asyncFFmpegExecuteTask = new AsyncFFmpegExecuteTask(newExecutionId, command, executeCallback);
asyncFFmpegExecuteTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return newExecutionId;
}
/**
* <p>Asynchronously executes FFmpeg command provided. Space character is used to split command
* into arguments. You can use single and double quote characters to specify arguments inside
* your command.
*
* @param command FFmpeg command
* @param executeCallback callback that will be notified when execution is completed
* @param executor executor that will be used to run this asynchronous operation
* @return returns a unique id that represents this execution
*/
public static long executeAsync(final String command, final ExecuteCallback executeCallback, final Executor executor) {
final long newExecutionId = executionIdCounter.incrementAndGet();
AsyncFFmpegExecuteTask asyncFFmpegExecuteTask = new AsyncFFmpegExecuteTask(newExecutionId, command, executeCallback);
asyncFFmpegExecuteTask.executeOnExecutor(executor);
return newExecutionId;
}
/**
* <p>Cancels an ongoing operation.
*
* <p>This function does not wait for termination to complete and returns immediately.
*/
public static void cancel() {
FFmpegKitConfig.nativeFFmpegCancel(DEFAULT_EXECUTION_ID);
}
/**
* <p>Cancels an ongoing operation.
*
* <p>This function does not wait for termination to complete and returns immediately.
*
* @param executionId id of the execution
*/
public static void cancel(final long executionId) {
FFmpegKitConfig.nativeFFmpegCancel(executionId);
}
/**
* <p>Lists ongoing executions.
*
* @return list of ongoing executions
*/
public static List<FFmpegExecution> listExecutions() {
return FFmpegKitConfig.listFFmpegExecutions();
}
/**
* <p>Parses the given command into arguments.
*
* @param command string command
* @return array of arguments
*/
static String[] parseArguments(final String command) {
final List<String> argumentList = new ArrayList<>();
StringBuilder currentArgument = new StringBuilder();
boolean singleQuoteStarted = false;
boolean doubleQuoteStarted = false;
for (int i = 0; i < command.length(); i++) {
final Character previousChar;
if (i > 0) {
previousChar = command.charAt(i - 1);
} else {
previousChar = null;
}
final char currentChar = command.charAt(i);
if (currentChar == ' ') {
if (singleQuoteStarted || doubleQuoteStarted) {
currentArgument.append(currentChar);
} else if (currentArgument.length() > 0) {
argumentList.add(currentArgument.toString());
currentArgument = new StringBuilder();
}
} else if (currentChar == '\'' && (previousChar == null || previousChar != '\\')) {
if (singleQuoteStarted) {
singleQuoteStarted = false;
} else if (doubleQuoteStarted) {
currentArgument.append(currentChar);
} else {
singleQuoteStarted = true;
}
} else if (currentChar == '\"' && (previousChar == null || previousChar != '\\')) {
if (doubleQuoteStarted) {
doubleQuoteStarted = false;
} else if (singleQuoteStarted) {
currentArgument.append(currentChar);
} else {
doubleQuoteStarted = true;
}
} else {
currentArgument.append(currentChar);
}
}
if (currentArgument.length() > 0) {
argumentList.add(currentArgument.toString());
}
return argumentList.toArray(new String[0]);
}
/**
* <p>Combines arguments into a string.
*
* @param arguments arguments
* @return string containing all arguments
*/
static String argumentsToString(final String[] arguments) {
if (arguments == null) {
return "null";
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arguments.length; i++) {
if (i > 0) {
stringBuilder.append(" ");
}
stringBuilder.append(arguments[i]);
}
return stringBuilder.toString();
}
}

@ -0,0 +1,769 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/**
* <p>This class is used to configure FFmpegKit library utilities/tools.
*
* <p>1. {@link LogCallback}: This class redirects FFmpeg/FFprobe output to Logcat by default. As
* an alternative, it is possible not to print messages to Logcat and pass them to a
* {@link LogCallback} function. This function can decide whether to print these logs, show them
* inside another container or ignore them.
*
* <p>2. {@link #setLogLevel(Level)}/{@link #getLogLevel()}: Use this methods to set/get
* FFmpeg/FFprobe log severity.
*
* <p>3. {@link StatisticsCallback}: It is possible to receive statistics about an ongoing
* operation by defining a {@link StatisticsCallback} function or by calling
* {@link #getLastReceivedStatistics()} method.
*
* <p>4. Font configuration: It is possible to register custom fonts with
* {@link #setFontconfigConfigurationPath(String)} and
* {@link #setFontDirectory(Context, String, Map)} methods.
*/
public class FFmpegKitConfig {
public static final int RETURN_CODE_SUCCESS = 0;
public static final int RETURN_CODE_CANCEL = 255;
private static int lastReturnCode = 0;
/**
* Defines tag used for logging.
*/
public static final String TAG = "ffmpeg-kit";
public static final String FFMPEG_KIT_PIPE_PREFIX = "mf_pipe_";
private static LogCallback logCallbackFunction;
private static Level activeLogLevel;
private static StatisticsCallback statisticsCallbackFunction;
private static Statistics lastReceivedStatistics;
private static int lastCreatedPipeIndex;
private static final List<FFmpegExecution> executions;
static {
Log.i(FFmpegKitConfig.TAG, "Loading ffmpeg-kit.");
boolean nativeFFmpegLoaded = false;
boolean nativeFFmpegTriedAndFailed = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
/* LOADING LIBRARIES MANUALLY ON API < 21 */
final List<String> externalLibrariesEnabled = getExternalLibraries();
if (externalLibrariesEnabled.contains("tesseract") || externalLibrariesEnabled.contains("x265") || externalLibrariesEnabled.contains("snappy") || externalLibrariesEnabled.contains("openh264") || externalLibrariesEnabled.contains("rubberband")) {
System.loadLibrary("c++_shared");
}
if (AbiDetect.ARM_V7A.equals(AbiDetect.getNativeAbi())) {
try {
System.loadLibrary("avutil_neon");
System.loadLibrary("swscale_neon");
System.loadLibrary("swresample_neon");
System.loadLibrary("avcodec_neon");
System.loadLibrary("avformat_neon");
System.loadLibrary("avfilter_neon");
System.loadLibrary("avdevice_neon");
nativeFFmpegLoaded = true;
} catch (final UnsatisfiedLinkError e) {
Log.i(FFmpegKitConfig.TAG, "NEON supported armeabi-v7a ffmpeg library not found. Loading default armeabi-v7a library.", e);
nativeFFmpegTriedAndFailed = true;
}
}
if (!nativeFFmpegLoaded) {
System.loadLibrary("avutil");
System.loadLibrary("swscale");
System.loadLibrary("swresample");
System.loadLibrary("avcodec");
System.loadLibrary("avformat");
System.loadLibrary("avfilter");
System.loadLibrary("avdevice");
}
}
/* ALL FFMPEG-KIT LIBRARIES LOADED AT STARTUP */
Abi.class.getName();
FFmpegKit.class.getName();
FFprobeKit.class.getName();
boolean nativeFFmpegKitLoaded = false;
if (!nativeFFmpegTriedAndFailed && AbiDetect.ARM_V7A.equals(AbiDetect.getNativeAbi())) {
try {
/*
* THE TRY TO LOAD ARM-V7A-NEON FIRST. IF NOT LOAD DEFAULT ARM-V7A
*/
System.loadLibrary("ffmpegkit_armv7a_neon");
nativeFFmpegKitLoaded = true;
AbiDetect.setArmV7aNeonLoaded(true);
} catch (final UnsatisfiedLinkError e) {
Log.i(FFmpegKitConfig.TAG, "NEON supported armeabi-v7a ffmpegkit library not found. Loading default armeabi-v7a library.", e);
}
}
if (!nativeFFmpegKitLoaded) {
System.loadLibrary("ffmpegkit");
}
Log.i(FFmpegKitConfig.TAG, String.format("Loaded ffmpeg-kit-%s-%s-%s-%s.", getPackageName(), AbiDetect.getAbi(), getVersion(), getBuildDate()));
/* NATIVE LOG LEVEL IS RECEIVED ONLY ON STARTUP */
activeLogLevel = Level.from(getNativeLogLevel());
lastReceivedStatistics = new Statistics();
enableRedirection();
lastCreatedPipeIndex = 0;
executions = Collections.synchronizedList(new ArrayList<FFmpegExecution>());
}
/**
* Default constructor hidden.
*/
private FFmpegKitConfig() {
}
/**
* <p>Enables log and statistics redirection.
* <p>When redirection is not enabled FFmpeg/FFprobe logs are printed to stderr. By enabling
* redirection, they are routed to Logcat and can be routed further to a callback function.
* <p>Statistics redirection behaviour is similar. Statistics are not printed at all if
* redirection is not enabled. If it is enabled then it is possible to define a statistics
* callback function but if you don't, they are not printed anywhere and only saved as
* <code>lastReceivedStatistics</code> data which can be polled with
* {@link #getLastReceivedStatistics()}.
* <p>Note that redirection is enabled by default. If you do not want to use its functionality
* please use {@link #disableRedirection()} to disable it.
*/
public static void enableRedirection() {
enableNativeRedirection();
}
/**
* <p>Disables log and statistics redirection.
*/
public static void disableRedirection() {
disableNativeRedirection();
}
/**
* Returns log level.
*
* @return log level
*/
public static Level getLogLevel() {
return activeLogLevel;
}
/**
* Sets log level.
*
* @param level log level
*/
public static void setLogLevel(final Level level) {
if (level != null) {
activeLogLevel = level;
setNativeLogLevel(level.getValue());
}
}
/**
* <p>Sets a callback function to redirect FFmpeg/FFprobe logs.
*
* @param newLogCallback new log callback function or NULL to disable a previously defined callback
*/
public static void enableLogCallback(final LogCallback newLogCallback) {
logCallbackFunction = newLogCallback;
}
/**
* <p>Sets a callback function to redirect FFmpeg statistics.
*
* @param statisticsCallback new statistics callback function or NULL to disable a previously defined callback
*/
public static void enableStatisticsCallback(final StatisticsCallback statisticsCallback) {
statisticsCallbackFunction = statisticsCallback;
}
/**
* <p>Log redirection method called by JNI/native part.
*
* @param executionId id of the execution that generated this log, 0 by default
* @param levelValue log level as defined in {@link Level}
* @param logMessage redirected log message
*/
private static void log(final long executionId, final int levelValue, final byte[] logMessage) {
final Level level = Level.from(levelValue);
final String text = new String(logMessage);
// AV_LOG_STDERR logs are always redirected
if ((activeLogLevel == Level.AV_LOG_QUIET && levelValue != Level.AV_LOG_STDERR.getValue()) || levelValue > activeLogLevel.getValue()) {
// LOG NEITHER PRINTED NOR FORWARDED
return;
}
if (logCallbackFunction != null) {
try {
logCallbackFunction.apply(new LogMessage(executionId, level, text));
} catch (final Exception e) {
Log.e(FFmpegKitConfig.TAG, "Exception thrown inside LogCallback block", e);
}
} else {
switch (level) {
case AV_LOG_QUIET: {
// PRINT NO OUTPUT
}
break;
case AV_LOG_TRACE:
case AV_LOG_DEBUG: {
android.util.Log.d(TAG, text);
}
break;
case AV_LOG_STDERR:
case AV_LOG_VERBOSE: {
android.util.Log.v(TAG, text);
}
break;
case AV_LOG_INFO: {
android.util.Log.i(TAG, text);
}
break;
case AV_LOG_WARNING: {
android.util.Log.w(TAG, text);
}
break;
case AV_LOG_ERROR:
case AV_LOG_FATAL:
case AV_LOG_PANIC: {
android.util.Log.e(TAG, text);
}
break;
default: {
android.util.Log.v(TAG, text);
}
break;
}
}
}
/**
* <p>Statistics redirection method called by JNI/native part.
*
* @param executionId id of the execution that generated this statistics, 0 by default
* @param videoFrameNumber last processed frame number for videos
* @param videoFps frames processed per second for videos
* @param videoQuality quality of the video stream
* @param size size in bytes
* @param time processed duration in milliseconds
* @param bitrate output bit rate in kbits/s
* @param speed processing speed = processed duration / operation duration
*/
private static void statistics(final long executionId, final int videoFrameNumber,
final float videoFps, final float videoQuality, final long size,
final int time, final double bitrate, final double speed) {
final Statistics newStatistics = new Statistics(executionId, videoFrameNumber, videoFps, videoQuality, size, time, bitrate, speed);
lastReceivedStatistics.update(newStatistics);
if (statisticsCallbackFunction != null) {
try {
statisticsCallbackFunction.apply(lastReceivedStatistics);
} catch (final Exception e) {
Log.e(FFmpegKitConfig.TAG, "Exception thrown inside StatisticsCallback block", e);
}
}
}
/**
* <p>Returns the last received statistics data.
*
* @return last received statistics data
*/
public static Statistics getLastReceivedStatistics() {
return lastReceivedStatistics;
}
/**
* <p>Resets last received statistics. It is recommended to call it before starting a new execution.
*/
public static void resetStatistics() {
lastReceivedStatistics = new Statistics();
}
/**
* <p>Sets and overrides <code>fontconfig</code> configuration directory.
*
* @param path directory which contains fontconfig configuration (fonts.conf)
* @return zero on success, non-zero on error
*/
public static int setFontconfigConfigurationPath(final String path) {
return setNativeEnvironmentVariable("FONTCONFIG_PATH", path);
}
/**
* <p>Registers fonts inside the given path, so they are available to use in FFmpeg filters.
*
* <p>Note that you need to build <code>FFmpegKit</code> with <code>fontconfig</code>
* enabled or use a prebuilt package with <code>fontconfig</code> inside to use this feature.
*
* @param context application context to access application data
* @param fontDirectoryPath directory which contains fonts (.ttf and .otf files)
* @param fontNameMapping custom font name mappings, useful to access your fonts with more friendly names
*/
public static void setFontDirectory(final Context context, final String fontDirectoryPath, final Map<String, String> fontNameMapping) {
final File cacheDir = context.getCacheDir();
int validFontNameMappingCount = 0;
final File tempConfigurationDirectory = new File(cacheDir, ".ffmpegkit");
if (!tempConfigurationDirectory.exists()) {
boolean tempFontConfDirectoryCreated = tempConfigurationDirectory.mkdirs();
Log.d(TAG, String.format("Created temporary font conf directory: %s.", tempFontConfDirectoryCreated));
}
final File fontConfiguration = new File(tempConfigurationDirectory, "fonts.conf");
if (fontConfiguration.exists()) {
boolean fontConfigurationDeleted = fontConfiguration.delete();
Log.d(TAG, String.format("Deleted old temporary font configuration: %s.", fontConfigurationDeleted));
}
/* PROCESS MAPPINGS FIRST */
final StringBuilder fontNameMappingBlock = new StringBuilder("");
if (fontNameMapping != null && (fontNameMapping.size() > 0)) {
fontNameMapping.entrySet();
for (Map.Entry<String, String> mapping : fontNameMapping.entrySet()) {
String fontName = mapping.getKey();
String mappedFontName = mapping.getValue();
if ((fontName != null) && (mappedFontName != null) && (fontName.trim().length() > 0) && (mappedFontName.trim().length() > 0)) {
fontNameMappingBlock.append(" <match target=\"pattern\">\n");
fontNameMappingBlock.append(" <test qual=\"any\" name=\"family\">\n");
fontNameMappingBlock.append(String.format(" <string>%s</string>\n", fontName));
fontNameMappingBlock.append(" </test>\n");
fontNameMappingBlock.append(" <edit name=\"family\" mode=\"assign\" binding=\"same\">\n");
fontNameMappingBlock.append(String.format(" <string>%s</string>\n", mappedFontName));
fontNameMappingBlock.append(" </edit>\n");
fontNameMappingBlock.append(" </match>\n");
validFontNameMappingCount++;
}
}
}
final String fontConfig = "<?xml version=\"1.0\"?>\n" +
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n" +
"<fontconfig>\n" +
" <dir>.</dir>\n" +
" <dir>" + fontDirectoryPath + "</dir>\n" +
fontNameMappingBlock +
"</fontconfig>";
final AtomicReference<FileOutputStream> reference = new AtomicReference<>();
try {
final FileOutputStream outputStream = new FileOutputStream(fontConfiguration);
reference.set(outputStream);
outputStream.write(fontConfig.getBytes());
outputStream.flush();
Log.d(TAG, String.format("Saved new temporary font configuration with %d font name mappings.", validFontNameMappingCount));
setFontconfigConfigurationPath(tempConfigurationDirectory.getAbsolutePath());
Log.d(TAG, String.format("Font directory %s registered successfully.", fontDirectoryPath));
} catch (final IOException e) {
Log.e(TAG, String.format("Failed to set font directory: %s.", fontDirectoryPath), e);
} finally {
if (reference.get() != null) {
try {
reference.get().close();
} catch (IOException e) {
// DO NOT PRINT THIS ERROR
}
}
}
}
/**
* <p>Returns package name.
*
* @return guessed package name according to supported external libraries
* @since 3.0
*/
public static String getPackageName() {
return Packages.getPackageName();
}
/**
* <p>Returns supported external libraries.
*
* @return list of supported external libraries
* @since 3.0
*/
public static List<String> getExternalLibraries() {
return Packages.getExternalLibraries();
}
/**
* <p>Creates a new named pipe to use in <code>FFmpeg</code> operations.
*
* <p>Please note that creator is responsible of closing created pipes.
*
* @param context application context
* @return the full path of named pipe
*/
public static String registerNewFFmpegPipe(final Context context) {
// PIPES ARE CREATED UNDER THE CACHE DIRECTORY
final File cacheDir = context.getCacheDir();
final String newFFmpegPipePath = cacheDir + File.separator + FFMPEG_KIT_PIPE_PREFIX + (++lastCreatedPipeIndex);
// FIRST CLOSE OLD PIPES WITH THE SAME NAME
closeFFmpegPipe(newFFmpegPipePath);
int rc = registerNewNativeFFmpegPipe(newFFmpegPipePath);
if (rc == 0) {
return newFFmpegPipePath;
} else {
Log.e(TAG, String.format("Failed to register new FFmpeg pipe %s. Operation failed with rc=%d.", newFFmpegPipePath, rc));
return null;
}
}
/**
* <p>Closes a previously created <code>FFmpeg</code> pipe.
*
* @param ffmpegPipePath full path of ffmpeg pipe
*/
public static void closeFFmpegPipe(final String ffmpegPipePath) {
File file = new File(ffmpegPipePath);
if (file.exists()) {
file.delete();
}
}
/**
* Returns the list of camera ids supported.
*
* @param context application context
* @return the list of camera ids supported or an empty list if no supported camera is found
*/
public static List<String> getSupportedCameraIds(final Context context) {
final List<String> detectedCameraIdList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
detectedCameraIdList.addAll(CameraSupport.extractSupportedCameraIds(context));
}
return detectedCameraIdList;
}
/**
* <p>Returns FFmpeg version bundled within the library.
*
* @return FFmpeg version
*/
public static String getFFmpegVersion() {
return getNativeFFmpegVersion();
}
/**
* <p>Returns FFmpegKit library version.
*
* @return FFmpegKit version
*/
public static String getVersion() {
if (isLTSBuild()) {
return String.format("%s-lts", getNativeVersion());
} else {
return getNativeVersion();
}
}
/**
* <p>Returns whether FFmpegKit release is a long term release or not.
*
* @return YES or NO
*/
public static boolean isLTSBuild() {
return AbiDetect.isNativeLTSBuild();
}
/**
* <p>Returns FFmpegKit library build date.
*
* @return FFmpegKit library build date
*/
public static String getBuildDate() {
return getNativeBuildDate();
}
/**
* <p>Returns return code of last executed command.
*
* @return return code of last executed command
* @since 3.0
*/
public static int getLastReturnCode() {
return lastReturnCode;
}
/**
* <p>Returns log output of last executed single FFmpeg/FFprobe command.
*
* <p>This method does not support executing multiple concurrent commands. If you execute
* multiple commands at the same time, this method will return output from all executions.
*
* <p>Please note that disabling redirection using {@link FFmpegKitConfig#disableRedirection()} method
* also disables this functionality.
*
* @return output of the last executed command
* @since 3.0
*/
public static String getLastCommandOutput() {
String nativeLastCommandOutput = getNativeLastCommandOutput();
if (nativeLastCommandOutput != null) {
// REPLACING CH(13) WITH CH(10)
nativeLastCommandOutput = nativeLastCommandOutput.replace('\r', '\n');
}
return nativeLastCommandOutput;
}
/**
* <p>Prints the output of the last executed FFmpeg/FFprobe command to the Logcat at the
* specified priority.
*
* <p>This method does not support executing multiple concurrent commands. If you execute
* multiple commands at the same time, this method will print output from all executions.
*
* @param logPriority one of {@link Log#VERBOSE}, {@link Log#DEBUG}, {@link Log#INFO},
* {@link Log#WARN}, {@link Log#ERROR}, {@link Log#ASSERT}
* @since 4.3
*/
public static void printLastCommandOutput(int logPriority) {
final int LOGGER_ENTRY_MAX_LEN = 4 * 1000;
String buffer = getLastCommandOutput();
do {
if (buffer.length() <= LOGGER_ENTRY_MAX_LEN) {
Log.println(logPriority, FFmpegKitConfig.TAG, buffer);
buffer = "";
} else {
final int index = buffer.substring(0, LOGGER_ENTRY_MAX_LEN).lastIndexOf('\n');
if (index < 0) {
Log.println(logPriority, FFmpegKitConfig.TAG, buffer.substring(0, LOGGER_ENTRY_MAX_LEN));
buffer = buffer.substring(LOGGER_ENTRY_MAX_LEN);
} else {
Log.println(logPriority, FFmpegKitConfig.TAG, buffer.substring(0, index));
buffer = buffer.substring(index);
}
}
} while (buffer.length() > 0);
}
/**
* <p>Sets an environment variable.
*
* @param variableName environment variable name
* @param variableValue environment variable value
* @return zero on success, non-zero on error
*/
public static int setEnvironmentVariable(final String variableName, final String variableValue) {
return setNativeEnvironmentVariable(variableName, variableValue);
}
/**
* <p>Registers a new ignored signal. Ignored signals are not handled by the library.
*
* @param signal signal number to ignore
*/
public static void ignoreSignal(final Signal signal) {
ignoreNativeSignal(signal.getValue());
}
/**
* <p>Synchronously executes FFmpeg with arguments provided.
*
* @param executionId id of the execution
* @param arguments FFmpeg command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
static int ffmpegExecute(final long executionId, final String[] arguments) {
final FFmpegExecution currentFFmpegExecution = new FFmpegExecution(executionId, arguments);
executions.add(currentFFmpegExecution);
try {
final int lastReturnCode = nativeFFmpegExecute(executionId, arguments);
FFmpegKitConfig.setLastReturnCode(lastReturnCode);
return lastReturnCode;
} finally {
executions.remove(currentFFmpegExecution);
}
}
/**
* Updates return code value for the last executed command.
*
* @param newLastReturnCode new last return code value
*/
static void setLastReturnCode(int newLastReturnCode) {
lastReturnCode = newLastReturnCode;
}
/**
* <p>Lists ongoing FFmpeg executions.
*
* @return list of ongoing FFmpeg executions
*/
static List<FFmpegExecution> listFFmpegExecutions() {
return new ArrayList<>(executions);
}
/**
* <p>Enables native redirection. Necessary for log and statistics callback functions.
*/
private static native void enableNativeRedirection();
/**
* <p>Disables native redirection
*/
private static native void disableNativeRedirection();
/**
* Sets native log level
*
* @param level log level
*/
private static native void setNativeLogLevel(int level);
/**
* Returns native log level.
*
* @return log level
*/
private static native int getNativeLogLevel();
/**
* <p>Returns FFmpeg version bundled within the library natively.
*
* @return FFmpeg version
*/
private native static String getNativeFFmpegVersion();
/**
* <p>Returns FFmpegKit library version natively.
*
* @return FFmpegKit version
*/
private native static String getNativeVersion();
/**
* <p>Synchronously executes FFmpeg natively with arguments provided.
*
* @param executionId id of the execution
* @param arguments FFmpeg command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
private native static int nativeFFmpegExecute(final long executionId, final String[] arguments);
/**
* <p>Cancels an ongoing FFmpeg operation natively. This function does not wait for termination
* to complete and returns immediately.
*
* @param executionId id of the execution
*/
native static void nativeFFmpegCancel(final long executionId);
/**
* <p>Synchronously executes FFprobe natively with arguments provided.
*
* @param arguments FFprobe command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
native static int nativeFFprobeExecute(final String[] arguments);
/**
* <p>Creates natively a new named pipe to use in <code>FFmpeg</code> operations.
*
* <p>Please note that creator is responsible of closing created pipes.
*
* @param ffmpegPipePath full path of ffmpeg pipe
* @return zero on successful creation, non-zero on error
*/
private native static int registerNewNativeFFmpegPipe(final String ffmpegPipePath);
/**
* <p>Returns FFmpegKit library build date natively.
*
* @return FFmpegKit library build date
*/
private native static String getNativeBuildDate();
/**
* <p>Sets an environment variable natively.
*
* @param variableName environment variable name
* @param variableValue environment variable value
* @return zero on success, non-zero on error
*/
private native static int setNativeEnvironmentVariable(final String variableName, final String variableValue);
/**
* <p>Returns log output of the last executed single command natively.
*
* @return output of the last executed single command
*/
private native static String getNativeLastCommandOutput();
/**
* <p>Registers a new ignored signal natively. Ignored signals are not handled by the library.
*
* @param signum signal number
*/
private native static void ignoreNativeSignal(final int signum);
}

@ -0,0 +1,130 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.util.Log;
/**
* <p>Main class for FFprobe operations. Provides {@link #execute(String...)} method to execute
* FFprobe commands.
* <pre>
* int rc = FFprobe.execute("-hide_banner -v error -show_entries format=size -of default=noprint_wrappers=1 file1.mp4");
* Log.i(Config.TAG, String.format("Command execution %s.", (rc == 0?"completed successfully":"failed with rc=" + rc));
* </pre>
*/
public class FFprobeKit {
static {
AbiDetect.class.getName();
FFmpegKitConfig.class.getName();
}
/**
* Default constructor hidden.
*/
private FFprobeKit() {
}
/**
* <p>Synchronously executes FFprobe with arguments provided.
*
* @param arguments FFprobe command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
public static int execute(final String[] arguments) {
final int lastReturnCode = FFmpegKitConfig.nativeFFprobeExecute(arguments);
FFmpegKitConfig.setLastReturnCode(lastReturnCode);
return lastReturnCode;
}
/**
* <p>Synchronously executes FFprobe command provided. Space character is used to split command
* into arguments. You can use single and double quote characters to specify arguments inside
* your command.
*
* @param command FFprobe command
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
public static int execute(final String command) {
return execute(FFmpegKit.parseArguments(command));
}
/**
* <p>Returns media information for the given file.
*
* <p>This method does not support executing multiple concurrent operations. If you execute
* multiple operations (execute or getMediaInformation) at the same time, the response of this
* method is not predictable.
*
* @param path path or uri of media file
* @return media information
* @since 3.0
*/
public static MediaInformation getMediaInformation(final String path) {
return getMediaInformationFromCommandArguments(new String[]{"-v", "error", "-hide_banner", "-print_format", "json", "-show_format", "-show_streams", "-i", path});
}
/**
* <p>Returns media information for the given command.
*
* <p>This method does not support executing multiple concurrent operations. If you execute
* multiple operations (execute or getMediaInformation) at the same time, the response of this
* method is not predictable.
*
* @param command command to execute
* @return media information
* @since 4.3.3
*/
public static MediaInformation getMediaInformationFromCommand(final String command) {
return getMediaInformationFromCommandArguments(FFmpegKit.parseArguments(command));
}
/**
* <p>Returns media information for given file.
*
* <p>This method does not support executing multiple concurrent operations. If you execute
* multiple operations (execute or getMediaInformation) at the same time, the response of this
* method is not predictable.
*
* @param path path or uri of media file
* @param timeout complete timeout
* @return media information
* @since 3.0
* @deprecated this method is deprecated since v4.3.1. You can still use this method but
* <code>timeout</code> parameter is not effective anymore.
*/
public static MediaInformation getMediaInformation(final String path, final Long timeout) {
return getMediaInformation(path);
}
private static MediaInformation getMediaInformationFromCommandArguments(final String[] arguments) {
final int rc = execute(arguments);
if (rc == 0) {
return MediaInformationParser.from(FFmpegKitConfig.getLastCommandOutput());
} else {
Log.w(FFmpegKitConfig.TAG, FFmpegKitConfig.getLastCommandOutput());
return null;
}
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Represents a callback function to receive asynchronous getMediaInformation result.
*/
@FunctionalInterface
public interface GetMediaInformationCallback {
void apply(MediaInformation mediaInformation);
}

@ -0,0 +1,132 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Helper enumeration type for log levels.
*/
public enum Level {
/**
* This log level is defined by FFmpegKit. It is used to specify logs printed to stderr by
* ffmpeg. Logs that has this level are not filtered and always redirected.
*/
AV_LOG_STDERR(-16),
/**
* Print no output.
*/
AV_LOG_QUIET(-8),
/**
* Something went really wrong and we will crash now.
*/
AV_LOG_PANIC(0),
/**
* Something went wrong and recovery is not possible.
* For example, no header was found for a format which depends
* on headers or an illegal combination of parameters is used.
*/
AV_LOG_FATAL(8),
/**
* Something went wrong and cannot losslessly be recovered.
* However, not all future data is affected.
*/
AV_LOG_ERROR(16),
/**
* Something somehow does not look correct. This may or may not
* lead to problems. An example would be the use of '-vstrict -2'.
*/
AV_LOG_WARNING(24),
/**
* Standard information.
*/
AV_LOG_INFO(32),
/**
* Detailed information.
*/
AV_LOG_VERBOSE(40),
/**
* Stuff which is only useful for libav* developers.
*/
AV_LOG_DEBUG(48),
/**
* Extremely verbose debugging, useful for libav* development.
*/
AV_LOG_TRACE(56);
private int value;
/**
* <p>Returns enumeration defined by value.
*
* @param value level value
* @return enumeration defined by value
*/
public static Level from(final int value) {
if (value == AV_LOG_STDERR.getValue()) {
return AV_LOG_STDERR;
} else if (value == AV_LOG_QUIET.getValue()) {
return AV_LOG_QUIET;
} else if (value == AV_LOG_PANIC.getValue()) {
return AV_LOG_PANIC;
} else if (value == AV_LOG_FATAL.getValue()) {
return AV_LOG_FATAL;
} else if (value == AV_LOG_ERROR.getValue()) {
return AV_LOG_ERROR;
} else if (value == AV_LOG_WARNING.getValue()) {
return AV_LOG_WARNING;
} else if (value == AV_LOG_INFO.getValue()) {
return AV_LOG_INFO;
} else if (value == AV_LOG_VERBOSE.getValue()) {
return AV_LOG_VERBOSE;
} else if (value == AV_LOG_DEBUG.getValue()) {
return AV_LOG_DEBUG;
} else {
return AV_LOG_TRACE;
}
}
/**
* Returns level value.
*
* @return level value
*/
public int getValue() {
return value;
}
/**
* Creates new enum.
*
* @param value level value
*/
Level(final int value) {
this.value = value;
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Represents a callback function to receive logs from running executions
*/
@FunctionalInterface
public interface LogCallback {
void apply(final LogMessage message);
}

@ -0,0 +1,66 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Logs for running executions.
*/
public class LogMessage {
private final long executionId;
private final Level level;
private final String text;
public LogMessage(final long executionId, final Level level, final String text) {
this.executionId = executionId;
this.level = level;
this.text = text;
}
public long getExecutionId() {
return executionId;
}
public Level getLevel() {
return level;
}
public String getText() {
return text;
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("LogMessage{");
stringBuilder.append("executionId=");
stringBuilder.append(executionId);
stringBuilder.append(", level=");
stringBuilder.append(level);
stringBuilder.append(", text=");
stringBuilder.append("\'");
stringBuilder.append(text);
stringBuilder.append('\'');
stringBuilder.append('}');
return stringBuilder.toString();
}
}

@ -0,0 +1,208 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import org.json.JSONObject;
import java.util.List;
/**
* Media information class.
*/
public class MediaInformation {
private static final String KEY_MEDIA_PROPERTIES = "format";
private static final String KEY_FILENAME = "filename";
private static final String KEY_FORMAT = "format_name";
private static final String KEY_FORMAT_LONG = "format_long_name";
private static final String KEY_START_TIME = "start_time";
private static final String KEY_DURATION = "duration";
private static final String KEY_SIZE = "size";
private static final String KEY_BIT_RATE = "bit_rate";
private static final String KEY_TAGS = "tags";
/**
* Stores all properties.
*/
private final JSONObject jsonObject;
/**
* Stores streams.
*/
private final List<StreamInformation> streams;
public MediaInformation(final JSONObject jsonObject, final List<StreamInformation> streams) {
this.jsonObject = jsonObject;
this.streams = streams;
}
/**
* Returns file name.
*
* @return media file name
*/
public String getFilename() {
return getStringProperty(KEY_FILENAME);
}
/**
* Returns format.
*
* @return media format
*/
public String getFormat() {
return getStringProperty(KEY_FORMAT);
}
/**
* Returns long format.
*
* @return media long format
*/
public String getLongFormat() {
return getStringProperty(KEY_FORMAT_LONG);
}
/**
* Returns duration.
*
* @return media duration in milliseconds
*/
public String getDuration() {
return getStringProperty(KEY_DURATION);
}
/**
* Returns start time.
*
* @return media start time in milliseconds
*/
public String getStartTime() {
return getStringProperty(KEY_START_TIME);
}
/**
* Returns size.
*
* @return media size in bytes
*/
public String getSize() {
return getStringProperty(KEY_SIZE);
}
/**
* Returns bitrate.
*
* @return media bitrate in kb/s
*/
public String getBitrate() {
return getStringProperty(KEY_BIT_RATE);
}
/**
* Returns all tags.
*
* @return tags dictionary
*/
public JSONObject getTags() {
return getProperties(KEY_TAGS);
}
/**
* Returns all streams.
*
* @return list of streams
*/
public List<StreamInformation> getStreams() {
return streams;
}
/**
* Returns the media property associated with the key.
*
* @param key property key
* @return media property as string or null if the key is not found
*/
public String getStringProperty(final String key) {
JSONObject mediaProperties = getMediaProperties();
if (mediaProperties == null) {
return null;
}
if (mediaProperties.has(key)) {
return mediaProperties.optString(key);
} else {
return null;
}
}
/**
* Returns the media property associated with the key.
*
* @param key property key
* @return media property as Long or null if the key is not found
*/
public Long getNumberProperty(String key) {
JSONObject mediaProperties = getMediaProperties();
if (mediaProperties == null) {
return null;
}
if (mediaProperties.has(key)) {
return mediaProperties.optLong(key);
} else {
return null;
}
}
/**
* Returns the media properties associated with the key.
*
* @param key properties key
* @return media properties as a JSONObject or null if the key is not found
*/
public JSONObject getProperties(String key) {
JSONObject mediaProperties = getMediaProperties();
if (mediaProperties == null) {
return null;
}
return mediaProperties.optJSONObject(key);
}
/**
* Returns all media properties.
*
* @return all media properties as a JSONObject or null if no media properties are defined
*/
public JSONObject getMediaProperties() {
return jsonObject.optJSONObject(KEY_MEDIA_PROPERTIES);
}
/**
* Returns all properties defined.
*
* @return all properties as a JSONObject or null if no properties are defined
*/
public JSONObject getAllProperties() {
return jsonObject;
}
}

@ -0,0 +1,73 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Helper class for parsing {@link MediaInformation}.
*/
public class MediaInformationParser {
/**
* Extracts MediaInformation from the given ffprobe json output.
*
* @param ffprobeJsonOutput ffprobe json output
* @return created {@link MediaInformation} instance of null if a parsing error occurs
*/
public static MediaInformation from(final String ffprobeJsonOutput) {
try {
return fromWithError(ffprobeJsonOutput);
} catch (JSONException e) {
Log.e(FFmpegKitConfig.TAG, "MediaInformation parsing failed.", e);
e.printStackTrace();
return null;
}
}
/**
* Extracts MediaInformation from the given ffprobe json output.
*
* @param ffprobeJsonOutput ffprobe json output
* @return created {@link MediaInformation} instance
* @throws JSONException if a parsing error occurs
*/
public static MediaInformation fromWithError(final String ffprobeJsonOutput) throws JSONException {
JSONObject jsonObject = new JSONObject(ffprobeJsonOutput);
JSONArray streamArray = jsonObject.optJSONArray("streams");
ArrayList<StreamInformation> arrayList = new ArrayList<>();
for (int i = 0; streamArray != null && i < streamArray.length(); i++) {
JSONObject streamObject = streamArray.optJSONObject(i);
if (streamObject != null) {
arrayList.add(new StreamInformation(streamObject));
}
}
return new MediaInformation(jsonObject, arrayList);
}
}

@ -0,0 +1,273 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* <p>Provides helper methods to extract binary package information.
*/
class Packages {
private static final List<String> supportedExternalLibraries;
static {
supportedExternalLibraries = new ArrayList<>();
supportedExternalLibraries.add("fontconfig");
supportedExternalLibraries.add("freetype");
supportedExternalLibraries.add("fribidi");
supportedExternalLibraries.add("gmp");
supportedExternalLibraries.add("gnutls");
supportedExternalLibraries.add("kvazaar");
supportedExternalLibraries.add("mp3lame");
supportedExternalLibraries.add("libaom");
supportedExternalLibraries.add("libass");
supportedExternalLibraries.add("iconv");
supportedExternalLibraries.add("libilbc");
supportedExternalLibraries.add("libtheora");
supportedExternalLibraries.add("libvidstab");
supportedExternalLibraries.add("libvorbis");
supportedExternalLibraries.add("libvpx");
supportedExternalLibraries.add("libwebp");
supportedExternalLibraries.add("libxml2");
supportedExternalLibraries.add("opencore-amr");
supportedExternalLibraries.add("openh264");
supportedExternalLibraries.add("opus");
supportedExternalLibraries.add("rubberband");
supportedExternalLibraries.add("sdl2");
supportedExternalLibraries.add("shine");
supportedExternalLibraries.add("snappy");
supportedExternalLibraries.add("soxr");
supportedExternalLibraries.add("speex");
supportedExternalLibraries.add("tesseract");
supportedExternalLibraries.add("twolame");
supportedExternalLibraries.add("wavpack");
supportedExternalLibraries.add("x264");
supportedExternalLibraries.add("x265");
supportedExternalLibraries.add("xvid");
}
/**
* Returns enabled external libraries by FFmpeg.
*
* @return enabled external libraries
*/
static List<String> getExternalLibraries() {
final String buildConfiguration = AbiDetect.getNativeBuildConf();
final List<String> enabledLibraryList = new ArrayList<>();
for (String supportedExternalLibrary : supportedExternalLibraries) {
if (buildConfiguration.contains("enable-" + supportedExternalLibrary) ||
buildConfiguration.contains("enable-lib" + supportedExternalLibrary)) {
enabledLibraryList.add(supportedExternalLibrary);
}
}
Collections.sort(enabledLibraryList);
return enabledLibraryList;
}
/**
* Returns FFmpegKit binary package name.
*
* @return guessed FFmpegKit binary package name
*/
static String getPackageName() {
final List<String> externalLibraryList = getExternalLibraries();
final boolean speex = externalLibraryList.contains("speex");
final boolean fribidi = externalLibraryList.contains("fribidi");
final boolean gnutls = externalLibraryList.contains("gnutls");
final boolean xvid = externalLibraryList.contains("xvid");
boolean minGpl = false;
boolean https = false;
boolean httpsGpl = false;
boolean audio = false;
boolean video = false;
boolean full = false;
boolean fullGpl = false;
if (speex && fribidi) {
if (xvid) {
fullGpl = true;
} else {
full = true;
}
} else if (speex) {
audio = true;
} else if (fribidi) {
video = true;
} else if (xvid) {
if (gnutls) {
httpsGpl = true;
} else {
minGpl = true;
}
} else {
if (gnutls) {
https = true;
}
}
if (fullGpl) {
if (externalLibraryList.contains("fontconfig") &&
externalLibraryList.contains("freetype") &&
externalLibraryList.contains("fribidi") &&
externalLibraryList.contains("gmp") &&
externalLibraryList.contains("gnutls") &&
externalLibraryList.contains("kvazaar") &&
externalLibraryList.contains("mp3lame") &&
externalLibraryList.contains("libaom") &&
externalLibraryList.contains("libass") &&
externalLibraryList.contains("iconv") &&
externalLibraryList.contains("libilbc") &&
externalLibraryList.contains("libtheora") &&
externalLibraryList.contains("libvidstab") &&
externalLibraryList.contains("libvorbis") &&
externalLibraryList.contains("libvpx") &&
externalLibraryList.contains("libwebp") &&
externalLibraryList.contains("libxml2") &&
externalLibraryList.contains("opencore-amr") &&
externalLibraryList.contains("opus") &&
externalLibraryList.contains("shine") &&
externalLibraryList.contains("snappy") &&
externalLibraryList.contains("soxr") &&
externalLibraryList.contains("speex") &&
externalLibraryList.contains("twolame") &&
externalLibraryList.contains("wavpack") &&
externalLibraryList.contains("x264") &&
externalLibraryList.contains("x265") &&
externalLibraryList.contains("xvid")) {
return "full-gpl";
} else {
return "custom";
}
}
if (full) {
if (externalLibraryList.contains("fontconfig") &&
externalLibraryList.contains("freetype") &&
externalLibraryList.contains("fribidi") &&
externalLibraryList.contains("gmp") &&
externalLibraryList.contains("gnutls") &&
externalLibraryList.contains("kvazaar") &&
externalLibraryList.contains("mp3lame") &&
externalLibraryList.contains("libaom") &&
externalLibraryList.contains("libass") &&
externalLibraryList.contains("iconv") &&
externalLibraryList.contains("libilbc") &&
externalLibraryList.contains("libtheora") &&
externalLibraryList.contains("libvorbis") &&
externalLibraryList.contains("libvpx") &&
externalLibraryList.contains("libwebp") &&
externalLibraryList.contains("libxml2") &&
externalLibraryList.contains("opencore-amr") &&
externalLibraryList.contains("opus") &&
externalLibraryList.contains("shine") &&
externalLibraryList.contains("snappy") &&
externalLibraryList.contains("soxr") &&
externalLibraryList.contains("speex") &&
externalLibraryList.contains("twolame") &&
externalLibraryList.contains("wavpack")) {
return "full";
} else {
return "custom";
}
}
if (video) {
if (externalLibraryList.contains("fontconfig") &&
externalLibraryList.contains("freetype") &&
externalLibraryList.contains("fribidi") &&
externalLibraryList.contains("kvazaar") &&
externalLibraryList.contains("libaom") &&
externalLibraryList.contains("libass") &&
externalLibraryList.contains("iconv") &&
externalLibraryList.contains("libtheora") &&
externalLibraryList.contains("libvpx") &&
externalLibraryList.contains("libwebp") &&
externalLibraryList.contains("snappy")) {
return "video";
} else {
return "custom";
}
}
if (audio) {
if (externalLibraryList.contains("mp3lame") &&
externalLibraryList.contains("libilbc") &&
externalLibraryList.contains("libvorbis") &&
externalLibraryList.contains("opencore-amr") &&
externalLibraryList.contains("opus") &&
externalLibraryList.contains("shine") &&
externalLibraryList.contains("soxr") &&
externalLibraryList.contains("speex") &&
externalLibraryList.contains("twolame") &&
externalLibraryList.contains("wavpack")) {
return "audio";
} else {
return "custom";
}
}
if (httpsGpl) {
if (externalLibraryList.contains("gmp") &&
externalLibraryList.contains("gnutls") &&
externalLibraryList.contains("libvidstab") &&
externalLibraryList.contains("x264") &&
externalLibraryList.contains("x265") &&
externalLibraryList.contains("xvid")) {
return "https-gpl";
} else {
return "custom";
}
}
if (https) {
if (externalLibraryList.contains("gmp") &&
externalLibraryList.contains("gnutls")) {
return "https";
} else {
return "custom";
}
}
if (minGpl) {
if (externalLibraryList.contains("libvidstab") &&
externalLibraryList.contains("x264") &&
externalLibraryList.contains("x265") &&
externalLibraryList.contains("xvid")) {
return "min-gpl";
} else {
return "custom";
}
}
if (externalLibraryList.size() == 0) {
return "min";
} else {
return "custom";
}
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Lists signals handled by FFmpegKit library.
*/
public enum Signal {
SIGINT(2),
SIGQUIT(3),
SIGPIPE(13),
SIGTERM(15),
SIGXCPU(24);
private int value;
Signal(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}

@ -0,0 +1,180 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Statistics for running executions.
*/
public class Statistics {
private long executionId;
private int videoFrameNumber;
private float videoFps;
private float videoQuality;
private long size;
private int time;
private double bitrate;
private double speed;
public Statistics() {
executionId = 0;
videoFrameNumber = 0;
videoFps = 0;
videoQuality = 0;
size = 0;
time = 0;
bitrate = 0;
speed = 0;
}
public Statistics(long executionId, int videoFrameNumber, float videoFps, float videoQuality, long size, int time, double bitrate, double speed) {
this.executionId = executionId;
this.videoFrameNumber = videoFrameNumber;
this.videoFps = videoFps;
this.videoQuality = videoQuality;
this.size = size;
this.time = time;
this.bitrate = bitrate;
this.speed = speed;
}
public void update(final Statistics newStatistics) {
if (newStatistics != null) {
this.executionId = newStatistics.getExecutionId();
if (newStatistics.getVideoFrameNumber() > 0) {
this.videoFrameNumber = newStatistics.getVideoFrameNumber();
}
if (newStatistics.getVideoFps() > 0) {
this.videoFps = newStatistics.getVideoFps();
}
if (newStatistics.getVideoQuality() > 0) {
this.videoQuality = newStatistics.getVideoQuality();
}
if (newStatistics.getSize() > 0) {
this.size = newStatistics.getSize();
}
if (newStatistics.getTime() > 0) {
this.time = newStatistics.getTime();
}
if (newStatistics.getBitrate() > 0) {
this.bitrate = newStatistics.getBitrate();
}
if (newStatistics.getSpeed() > 0) {
this.speed = newStatistics.getSpeed();
}
}
}
public long getExecutionId() {
return executionId;
}
public void setExecutionId(long executionId) {
this.executionId = executionId;
}
public int getVideoFrameNumber() {
return videoFrameNumber;
}
public void setVideoFrameNumber(int videoFrameNumber) {
this.videoFrameNumber = videoFrameNumber;
}
public float getVideoFps() {
return videoFps;
}
public void setVideoFps(float videoFps) {
this.videoFps = videoFps;
}
public float getVideoQuality() {
return videoQuality;
}
public void setVideoQuality(float videoQuality) {
this.videoQuality = videoQuality;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public double getBitrate() {
return bitrate;
}
public void setBitrate(double bitrate) {
this.bitrate = bitrate;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Statistics{");
stringBuilder.append("executionId=");
stringBuilder.append(executionId);
stringBuilder.append(", videoFrameNumber=");
stringBuilder.append(videoFrameNumber);
stringBuilder.append(", videoFps=");
stringBuilder.append(videoFps);
stringBuilder.append(", videoQuality=");
stringBuilder.append(videoQuality);
stringBuilder.append(", size=");
stringBuilder.append(size);
stringBuilder.append(", time=");
stringBuilder.append(time);
stringBuilder.append(", bitrate=");
stringBuilder.append(bitrate);
stringBuilder.append(", speed=");
stringBuilder.append(speed);
stringBuilder.append('}');
return stringBuilder.toString();
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
/**
* <p>Represents a callback function to receive statistics from running executions.
*/
@FunctionalInterface
public interface StatisticsCallback {
void apply(final Statistics statistics);
}

@ -0,0 +1,281 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import org.json.JSONObject;
/**
* Stream information class.
*/
public class StreamInformation {
private static final String KEY_INDEX = "index";
private static final String KEY_TYPE = "codec_type";
private static final String KEY_CODEC = "codec_name";
private static final String KEY_CODEC_LONG = "codec_long_name";
private static final String KEY_FORMAT = "pix_fmt";
private static final String KEY_WIDTH = "width";
private static final String KEY_HEIGHT = "height";
private static final String KEY_BIT_RATE = "bit_rate";
private static final String KEY_SAMPLE_RATE = "sample_rate";
private static final String KEY_SAMPLE_FORMAT = "sample_fmt";
private static final String KEY_CHANNEL_LAYOUT = "channel_layout";
private static final String KEY_SAMPLE_ASPECT_RATIO = "sample_aspect_ratio";
private static final String KEY_DISPLAY_ASPECT_RATIO = "display_aspect_ratio";
private static final String KEY_AVERAGE_FRAME_RATE = "avg_frame_rate";
private static final String KEY_REAL_FRAME_RATE = "r_frame_rate";
private static final String KEY_TIME_BASE = "time_base";
private static final String KEY_CODEC_TIME_BASE = "codec_time_base";
private static final String KEY_TAGS = "tags";
/**
* Stores all properties.
*/
private final JSONObject jsonObject;
public StreamInformation(final JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
/**
* Returns stream index.
*
* @return stream index, starting from zero
*/
public Long getIndex() {
return getNumberProperty(KEY_INDEX);
}
/**
* Returns stream type.
*
* @return stream type; audio or video
*/
public String getType() {
return getStringProperty(KEY_TYPE);
}
/**
* Returns stream codec.
*
* @return stream codec
*/
public String getCodec() {
return getStringProperty(KEY_CODEC);
}
/**
* Returns full stream codec.
*
* @return stream codec with additional profile and mode information
*/
public String getFullCodec() {
return getStringProperty(KEY_CODEC_LONG);
}
/**
* Returns stream format.
*
* @return stream format
*/
public String getFormat() {
return getStringProperty(KEY_FORMAT);
}
/**
* Returns width.
*
* @return width in pixels
*/
public Long getWidth() {
return getNumberProperty(KEY_WIDTH);
}
/**
* Returns height.
*
* @return height in pixels
*/
public Long getHeight() {
return getNumberProperty(KEY_HEIGHT);
}
/**
* Returns bitrate.
*
* @return bitrate in kb/s
*/
public String getBitrate() {
return getStringProperty(KEY_BIT_RATE);
}
/**
* Returns sample rate.
*
* @return sample rate in hz
*/
public String getSampleRate() {
return getStringProperty(KEY_SAMPLE_RATE);
}
/**
* Returns sample format.
*
* @return sample format
*/
public String getSampleFormat() {
return getStringProperty(KEY_SAMPLE_FORMAT);
}
/**
* Returns channel layout.
*
* @return channel layout
*/
public String getChannelLayout() {
return getStringProperty(KEY_CHANNEL_LAYOUT);
}
/**
* Returns sample aspect ratio.
*
* @return sample aspect ratio
*/
public String getSampleAspectRatio() {
return getStringProperty(KEY_SAMPLE_ASPECT_RATIO);
}
/**
* Returns display aspect ratio.
*
* @return display aspect ratio
*/
public String getDisplayAspectRatio() {
return getStringProperty(KEY_DISPLAY_ASPECT_RATIO);
}
/**
* Returns display aspect ratio.
*
* @return average frame rate in fps
*/
public String getAverageFrameRate() {
return getStringProperty(KEY_AVERAGE_FRAME_RATE);
}
/**
* Returns real frame rate.
*
* @return real frame rate in tbr
*/
public String getRealFrameRate() {
return getStringProperty(KEY_REAL_FRAME_RATE);
}
/**
* Returns time base.
*
* @return time base in tbn
*/
public String getTimeBase() {
return getStringProperty(KEY_TIME_BASE);
}
/**
* Returns codec time base.
*
* @return codec time base in tbc
*/
public String getCodecTimeBase() {
return getStringProperty(KEY_CODEC_TIME_BASE);
}
/**
* Returns all tags.
*
* @return tags dictionary
*/
public JSONObject getTags() {
return getProperties(KEY_TAGS);
}
/**
* Returns the stream property associated with the key.
*
* @param key property key
* @return stream property as string or null if the key is not found
*/
public String getStringProperty(final String key) {
JSONObject mediaProperties = getAllProperties();
if (mediaProperties == null) {
return null;
}
if (mediaProperties.has(key)) {
return mediaProperties.optString(key);
} else {
return null;
}
}
/**
* Returns the stream property associated with the key.
*
* @param key property key
* @return stream property as Long or null if the key is not found
*/
public Long getNumberProperty(String key) {
JSONObject mediaProperties = getAllProperties();
if (mediaProperties == null) {
return null;
}
if (mediaProperties.has(key)) {
return mediaProperties.optLong(key);
} else {
return null;
}
}
/**
* Returns the stream properties associated with the key.
*
* @param key properties key
* @return stream properties as a JSONObject or null if the key is not found
*/
public JSONObject getProperties(String key) {
JSONObject mediaProperties = getAllProperties();
if (mediaProperties == null) {
return null;
}
return mediaProperties.optJSONObject(key);
}
/**
* Returns all stream properties defined.
*
* @return all stream properties as a JSONObject or null if no properties are defined
*/
public JSONObject getAllProperties() {
return jsonObject;
}
}

@ -0,0 +1,186 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* <p>Tests for {@link FFmpegKitConfig} class.
*/
public class FFmpegKitConfigTest {
private static final String externalLibrariesCommandOutput = " configuration:\n" +
" --cross-prefix=i686-linux-android-\n" +
" --sysroot=/Users/taner/Library/Android/sdk/ndk-bundle/toolchains/ffmpeg-kit-i686/sysroot\n" +
" --prefix=/Users/taner/Projects/ffmpeg-kit/prebuilt/android-x86/ffmpeg\n" +
" --pkg-config=/usr/local/bin/pkg-config --extra-cflags='-march=i686 -mtune=intel -mssse3 -mfpmath=sse -m32 -Wno-unused-function -fstrict-aliasing -fPIC -DANDROID -D__ANDROID__ -D__ANDROID_API__=21 -O2 -I/Users/taner/Library/Android/sdk/ndk-bundle/toolchains/ffmpeg-kit-i686/sysroot/usr/include -I/Users/taner/Library/Android/sdk/ndk-bundle/toolchains/ffmpeg-kit-i686/sysroot/usr/local/include'\n" +
" --extra-cxxflags='-std=c++11 -fno-exceptions -fno-rtti'\n" +
" --extra-ldflags='-march=i686 -Wl,--gc-sections,--icf=safe -lc -lm -ldl -llog -lc++_shared -L/Users/taner/Library/Android/sdk/ndk-bundle/toolchains/ffmpeg-kit-i686/i686-linux-android/lib -L/Users/taner/Library/Android/sdk/ndk-bundle/toolchains/ffmpeg-kit-i686/sysroot/usr/lib -L/Users/taner/Library/Android/sdk/ndk-bundle/toolchains/ffmpeg-kit-i686/lib -L/Users/taner/Library/Android/sdk/ndk-bundle/platforms/android-21/arch-x86/usr/lib'\n" +
" --enable-version3\n" +
" --arch=i686\n" +
" --cpu=i686\n" +
" --target-os=android\n" +
" --disable-neon\n" +
" --disable-asm\n" +
" --disable-inline-asm\n" +
" --enable-cross-compile\n" +
" --enable-pic\n" +
" --enable-jni\n" +
" --enable-libvorbis\n" +
" --enable-optimizations\n" +
" --enable-swscale\n" +
" --enable-shared\n" +
" --enable-v4l2-m2m\n" +
" --enable-small\n" +
" --disable-openssl\n" +
" --disable-xmm-clobber-test\n" +
" --disable-debug\n" +
" --disable-neon-clobber-test\n" +
" --disable-programs\n" +
" --disable-postproc\n" +
" --disable-doc\n" +
" --disable-htmlpages\n" +
" --disable-manpages\n" +
" --disable-podpages\n" +
" --disable-txtpages\n" +
" --disable-static\n" +
" --disable-sndio\n" +
" --disable-schannel\n" +
" --disable-securetransport\n" +
" --disable-xlib\n" +
" --disable-cuda\n" +
" --disable-cuvid\n" +
" --disable-nvenc\n" +
" --disable-vaapi\n" +
" --disable-vdpau\n" +
" --disable-videotoolbox\n" +
" --disable-audiotoolbox\n" +
" --disable-appkit\n" +
" --disable-alsa\n" +
" --disable-cuda\n" +
" --disable-cuvid\n" +
" --disable-nvenc\n" +
" --disable-vaapi\n" +
" --disable-vdpau\n" +
" --disable-zlib\n";
@Test
public void getExternalLibraries() {
final List<String> supportedExternalLibraries = new ArrayList<>();
supportedExternalLibraries.add("chromaprint");
supportedExternalLibraries.add("fontconfig");
supportedExternalLibraries.add("freetype");
supportedExternalLibraries.add("fribidi");
supportedExternalLibraries.add("gmp");
supportedExternalLibraries.add("gnutls");
supportedExternalLibraries.add("kvazaar");
supportedExternalLibraries.add("lame");
supportedExternalLibraries.add("libaom");
supportedExternalLibraries.add("libass");
supportedExternalLibraries.add("libiconv");
supportedExternalLibraries.add("libilbc");
supportedExternalLibraries.add("libtheora");
supportedExternalLibraries.add("libvidstab");
supportedExternalLibraries.add("libvorbis");
supportedExternalLibraries.add("libvpx");
supportedExternalLibraries.add("libwebp");
supportedExternalLibraries.add("libxml2");
supportedExternalLibraries.add("opencore-amr");
supportedExternalLibraries.add("opus");
supportedExternalLibraries.add("shine");
supportedExternalLibraries.add("sdl");
supportedExternalLibraries.add("snappy");
supportedExternalLibraries.add("soxr");
supportedExternalLibraries.add("speex");
supportedExternalLibraries.add("tesseract");
supportedExternalLibraries.add("twolame");
supportedExternalLibraries.add("wavpack");
supportedExternalLibraries.add("x264");
supportedExternalLibraries.add("x265");
supportedExternalLibraries.add("xvidcore");
supportedExternalLibraries.add("android-zlib");
supportedExternalLibraries.add("android-media-codec");
final List<String> enabledList = new ArrayList<>();
for (String supportedExternalLibrary : supportedExternalLibraries) {
if (externalLibrariesCommandOutput.contains("enable-" + supportedExternalLibrary) ||
externalLibrariesCommandOutput.contains("enable-lib" + supportedExternalLibrary)) {
enabledList.add(supportedExternalLibrary);
}
}
Collections.sort(enabledList);
Assert.assertNotNull(enabledList);
Assert.assertEquals(1, enabledList.size());
}
@Test
public void getPackageName() {
Assert.assertEquals("min", listToPackageName(Collections.singletonList("")));
Assert.assertEquals("min-gpl", listToPackageName(Collections.singletonList("xvidcore")));
Assert.assertEquals("full-gpl", listToPackageName(Arrays.asList("gnutls", "speex", "fribidi", "xvidcore")));
Assert.assertEquals("full", listToPackageName(Arrays.asList("fribidi", "speex")));
Assert.assertEquals("video", listToPackageName(Collections.singletonList("fribidi")));
Assert.assertEquals("audio", listToPackageName(Collections.singletonList("speex")));
Assert.assertEquals("https", listToPackageName(Collections.singletonList("gnutls")));
Assert.assertEquals("https-gpl", listToPackageName(Arrays.asList("gnutls", "xvidcore")));
}
private String listToPackageName(final List<String> externalLibraryList) {
boolean speex = externalLibraryList.contains("speex");
boolean fribidi = externalLibraryList.contains("fribidi");
boolean gnutls = externalLibraryList.contains("gnutls");
boolean xvidcore = externalLibraryList.contains("xvidcore");
if (speex && fribidi) {
if (xvidcore) {
return "full-gpl";
} else {
return "full";
}
} else if (speex) {
return "audio";
} else if (fribidi) {
return "video";
} else if (xvidcore) {
if (gnutls) {
return "https-gpl";
} else {
return "min-gpl";
}
} else {
if (gnutls) {
return "https";
} else {
return "min";
}
}
}
}

@ -0,0 +1,746 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
package com.arthenica.ffmpegkit;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
/**
* <p>Tests for {@link FFmpegKit} class.
*/
public class FFmpegKitTest {
private static final String MEDIA_INFORMATION_MP3 =
"{\n" +
" \"streams\": [\n" +
" {\n" +
" \"index\": 0,\n" +
" \"codec_name\": \"mp3\",\n" +
" \"codec_long_name\": \"MP3 (MPEG audio layer 3)\",\n" +
" \"codec_type\": \"audio\",\n" +
" \"codec_time_base\": \"1/44100\",\n" +
" \"codec_tag_string\": \"[0][0][0][0]\",\n" +
" \"codec_tag\": \"0x0000\",\n" +
" \"sample_fmt\": \"fltp\",\n" +
" \"sample_rate\": \"44100\",\n" +
" \"channels\": 2,\n" +
" \"channel_layout\": \"stereo\",\n" +
" \"bits_per_sample\": 0,\n" +
" \"r_frame_rate\": \"0/0\",\n" +
" \"avg_frame_rate\": \"0/0\",\n" +
" \"time_base\": \"1/14112000\",\n" +
" \"start_pts\": 169280,\n" +
" \"start_time\": \"0.011995\",\n" +
" \"duration_ts\": 4622376960,\n" +
" \"duration\": \"327.549388\",\n" +
" \"bit_rate\": \"320000\",\n" +
" \"disposition\": {\n" +
" \"default\": 0,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" },\n" +
" \"tags\": {\n" +
" \"encoder\": \"Lavf\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"format\": {\n" +
" \"filename\": \"sample.mp3\",\n" +
" \"nb_streams\": 1,\n" +
" \"nb_programs\": 0,\n" +
" \"format_name\": \"mp3\",\n" +
" \"format_long_name\": \"MP2/3 (MPEG audio layer 2/3)\",\n" +
" \"start_time\": \"0.011995\",\n" +
" \"duration\": \"327.549388\",\n" +
" \"size\": \"13103064\",\n" +
" \"bit_rate\": \"320026\",\n" +
" \"probe_score\": 51,\n" +
" \"tags\": {\n" +
" \"encoder\": \"Lavf58.20.100\",\n" +
" \"album\": \"Impact\",\n" +
" \"artist\": \"Kevin MacLeod\",\n" +
" \"comment\": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit finito.\",\n" +
" \"genre\": \"Cinematic\",\n" +
" \"title\": \"Impact Moderato\"\n" +
" }\n" +
" }\n" +
"}";
private static final String MEDIA_INFORMATION_JPG =
"{\n" +
" \"streams\": [\n" +
" {\n" +
" \"index\": 0,\n" +
" \"codec_name\": \"mjpeg\",\n" +
" \"codec_long_name\": \"Motion JPEG\",\n" +
" \"profile\": \"Baseline\",\n" +
" \"codec_type\": \"video\",\n" +
" \"codec_time_base\": \"0/1\",\n" +
" \"codec_tag_string\": \"[0][0][0][0]\",\n" +
" \"codec_tag\": \"0x0000\",\n" +
" \"width\": 1496,\n" +
" \"height\": 1729,\n" +
" \"coded_width\": 1496,\n" +
" \"coded_height\": 1729,\n" +
" \"has_b_frames\": 0,\n" +
" \"sample_aspect_ratio\": \"1:1\",\n" +
" \"display_aspect_ratio\": \"1496:1729\",\n" +
" \"pix_fmt\": \"yuvj444p\",\n" +
" \"level\": -99,\n" +
" \"color_range\": \"pc\",\n" +
" \"color_space\": \"bt470bg\",\n" +
" \"chroma_location\": \"center\",\n" +
" \"refs\": 1,\n" +
" \"r_frame_rate\": \"25/1\",\n" +
" \"avg_frame_rate\": \"0/0\",\n" +
" \"time_base\": \"1/25\",\n" +
" \"start_pts\": 0,\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration_ts\": 1,\n" +
" \"duration\": \"0.040000\",\n" +
" \"bits_per_raw_sample\": \"8\",\n" +
" \"disposition\": {\n" +
" \"default\": 0,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"format\": {\n" +
" \"filename\": \"sample.jpg\",\n" +
" \"nb_streams\": 1,\n" +
" \"nb_programs\": 0,\n" +
" \"format_name\": \"image2\",\n" +
" \"format_long_name\": \"image2 sequence\",\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration\": \"0.040000\",\n" +
" \"size\": \"1659050\",\n" +
" \"bit_rate\": \"331810000\",\n" +
" \"probe_score\": 50\n" +
" }\n" +
"}";
private static final String MEDIA_INFORMATION_GIF =
"{\n" +
" \"streams\": [\n" +
" {\n" +
" \"index\": 0,\n" +
" \"codec_name\": \"gif\",\n" +
" \"codec_long_name\": \"CompuServe GIF (Graphics Interchange Format)\",\n" +
" \"codec_type\": \"video\",\n" +
" \"codec_time_base\": \"12/133\",\n" +
" \"codec_tag_string\": \"[0][0][0][0]\",\n" +
" \"codec_tag\": \"0x0000\",\n" +
" \"width\": 400,\n" +
" \"height\": 400,\n" +
" \"coded_width\": 400,\n" +
" \"coded_height\": 400,\n" +
" \"has_b_frames\": 0,\n" +
" \"pix_fmt\": \"bgra\",\n" +
" \"level\": -99,\n" +
" \"refs\": 1,\n" +
" \"r_frame_rate\": \"100/9\",\n" +
" \"avg_frame_rate\": \"133/12\",\n" +
" \"time_base\": \"1/100\",\n" +
" \"start_pts\": 0,\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration_ts\": 396,\n" +
" \"duration\": \"3.960000\",\n" +
" \"nb_frames\": \"44\",\n" +
" \"disposition\": {\n" +
" \"default\": 0,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"format\": {\n" +
" \"filename\": \"sample.gif\",\n" +
" \"nb_streams\": 1,\n" +
" \"nb_programs\": 0,\n" +
" \"format_name\": \"gif\",\n" +
" \"format_long_name\": \"CompuServe Graphics Interchange Format (GIF)\",\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration\": \"3.960000\",\n" +
" \"size\": \"1001718\",\n" +
" \"bit_rate\": \"2023672\",\n" +
" \"probe_score\": 100\n" +
" }\n" +
"}";
private static final String MEDIA_INFORMATION_MP4 =
"{\n" +
" \"streams\": [\n" +
" {\n" +
" \"index\": 0,\n" +
" \"codec_name\": \"h264\",\n" +
" \"codec_long_name\": \"H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10\",\n" +
" \"profile\": \"Main\",\n" +
" \"codec_type\": \"video\",\n" +
" \"codec_time_base\": \"1/60\",\n" +
" \"codec_tag_string\": \"avc1\",\n" +
" \"codec_tag\": \"0x31637661\",\n" +
" \"width\": 1280,\n" +
" \"height\": 720,\n" +
" \"coded_width\": 1280,\n" +
" \"coded_height\": 720,\n" +
" \"has_b_frames\": 0,\n" +
" \"sample_aspect_ratio\": \"1:1\",\n" +
" \"display_aspect_ratio\": \"16:9\",\n" +
" \"pix_fmt\": \"yuv420p\",\n" +
" \"level\": 42,\n" +
" \"chroma_location\": \"left\",\n" +
" \"refs\": 1,\n" +
" \"is_avc\": \"true\",\n" +
" \"nal_length_size\": \"4\",\n" +
" \"r_frame_rate\": \"30/1\",\n" +
" \"avg_frame_rate\": \"30/1\",\n" +
" \"time_base\": \"1/15360\",\n" +
" \"start_pts\": 0,\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration_ts\": 215040,\n" +
" \"duration\": \"14.000000\",\n" +
" \"bit_rate\": \"9166570\",\n" +
" \"bits_per_raw_sample\": \"8\",\n" +
" \"nb_frames\": \"420\",\n" +
" \"disposition\": {\n" +
" \"default\": 1,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" },\n" +
" \"tags\": {\n" +
" \"language\": \"und\",\n" +
" \"handler_name\": \"VideoHandler\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"format\": {\n" +
" \"filename\": \"sample.mp4\",\n" +
" \"nb_streams\": 1,\n" +
" \"nb_programs\": 0,\n" +
" \"format_name\": \"mov,mp4,m4a,3gp,3g2,mj2\",\n" +
" \"format_long_name\": \"QuickTime / MOV\",\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration\": \"14.000000\",\n" +
" \"size\": \"16044159\",\n" +
" \"bit_rate\": \"9168090\",\n" +
" \"probe_score\": 100,\n" +
" \"tags\": {\n" +
" \"major_brand\": \"isom\",\n" +
" \"minor_version\": \"512\",\n" +
" \"compatible_brands\": \"isomiso2avc1mp41\",\n" +
" \"encoder\": \"Lavf58.33.100\"\n" +
" }\n" +
" }\n" +
"}";
private static final String MEDIA_INFORMATION_PNG =
"{\n" +
" \"streams\": [\n" +
" {\n" +
" \"index\": 0,\n" +
" \"codec_name\": \"png\",\n" +
" \"codec_long_name\": \"PNG (Portable Network Graphics) image\",\n" +
" \"codec_type\": \"video\",\n" +
" \"codec_time_base\": \"0/1\",\n" +
" \"codec_tag_string\": \"[0][0][0][0]\",\n" +
" \"codec_tag\": \"0x0000\",\n" +
" \"width\": 1198,\n" +
" \"height\": 1198,\n" +
" \"coded_width\": 1198,\n" +
" \"coded_height\": 1198,\n" +
" \"has_b_frames\": 0,\n" +
" \"sample_aspect_ratio\": \"1:1\",\n" +
" \"display_aspect_ratio\": \"1:1\",\n" +
" \"pix_fmt\": \"pal8\",\n" +
" \"level\": -99,\n" +
" \"color_range\": \"pc\",\n" +
" \"refs\": 1,\n" +
" \"r_frame_rate\": \"25/1\",\n" +
" \"avg_frame_rate\": \"0/0\",\n" +
" \"time_base\": \"1/25\",\n" +
" \"disposition\": {\n" +
" \"default\": 0,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"format\": {\n" +
" \"filename\": \"sample.png\",\n" +
" \"nb_streams\": 1,\n" +
" \"nb_programs\": 0,\n" +
" \"format_name\": \"png_pipe\",\n" +
" \"format_long_name\": \"piped png sequence\",\n" +
" \"size\": \"31533\",\n" +
" \"probe_score\": 99\n" +
" }\n" +
"}";
private static final String MEDIA_INFORMATION_OGG =
"{\n" +
" \"streams\": [\n" +
" {\n" +
" \"index\": 0,\n" +
" \"codec_name\": \"theora\",\n" +
" \"codec_long_name\": \"Theora\",\n" +
" \"codec_type\": \"video\",\n" +
" \"codec_time_base\": \"1/25\",\n" +
" \"codec_tag_string\": \"[0][0][0][0]\",\n" +
" \"codec_tag\": \"0x0000\",\n" +
" \"width\": 1920,\n" +
" \"height\": 1080,\n" +
" \"coded_width\": 1920,\n" +
" \"coded_height\": 1088,\n" +
" \"has_b_frames\": 0,\n" +
" \"pix_fmt\": \"yuv420p\",\n" +
" \"level\": -99,\n" +
" \"color_space\": \"bt470bg\",\n" +
" \"color_transfer\": \"bt709\",\n" +
" \"color_primaries\": \"bt470bg\",\n" +
" \"chroma_location\": \"center\",\n" +
" \"refs\": 1,\n" +
" \"r_frame_rate\": \"25/1\",\n" +
" \"avg_frame_rate\": \"25/1\",\n" +
" \"time_base\": \"1/25\",\n" +
" \"start_pts\": 0,\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration_ts\": 813,\n" +
" \"duration\": \"32.520000\",\n" +
" \"disposition\": {\n" +
" \"default\": 0,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" },\n" +
" \"tags\": {\n" +
" \"ENCODER\": \"ffmpeg2theora 0.19\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"index\": 1,\n" +
" \"codec_name\": \"vorbis\",\n" +
" \"codec_long_name\": \"Vorbis\",\n" +
" \"codec_type\": \"audio\",\n" +
" \"codec_time_base\": \"1/48000\",\n" +
" \"codec_tag_string\": \"[0][0][0][0]\",\n" +
" \"codec_tag\": \"0x0000\",\n" +
" \"sample_fmt\": \"fltp\",\n" +
" \"sample_rate\": \"48000\",\n" +
" \"channels\": 2,\n" +
" \"channel_layout\": \"stereo\",\n" +
" \"bits_per_sample\": 0,\n" +
" \"r_frame_rate\": \"0/0\",\n" +
" \"avg_frame_rate\": \"0/0\",\n" +
" \"time_base\": \"1/48000\",\n" +
" \"start_pts\": 0,\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration_ts\": 1583850,\n" +
" \"duration\": \"32.996875\",\n" +
" \"bit_rate\": \"80000\",\n" +
" \"disposition\": {\n" +
" \"default\": 0,\n" +
" \"dub\": 0,\n" +
" \"original\": 0,\n" +
" \"comment\": 0,\n" +
" \"lyrics\": 0,\n" +
" \"karaoke\": 0,\n" +
" \"forced\": 0,\n" +
" \"hearing_impaired\": 0,\n" +
" \"visual_impaired\": 0,\n" +
" \"clean_effects\": 0,\n" +
" \"attached_pic\": 0,\n" +
" \"timed_thumbnails\": 0\n" +
" },\n" +
" \"tags\": {\n" +
" \"ENCODER\": \"ffmpeg2theora 0.19\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"format\": {\n" +
" \"filename\": \"sample.ogg\",\n" +
" \"nb_streams\": 2,\n" +
" \"nb_programs\": 0,\n" +
" \"format_name\": \"ogg\",\n" +
" \"format_long_name\": \"Ogg\",\n" +
" \"start_time\": \"0.000000\",\n" +
" \"duration\": \"32.996875\",\n" +
" \"size\": \"27873937\",\n" +
" \"bit_rate\": \"6757958\",\n" +
" \"probe_score\": 100\n" +
" }\n" +
"}";
@Test
public void mediaInformationMp3() {
MediaInformation mediaInformation = MediaInformationParser.from(MEDIA_INFORMATION_MP3);
Assert.assertNotNull(mediaInformation);
assertMediaInput(mediaInformation, "mp3", "sample.mp3");
assertMediaDuration(mediaInformation, "327.549388", "0.011995", "320026");
assertTag(mediaInformation, "comment", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit finito.");
assertTag(mediaInformation, "album", "Impact");
assertTag(mediaInformation, "title", "Impact Moderato");
assertTag(mediaInformation, "artist", "Kevin MacLeod");
Assert.assertNotNull(mediaInformation.getStreams());
Assert.assertEquals(1, mediaInformation.getStreams().size());
assertAudioStream(mediaInformation.getStreams().get(0), 0L, "mp3", "MP3 (MPEG audio layer 3)", "44100", "stereo", "fltp", "320000");
}
@Test
public void mediaInformationJpg() {
MediaInformation mediaInformation = MediaInformationParser.from(MEDIA_INFORMATION_JPG);
Assert.assertNotNull(mediaInformation);
assertMediaInput(mediaInformation, "image2", "sample.jpg");
assertMediaDuration(mediaInformation, "0.040000", "0.000000", "331810000");
Assert.assertNotNull(mediaInformation.getStreams());
Assert.assertEquals(1, mediaInformation.getStreams().size());
assertVideoStream(mediaInformation.getStreams().get(0), 0L, "mjpeg", "Motion JPEG", "yuvj444p", 1496L, 1729L, "1:1", "1496:1729", null, "0/0", "25/1", "1/25", "0/1");
}
@Test
public void mediaInformationGif() {
MediaInformation mediaInformation = MediaInformationParser.from(MEDIA_INFORMATION_GIF);
Assert.assertNotNull(mediaInformation);
assertMediaInput(mediaInformation, "gif", "sample.gif");
assertMediaDuration(mediaInformation, "3.960000", "0.000000", "2023672");
Assert.assertNotNull(mediaInformation.getStreams());
Assert.assertEquals(1, mediaInformation.getStreams().size());
assertVideoStream(mediaInformation.getStreams().get(0), 0L, "gif", "CompuServe GIF (Graphics Interchange Format)", "bgra", 400L, 400L, null, null, null, "133/12", "100/9", "1/100", "12/133");
}
@Test
public void mediaInformationMp4() {
MediaInformation mediaInformation = MediaInformationParser.from(MEDIA_INFORMATION_MP4);
Assert.assertNotNull(mediaInformation);
assertMediaInput(mediaInformation, "mov,mp4,m4a,3gp,3g2,mj2", "sample.mp4");
assertMediaDuration(mediaInformation, "14.000000", "0.000000", "9168090");
assertTag(mediaInformation, "major_brand", "isom");
assertTag(mediaInformation, "minor_version", "512");
assertTag(mediaInformation, "compatible_brands", "isomiso2avc1mp41");
assertTag(mediaInformation, "encoder", "Lavf58.33.100");
Assert.assertNotNull(mediaInformation.getStreams());
Assert.assertEquals(1, mediaInformation.getStreams().size());
assertVideoStream(mediaInformation.getStreams().get(0), 0L, "h264", "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", "yuv420p", 1280L, 720L, "1:1", "16:9", "9166570", "30/1", "30/1", "1/15360", "1/60");
assertStreamTag(mediaInformation.getStreams().get(0), "language", "und");
assertStreamTag(mediaInformation.getStreams().get(0), "handler_name", "VideoHandler");
}
@Test
public void mediaInformationPng() {
MediaInformation mediaInformation = MediaInformationParser.from(MEDIA_INFORMATION_PNG);
Assert.assertNotNull(mediaInformation);
assertMediaInput(mediaInformation, "png_pipe", "sample.png");
assertMediaDuration(mediaInformation, null, null, null);
Assert.assertNotNull(mediaInformation.getStreams());
Assert.assertEquals(1, mediaInformation.getStreams().size());
assertVideoStream(mediaInformation.getStreams().get(0), 0L, "png", "PNG (Portable Network Graphics) image", "pal8", 1198L, 1198L, "1:1", "1:1", null, "0/0", "25/1", "1/25", "0/1");
}
@Test
public void mediaInformationOgg() {
MediaInformation mediaInformation = MediaInformationParser.from(MEDIA_INFORMATION_OGG);
Assert.assertNotNull(mediaInformation);
assertMediaInput(mediaInformation, "ogg", "sample.ogg");
assertMediaDuration(mediaInformation, "32.996875", "0.000000", "6757958");
Assert.assertNotNull(mediaInformation.getStreams());
Assert.assertEquals(2, mediaInformation.getStreams().size());
assertVideoStream(mediaInformation.getStreams().get(0), 0L, "theora", "Theora", "yuv420p", 1920L, 1080L, null, null, null, "25/1", "25/1", "1/25", "1/25");
assertAudioStream(mediaInformation.getStreams().get(1), 1L, "vorbis", "Vorbis", "48000", "stereo", "fltp", "80000");
assertStreamTag(mediaInformation.getStreams().get(0), "ENCODER", "ffmpeg2theora 0.19");
assertStreamTag(mediaInformation.getStreams().get(1), "ENCODER", "ffmpeg2theora 0.19");
}
@Test
public void parseSimpleCommand() {
final String[] argumentArray = FFmpegKit.parseArguments("-hide_banner -loop 1 -i file.jpg -filter_complex [0:v]setpts=PTS-STARTPTS[video] -map [video] -vsync 2 -async 1 video.mp4");
Assert.assertNotNull(argumentArray);
Assert.assertEquals(14, argumentArray.length);
Assert.assertEquals("-hide_banner", argumentArray[0]);
Assert.assertEquals("-loop", argumentArray[1]);
Assert.assertEquals("1", argumentArray[2]);
Assert.assertEquals("-i", argumentArray[3]);
Assert.assertEquals("file.jpg", argumentArray[4]);
Assert.assertEquals("-filter_complex", argumentArray[5]);
Assert.assertEquals("[0:v]setpts=PTS-STARTPTS[video]", argumentArray[6]);
Assert.assertEquals("-map", argumentArray[7]);
Assert.assertEquals("[video]", argumentArray[8]);
Assert.assertEquals("-vsync", argumentArray[9]);
Assert.assertEquals("2", argumentArray[10]);
Assert.assertEquals("-async", argumentArray[11]);
Assert.assertEquals("1", argumentArray[12]);
Assert.assertEquals("video.mp4", argumentArray[13]);
}
@Test
public void parseSingleQuotesInCommand() {
String[] argumentArray = FFmpegKit.parseArguments("-loop 1 'file one.jpg' -filter_complex '[0:v]setpts=PTS-STARTPTS[video]' -map [video] video.mp4 ");
Assert.assertNotNull(argumentArray);
Assert.assertEquals(8, argumentArray.length);
Assert.assertEquals("-loop", argumentArray[0]);
Assert.assertEquals("1", argumentArray[1]);
Assert.assertEquals("file one.jpg", argumentArray[2]);
Assert.assertEquals("-filter_complex", argumentArray[3]);
Assert.assertEquals("[0:v]setpts=PTS-STARTPTS[video]", argumentArray[4]);
Assert.assertEquals("-map", argumentArray[5]);
Assert.assertEquals("[video]", argumentArray[6]);
Assert.assertEquals("video.mp4", argumentArray[7]);
}
@Test
public void parseDoubleQuotesInCommand() {
String[] argumentArray = FFmpegKit.parseArguments("-loop 1 \"file one.jpg\" -filter_complex \"[0:v]setpts=PTS-STARTPTS[video]\" -map [video] video.mp4 ");
Assert.assertNotNull(argumentArray);
Assert.assertEquals(8, argumentArray.length);
Assert.assertEquals("-loop", argumentArray[0]);
Assert.assertEquals("1", argumentArray[1]);
Assert.assertEquals("file one.jpg", argumentArray[2]);
Assert.assertEquals("-filter_complex", argumentArray[3]);
Assert.assertEquals("[0:v]setpts=PTS-STARTPTS[video]", argumentArray[4]);
Assert.assertEquals("-map", argumentArray[5]);
Assert.assertEquals("[video]", argumentArray[6]);
Assert.assertEquals("video.mp4", argumentArray[7]);
argumentArray = FFmpegKit.parseArguments(" -i file:///tmp/input.mp4 -vcodec libx264 -vf \"scale=1024:1024,pad=width=1024:height=1024:x=0:y=0:color=black\" -acodec copy -q:v 0 -q:a 0 video.mp4");
Assert.assertNotNull(argumentArray);
Assert.assertEquals(13, argumentArray.length);
Assert.assertEquals("-i", argumentArray[0]);
Assert.assertEquals("file:///tmp/input.mp4", argumentArray[1]);
Assert.assertEquals("-vcodec", argumentArray[2]);
Assert.assertEquals("libx264", argumentArray[3]);
Assert.assertEquals("-vf", argumentArray[4]);
Assert.assertEquals("scale=1024:1024,pad=width=1024:height=1024:x=0:y=0:color=black", argumentArray[5]);
Assert.assertEquals("-acodec", argumentArray[6]);
Assert.assertEquals("copy", argumentArray[7]);
Assert.assertEquals("-q:v", argumentArray[8]);
Assert.assertEquals("0", argumentArray[9]);
Assert.assertEquals("-q:a", argumentArray[10]);
Assert.assertEquals("0", argumentArray[11]);
Assert.assertEquals("video.mp4", argumentArray[12]);
}
@Test
public void parseDoubleQuotesAndEscapesInCommand() {
String[] argumentArray = FFmpegKit.parseArguments(" -i file:///tmp/input.mp4 -vf \"subtitles=file:///tmp/subtitles.srt:force_style=\'FontSize=16,PrimaryColour=&HFFFFFF&\'\" -vcodec libx264 -acodec copy -q:v 0 -q:a 0 video.mp4");
Assert.assertNotNull(argumentArray);
Assert.assertEquals(13, argumentArray.length);
Assert.assertEquals("-i", argumentArray[0]);
Assert.assertEquals("file:///tmp/input.mp4", argumentArray[1]);
Assert.assertEquals("-vf", argumentArray[2]);
Assert.assertEquals("subtitles=file:///tmp/subtitles.srt:force_style='FontSize=16,PrimaryColour=&HFFFFFF&'", argumentArray[3]);
Assert.assertEquals("-vcodec", argumentArray[4]);
Assert.assertEquals("libx264", argumentArray[5]);
Assert.assertEquals("-acodec", argumentArray[6]);
Assert.assertEquals("copy", argumentArray[7]);
Assert.assertEquals("-q:v", argumentArray[8]);
Assert.assertEquals("0", argumentArray[9]);
Assert.assertEquals("-q:a", argumentArray[10]);
Assert.assertEquals("0", argumentArray[11]);
Assert.assertEquals("video.mp4", argumentArray[12]);
argumentArray = FFmpegKit.parseArguments(" -i file:///tmp/input.mp4 -vf \"subtitles=file:///tmp/subtitles.srt:force_style=\\\"FontSize=16,PrimaryColour=&HFFFFFF&\\\"\" -vcodec libx264 -acodec copy -q:v 0 -q:a 0 video.mp4");
Assert.assertNotNull(argumentArray);
Assert.assertEquals(13, argumentArray.length);
Assert.assertEquals("-i", argumentArray[0]);
Assert.assertEquals("file:///tmp/input.mp4", argumentArray[1]);
Assert.assertEquals("-vf", argumentArray[2]);
Assert.assertEquals("subtitles=file:///tmp/subtitles.srt:force_style=\\\"FontSize=16,PrimaryColour=&HFFFFFF&\\\"", argumentArray[3]);
Assert.assertEquals("-vcodec", argumentArray[4]);
Assert.assertEquals("libx264", argumentArray[5]);
Assert.assertEquals("-acodec", argumentArray[6]);
Assert.assertEquals("copy", argumentArray[7]);
Assert.assertEquals("-q:v", argumentArray[8]);
Assert.assertEquals("0", argumentArray[9]);
Assert.assertEquals("-q:a", argumentArray[10]);
Assert.assertEquals("0", argumentArray[11]);
Assert.assertEquals("video.mp4", argumentArray[12]);
}
@Test
public void argumentsToString() {
Assert.assertEquals("null", argumentsToString(null));
Assert.assertEquals("-i input.mp4 -vf filter -c:v mpeg4 output.mp4", argumentsToString(new String[]{"-i", "input.mp4", "-vf", "filter", "-c:v", "mpeg4", "output.mp4"}));
}
public String argumentsToString(final String[] arguments) {
return FFmpegKit.argumentsToString(arguments);
}
private void assertMediaInput(MediaInformation mediaInformation, String format, String filename) {
Assert.assertEquals(format, mediaInformation.getFormat());
Assert.assertEquals(filename, mediaInformation.getFilename());
}
private void assertMediaDuration(MediaInformation mediaInformation, String duration, String startTime, String bitrate) {
Assert.assertEquals(duration, mediaInformation.getDuration());
Assert.assertEquals(startTime, mediaInformation.getStartTime());
Assert.assertEquals(bitrate, mediaInformation.getBitrate());
}
private void assertTag(MediaInformation mediaInformation, String expectedKey, String expectedValue) {
JSONObject tags = mediaInformation.getTags();
Assert.assertNotNull(tags);
try {
String value = tags.getString(expectedKey);
Assert.assertEquals(expectedValue, value);
} catch (JSONException e) {
e.printStackTrace();
Assert.fail(expectedKey + " not found");
}
}
private void assertStreamTag(StreamInformation streamInformation, String expectedKey, String expectedValue) {
JSONObject tags = streamInformation.getTags();
Assert.assertNotNull(tags);
try {
String value = tags.getString(expectedKey);
Assert.assertEquals(expectedValue, value);
} catch (JSONException e) {
e.printStackTrace();
Assert.fail(expectedKey + " not found");
}
}
private void assertStream(StreamInformation streamInformation, Long index, String type, String codec, String fullCodec, String bitrate) {
Assert.assertEquals(index, streamInformation.getIndex());
Assert.assertEquals(type, streamInformation.getType());
Assert.assertEquals(codec, streamInformation.getCodec());
Assert.assertEquals(fullCodec, streamInformation.getFullCodec());
Assert.assertEquals(bitrate, streamInformation.getBitrate());
}
private void assertAudioStream(StreamInformation streamInformation, Long index, String codec, String fullCodec, String sampleRate, String channelLayout, String sampleFormat, String bitrate) {
Assert.assertEquals(index, streamInformation.getIndex());
Assert.assertEquals("audio", streamInformation.getType());
Assert.assertEquals(codec, streamInformation.getCodec());
Assert.assertEquals(fullCodec, streamInformation.getFullCodec());
Assert.assertEquals(sampleRate, streamInformation.getSampleRate());
Assert.assertEquals(channelLayout, streamInformation.getChannelLayout());
Assert.assertEquals(sampleFormat, streamInformation.getSampleFormat());
Assert.assertEquals(bitrate, streamInformation.getBitrate());
}
private void assertVideoStream(StreamInformation streamInformation, Long index, String codec, String fullCodec, String format, Long width, Long height, String sar, String dar, String bitrate, String averageFrameRate, String realFrameRate, String timeBase, String codecTimeBase) {
Assert.assertEquals(index, streamInformation.getIndex());
Assert.assertEquals("video", streamInformation.getType());
Assert.assertEquals(codec, streamInformation.getCodec());
Assert.assertEquals(fullCodec, streamInformation.getFullCodec());
Assert.assertEquals(format, streamInformation.getFormat());
Assert.assertEquals(width, streamInformation.getWidth());
Assert.assertEquals(height, streamInformation.getHeight());
Assert.assertEquals(sar, streamInformation.getSampleAspectRatio());
Assert.assertEquals(dar, streamInformation.getDisplayAspectRatio());
Assert.assertEquals(bitrate, streamInformation.getBitrate());
Assert.assertEquals(averageFrameRate, streamInformation.getAverageFrameRate());
Assert.assertEquals(realFrameRate, streamInformation.getRealFrameRate());
Assert.assertEquals(timeBase, streamInformation.getTimeBase());
Assert.assertEquals(codecTimeBase, streamInformation.getCodecTimeBase());
}
}

@ -0,0 +1,25 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

@ -0,0 +1,19 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

Binary file not shown.

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

183
android/gradlew vendored

@ -0,0 +1,183 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

103
android/gradlew.bat vendored

@ -0,0 +1,103 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

@ -0,0 +1,2 @@
/Application.mk
/Android.mk.tmp

@ -0,0 +1,104 @@
MY_LOCAL_PATH := $(call my-dir)
$(call import-add-path, $(MY_LOCAL_PATH))
MY_ARMV7 := false
MY_ARMV7_NEON := false
ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)
ifeq ("$(shell test -e $(MY_LOCAL_PATH)/../build/.armv7 && echo armv7)","armv7")
MY_ARMV7 := true
endif
ifeq ("$(shell test -e $(MY_LOCAL_PATH)/../build/.armv7neon && echo armv7neon)","armv7neon")
MY_ARMV7_NEON := true
endif
endif
ifeq ($(MY_ARMV7_NEON), true)
FFMPEG_INCLUDES := $(MY_LOCAL_PATH)/../../prebuilt/android-$(TARGET_ARCH)-neon/ffmpeg/include
else
FFMPEG_INCLUDES := $(MY_LOCAL_PATH)/../../prebuilt/android-$(TARGET_ARCH)/ffmpeg/include
endif
MY_ARM_MODE := arm
MY_ARM_NEON := false
LOCAL_PATH := $(MY_LOCAL_PATH)/../app/src/main/cpp
# DEFINE ARCH FLAGS
ifeq ($(TARGET_ARCH_ABI), armeabi-v7a)
MY_ARCH_FLAGS := ARM_V7A
MY_ARM_NEON := false
endif
ifeq ($(TARGET_ARCH_ABI), arm64-v8a)
MY_ARCH_FLAGS := ARM64_V8A
MY_ARM_NEON := true
endif
ifeq ($(TARGET_ARCH_ABI), x86)
MY_ARCH_FLAGS := X86
endif
ifeq ($(TARGET_ARCH_ABI), x86_64)
MY_ARCH_FLAGS := X86_64
endif
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := ffmpegkit_abidetect
LOCAL_SRC_FILES := ffmpegkit_abidetect.c
LOCAL_CFLAGS := -Wall -Wextra -Werror -Wno-unused-parameter -DFFMPEG_KIT_${MY_ARCH_FLAGS}
LOCAL_C_INCLUDES := $(FFMPEG_INCLUDES)
LOCAL_LDLIBS := -llog -lz -landroid
LOCAL_STATIC_LIBRARIES := cpu-features
LOCAL_ARM_NEON := ${MY_ARM_NEON}
include $(BUILD_SHARED_LIBRARY)
$(call import-module, cpu-features)
ifeq ($(TARGET_PLATFORM),android-16)
MY_SRC_FILES := ffmpegkit.c ffprobekit.c android_lts_support.c ffmpegkit_exception.c fftools_cmdutils.c fftools_ffmpeg.c fftools_ffprobe.c fftools_ffmpeg_opt.c fftools_ffmpeg_hw.c fftools_ffmpeg_filter.c
else ifeq ($(TARGET_PLATFORM),android-17)
MY_SRC_FILES := ffmpegkit.c ffprobekit.c android_lts_support.c ffmpegkit_exception.c fftools_cmdutils.c fftools_ffmpeg.c fftools_ffprobe.c fftools_ffmpeg_opt.c fftools_ffmpeg_hw.c fftools_ffmpeg_filter.c
else
MY_SRC_FILES := ffmpegkit.c ffprobekit.c ffmpegkit_exception.c fftools_cmdutils.c fftools_ffmpeg.c fftools_ffprobe.c fftools_ffmpeg_opt.c fftools_ffmpeg_hw.c fftools_ffmpeg_filter.c
endif
MY_CFLAGS := -Wall -Werror -Wno-unused-parameter -Wno-switch -Wno-sign-compare
MY_LDLIBS := -llog -lz -landroid
MY_BUILD_GENERIC_FFMPEG_KIT := true
ifeq ($(MY_ARMV7_NEON), true)
include $(CLEAR_VARS)
LOCAL_PATH := $(MY_LOCAL_PATH)/../app/src/main/cpp
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := ffmpegkit_armv7a_neon
LOCAL_SRC_FILES := $(MY_SRC_FILES)
LOCAL_CFLAGS := $(MY_CFLAGS)
LOCAL_LDLIBS := $(MY_LDLIBS)
LOCAL_SHARED_LIBRARIES := libavcodec_neon libavfilter_neon libswscale_neon libavformat_neon libavutil_neon libswresample_neon libavdevice_neon
ifeq ($(APP_STL), c++_shared)
LOCAL_SHARED_LIBRARIES += c++_shared # otherwise NDK will not add the library for packaging
endif
LOCAL_ARM_NEON := true
include $(BUILD_SHARED_LIBRARY)
$(call import-module, ffmpeg/neon)
ifneq ($(MY_ARMV7), true)
MY_BUILD_GENERIC_FFMPEG_KIT := false
endif
endif
ifeq ($(MY_BUILD_GENERIC_FFMPEG_KIT), true)
include $(CLEAR_VARS)
LOCAL_PATH := $(MY_LOCAL_PATH)/../app/src/main/cpp
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := ffmpegkit
LOCAL_SRC_FILES := $(MY_SRC_FILES)
LOCAL_CFLAGS := $(MY_CFLAGS)
LOCAL_LDLIBS := $(MY_LDLIBS)
LOCAL_SHARED_LIBRARIES := libavfilter libavformat libavcodec libavutil libswresample libavdevice libswscale
ifeq ($(APP_STL), c++_shared)
LOCAL_SHARED_LIBRARIES += c++_shared # otherwise NDK will not add the library for packaging
endif
LOCAL_ARM_NEON := ${MY_ARM_NEON}
include $(BUILD_SHARED_LIBRARY)
$(call import-module, ffmpeg)
endif

@ -0,0 +1,12 @@
ifeq ($(MY_ARMV7_NEON), true)
LOCAL_PATH := $(call my-dir)/../../../prebuilt/android-$(TARGET_ARCH)-neon/cpu-features/lib
else
LOCAL_PATH := $(call my-dir)/../../../prebuilt/android-$(TARGET_ARCH)/cpu-features/lib
endif
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := cpu-features
LOCAL_SRC_FILES := libndk_compat.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include/ndk_compat
include $(PREBUILT_STATIC_LIBRARY)

@ -0,0 +1,46 @@
LOCAL_PATH := $(call my-dir)/../../../prebuilt/android-$(TARGET_ARCH)/ffmpeg/lib
MY_ARM_MODE := arm
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libavcodec
LOCAL_SRC_FILES := libavcodec.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libavfilter
LOCAL_SRC_FILES := libavfilter.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libavdevice
LOCAL_SRC_FILES := libavdevice.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libavformat
LOCAL_SRC_FILES := libavformat.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libavutil
LOCAL_SRC_FILES := libavutil.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libswresample
LOCAL_SRC_FILES := libswresample.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_MODULE := libswscale
LOCAL_SRC_FILES := libswscale.so
include $(PREBUILT_SHARED_LIBRARY)

@ -0,0 +1,61 @@
LOCAL_PATH := $(call my-dir)/../../../../prebuilt/android-$(TARGET_ARCH)-neon/ffmpeg/lib
MY_ARM_MODE := arm
MY_ARM_NEON := true
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libavcodec_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libavcodec_neon.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libavfilter_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libavfilter_neon.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libavdevice_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libavdevice_neon.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libavformat_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libavformat_neon.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libavutil_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libavutil_neon.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libswresample_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libswresample_neon.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := $(MY_ARM_MODE)
LOCAL_ARM_NEON := ${MY_ARM_NEON}
LOCAL_MODULE := libswscale_neon
LOCAL_MODULE_FILENAME := $(LOCAL_MODULE)
LOCAL_SRC_FILES := libswscale_neon.so
include $(PREBUILT_SHARED_LIBRARY)

@ -0,0 +1,4 @@
include ':app'
include ':ffmpeg-kit'
project(':ffmpeg-kit').projectDir = new File('..')
rootProject.name='FFmpegKit'

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

439
ios.sh

@ -1,230 +1,54 @@
#!/bin/bash #!/bin/bash
export FFMPEG_KIT_BUILD_TYPE="ios" # CHECK IF XCODE IS INSTALLED
export BASEDIR="$(pwd)" if [ ! -x "$(command -v xcrun)" ]; then
echo -e "\n(*) xcrun command not found. Please check your Xcode installation\n"
source "${BASEDIR}"/scripts/common-${FFMPEG_KIT_BUILD_TYPE}.sh
# ENABLE ARCH
ENABLED_ARCHITECTURES=(0 0 1 1 0 1 1 1 0 1 1)
# ENABLE LIBRARIES
ENABLED_LIBRARIES=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
# USE 12.1 AS DEFAULT IOS_MIN_VERSION
export IOS_MIN_VERSION=12.1
RECONF_LIBRARIES=()
REBUILD_LIBRARIES=()
REDOWNLOAD_LIBRARIES=()
get_ffmpeg_kit_version() {
local FFMPEG_KIT_VERSION=$(grep 'const FFMPEG_KIT_VERSION' "${BASEDIR}"/ios/src/FFmpegKit.m | grep -Eo '\".*\"' | sed -e 's/\"//g')
if [[ -z ${FFMPEG_KIT_LTS_BUILD} ]]; then
echo "${FFMPEG_KIT_VERSION}"
else
echo "${FFMPEG_KIT_VERSION}.LTS"
fi
}
display_help() {
COMMAND=$(echo "$0" | sed -e 's/\.\///g')
echo -e "\n$COMMAND builds FFmpegKit for iOS platform. By default seven architectures (armv7, armv7s, arm64, arm64e, \
i386, x86-64 and x86-64-mac-catalyst) are built without any external libraries enabled. Options can be used to disable \
architectures and/or enable external libraries. Please note that GPL libraries (external libraries with GPL license) \
need --enable-gpl flag to be set explicitly. When compilation ends, library bundles are created under the prebuilt \
folder. By default framework bundles and universal fat binaries are created. If --xcframework option is provided then \
xcframework bundles are created.\n"
echo -e "Usage: ./$COMMAND [OPTION]...\n"
echo -e "Specify environment variables as VARIABLE=VALUE to override default build options.\n"
display_help_options " -x, --xcframework\t\tbuild xcframework bundles instead of framework bundles and universal libraries"
display_help_licensing
echo -e "Architectures:"
echo -e " --disable-armv7\t\tdo not build armv7 architecture [yes]"
echo -e " --disable-armv7s\t\tdo not build armv7s architecture [yes]"
echo -e " --disable-arm64\t\tdo not build arm64 architecture [yes]"
echo -e " --disable-arm64e\t\tdo not build arm64e architecture [yes]"
echo -e " --disable-i386\t\tdo not build i386 architecture [yes]"
echo -e " --disable-x86-64\t\tdo not build x86-64 architecture [yes]"
echo -e " --disable-x86-64-mac-catalyst\tdo not build x86-64-mac-catalyst architecture [yes]\n"
echo -e "Libraries:"
echo -e " --full\t\t\tenables all non-GPL external libraries"
echo -e " --enable-ios-audiotoolbox\tbuild with built-in Apple AudioToolbox support[no]"
echo -e " --enable-ios-avfoundation\tbuild with built-in Apple AVFoundation support[no]"
echo -e " --enable-ios-bzip2\t\tbuild with built-in bzip2 support[no]"
echo -e " --enable-ios-videotoolbox\tbuild with built-in Apple VideoToolbox support[no]"
echo -e " --enable-ios-zlib\t\tbuild with built-in zlib [no]"
echo -e " --enable-ios-libiconv\t\tbuild with built-in libiconv [no]"
display_help_common_libraries
display_help_gpl_libraries
display_help_advanced_options
}
enable_lts_build() {
export FFMPEG_KIT_LTS_BUILD="1"
# XCODE 7.3 HAS IOS SDK 9.3
export IOS_MIN_VERSION=9.3
}
# 1 - library index
# 2 - library name
# 3 - static library name
# 4 - library version
create_external_library_package() {
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then
# 1. CREATE INDIVIDUAL FRAMEWORKS
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
if [[ ${TARGET_ARCH} != "arm64e" ]]; then
local FRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/.tmp/ios-${TARGET_ARCH}/$2.framework
mkdir -p "${FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
local STATIC_LIBRARY_PATH=$(find "${BASEDIR}"/prebuilt/ios-${TARGET_ARCH} -name $3)
local CAPITAL_CASE_LIBRARY_NAME=$(to_capital_case "$2")
build_info_plist "${FRAMEWORK_PATH}/Info.plist" "$2" "com.arthenica.ffmpegkit.${CAPITAL_CASE_LIBRARY_NAME}" "$4" "$4"
cp "${STATIC_LIBRARY_PATH}" "${FRAMEWORK_PATH}/$2" 1>>"${BASEDIR}"/build.log 2>&1
fi
done
# 2. CREATE XCFRAMEWORKS
local XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/$2.xcframework
mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
BUILD_COMMAND="xcodebuild -create-xcframework "
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
if [[ ${TARGET_ARCH} != "arm64e" ]]; then
local FRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/.tmp/ios-${TARGET_ARCH}/$2.framework
BUILD_COMMAND+=" -framework ${FRAMEWORK_PATH}"
fi
done
BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}"
COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1)
echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1
echo "" 1>>"${BASEDIR}"/build.log 2>&1
if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then
RC=1
else
RC=0
fi
else
# 1. CREATE FAT LIBRARY
local FAT_LIBRARY_PATH=${BASEDIR}/prebuilt/ios-universal/$2-universal
mkdir -p "${FAT_LIBRARY_PATH}/lib" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
LIPO_COMMAND="${LIPO} -create"
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
LIPO_COMMAND+=" $(find "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH}" -name $3)"
done
LIPO_COMMAND+=" -output ${FAT_LIBRARY_PATH}/lib/$3"
RC=$(${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1)
if [[ ${RC} -eq 0 ]]; then
# 2. CREATE FRAMEWORK
RC=$(create_static_framework "$2" "$3" "$4")
if [[ ${RC} -eq 0 ]]; then
# 3. COPY LICENSES
if [[ ${LIBRARY_LIBTHEORA} == "$1" ]]; then
license_directories=("${BASEDIR}/prebuilt/ios-universal/libtheora-universal" "${BASEDIR}/prebuilt/ios-universal/libtheoraenc-universal" "${BASEDIR}/prebuilt/ios-universal/libtheoradec-universal" "${BASEDIR}/prebuilt/ios-framework/libtheora.framework" "${BASEDIR}/prebuilt/ios-framework/libtheoraenc.framework" "${BASEDIR}/prebuilt/ios-framework/libtheoradec.framework")
elif [[ ${LIBRARY_LIBVORBIS} == "$1" ]]; then
license_directories=("${BASEDIR}/prebuilt/ios-universal/libvorbisfile-universal" "${BASEDIR}/prebuilt/ios-universal/libvorbisenc-universal" "${BASEDIR}/prebuilt/ios-universal/libvorbis-universal" "${BASEDIR}/prebuilt/ios-framework/libvorbisfile.framework" "${BASEDIR}/prebuilt/ios-framework/libvorbisenc.framework" "${BASEDIR}/prebuilt/ios-framework/libvorbis.framework")
elif [[ ${LIBRARY_LIBWEBP} == "$1" ]]; then
license_directories=("${BASEDIR}/prebuilt/ios-universal/libwebpmux-universal" "${BASEDIR}/prebuilt/ios-universal/libwebpdemux-universal" "${BASEDIR}/prebuilt/ios-universal/libwebp-universal" "${BASEDIR}/prebuilt/ios-framework/libwebpmux.framework" "${BASEDIR}/prebuilt/ios-framework/libwebpdemux.framework" "${BASEDIR}/prebuilt/ios-framework/libwebp.framework")
elif [[ ${LIBRARY_OPENCOREAMR} == "$1" ]]; then
license_directories=("${BASEDIR}/prebuilt/ios-universal/libopencore-amrnb-universal" "${BASEDIR}/prebuilt/ios-framework/libopencore-amrnb.framework")
elif [[ ${LIBRARY_NETTLE} == "$1" ]]; then
license_directories=("${BASEDIR}/prebuilt/ios-universal/libnettle-universal" "${BASEDIR}/prebuilt/ios-universal/libhogweed-universal" "${BASEDIR}/prebuilt/ios-framework/libnettle.framework" "${BASEDIR}/prebuilt/ios-framework/libhogweed.framework")
else
license_directories=("${BASEDIR}/prebuilt/ios-universal/$2-universal" "${BASEDIR}/prebuilt/ios-framework/$2.framework")
fi
RC=$(copy_external_library_license "$1" "${license_directories[@]}")
fi
fi
fi
echo "${RC}"
}
# 1 - library index
# 2 - output path
copy_external_library_license() {
output_path_array="$2"
for output_path in "${output_path_array[@]}"
do
$(cp $(get_external_library_license_path "$1") "${output_path}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1)
if [ $? -ne 0 ]; then
echo 1
return
fi
done;
echo 0
}
get_external_library_version() {
local library_version=$(grep Version "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/pkgconfig/"$1".pc 2>>"${BASEDIR}"/build.log | sed 's/Version://g;s/\ //g')
echo "${library_version}"
}
# CHECKING IF XCODE IS INSTALLED
if ! [ -x "$(command -v xcrun)" ]; then
echo -e "\n(*) xcrun command not found. Please check your Xcode installation.\n"
exit 1 exit 1
fi fi
# LOAD INITIAL SETTINGS
export BASEDIR="$(pwd)"
export FFMPEG_KIT_BUILD_TYPE="ios"
source "${BASEDIR}"/scripts/variable.sh
source "${BASEDIR}"/scripts/function-${FFMPEG_KIT_BUILD_TYPE}.sh
# SET DEFAULTS SETTINGS
enable_default_ios_architectures
enable_main_build
# SELECT XCODE VERSION USED FOR BUILDING # SELECT XCODE VERSION USED FOR BUILDING
XCODE_FOR_FFMPEG_KIT=source ~/.xcode.for.ffmpeg.kit.sh XCODE_FOR_FFMPEG_KIT=$(ls ~/.xcode.for.ffmpeg.kit.sh)
if [[ -f ${XCODE_FOR_FFMPEG_KIT} ]]; then if [[ -f ${XCODE_FOR_FFMPEG_KIT} ]]; then
source "${XCODE_FOR_FFMPEG_KIT}" 1>>"${BASEDIR}"/build.log 2>&1 source "${XCODE_FOR_FFMPEG_KIT}" 1>>"${BASEDIR}"/build.log 2>&1
fi fi
# DETECT IOS SDK VERSION
DETECTED_IOS_SDK_VERSION="$(xcrun --sdk iphoneos --show-sdk-version)" DETECTED_IOS_SDK_VERSION="$(xcrun --sdk iphoneos --show-sdk-version)"
echo -e "INFO: Using SDK ${DETECTED_IOS_SDK_VERSION} by Xcode provided at $(xcode-select -p)\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "INFO: Using SDK ${DETECTED_IOS_SDK_VERSION} by Xcode provided at $(xcode-select -p)\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "\nINFO: Build options: $*\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "INFO: Build options: $*\n" 1>>"${BASEDIR}"/build.log 2>&1
if [[ -n ${FFMPEG_KIT_LTS_BUILD} ]] && [[ "${DETECTED_IOS_SDK_VERSION}" != "${IOS_MIN_VERSION}" ]]; then
echo -e "\n(*) LTS packages should be built using SDK ${IOS_MIN_VERSION} but current configuration uses SDK ${DETECTED_IOS_SDK_VERSION}\n"
if [[ -z ${BUILD_FORCE} ]]; then
exit 1
fi
fi
# SET DEFAULT BUILD OPTIONS
GPL_ENABLED="no" GPL_ENABLED="no"
DISPLAY_HELP="" DISPLAY_HELP=""
BUILD_TYPE_ID="" BUILD_TYPE_ID=""
BUILD_LTS=""
BUILD_FULL="" BUILD_FULL=""
FFMPEG_KIT_XCF_BUILD="" FFMPEG_KIT_XCF_BUILD=""
BUILD_FORCE="" BUILD_FORCE=""
BUILD_VERSION=$(git describe --tags 2>>"${BASEDIR}"/build.log) BUILD_VERSION=$(git describe --tags --always 2>>"${BASEDIR}"/build.log)
if [[ -z ${BUILD_VERSION} ]]; then
echo -e "\n(*): Can not run git commands in this folder. See build.log.\n"
exit 1
fi
# PROCESS LTS BUILD OPTION FIRST AND SET BUILD TYPE: MAIN OR LTS
for argument in "$@"; do
if [[ "$argument" == "-l" ]] || [[ "$argument" == "--lts" ]]; then
enable_lts_build
BUILD_TYPE_ID+="LTS "
fi
done
# PROCESS BUILD OPTIONS
while [ ! $# -eq 0 ]; do while [ ! $# -eq 0 ]; do
case $1 in case $1 in
-h | --help) -h | --help)
@ -253,14 +77,12 @@ while [ ! $# -eq 0 ]; do
-s | --speed) -s | --speed)
optimize_for_speed optimize_for_speed
;; ;;
-l | --lts) -l | --lts) ;;
BUILD_LTS="1"
;;
-x | --xcframework) -x | --xcframework)
FFMPEG_KIT_XCF_BUILD="1" FFMPEG_KIT_XCF_BUILD="1"
;; ;;
-f | --force) -f | --force)
BUILD_FORCE="1" export BUILD_FORCE="1"
;; ;;
--reconf-*) --reconf-*)
CONF_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g') CONF_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
@ -272,7 +94,7 @@ while [ ! $# -eq 0 ]; do
rebuild_library "${BUILD_LIBRARY}" rebuild_library "${BUILD_LIBRARY}"
;; ;;
--redownload-*) --redownload-*)
DOWNLOAD_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g') DOWNLOAD_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
redownload_library "${DOWNLOAD_LIBRARY}" redownload_library "${DOWNLOAD_LIBRARY}"
@ -300,80 +122,63 @@ while [ ! $# -eq 0 ]; do
shift shift
done done
if [[ -z ${BUILD_VERSION} ]]; then # VALIDATE THAT LTS RELEASES ARE BUILT USING THE CORRECT VERSION
echo -e "\nerror: Can not run git commands in this folder. See build.log.\n" if [[ -n ${FFMPEG_KIT_LTS_BUILD} ]] && [[ "${DETECTED_IOS_SDK_VERSION}" != "${IOS_MIN_VERSION}" ]]; then
exit 1 if [[ -z ${BUILD_FORCE} ]]; then
fi echo -e "\n(*) LTS packages should be built using SDK ${IOS_MIN_VERSION} but current configuration uses SDK ${DETECTED_IOS_SDK_VERSION}\n"
exit 1
# DETECT BUILD TYPE fi
if [[ -n ${BUILD_LTS} ]]; then
enable_lts_build
BUILD_TYPE_ID+="LTS "
fi
# HELP DISPLAYED AFTER SETTING LTS FLAG
if [[ -n ${DISPLAY_HELP} ]]; then
display_help
exit 0
fi fi
# PROCESS FULL FLAG # PROCESS FULL OPTION AS LAST OPTION
if [[ -n ${BUILD_FULL} ]]; then if [[ -n ${BUILD_FULL} ]]; then
for library in {0..60}; do for library in {0..57}; do
if [ ${GPL_ENABLED} == "yes" ]; then if [ ${GPL_ENABLED} == "yes" ]; then
enable_library "$(get_library_name $library)" enable_library "$(get_library_name $library)" 1
else else
if [[ $library -ne $LIBRARY_X264 ]] && [[ $library -ne $LIBRARY_XVIDCORE ]] && [[ $library -ne $LIBRARY_X265 ]] && [[ $library -ne $LIBRARY_LIBVIDSTAB ]] && [[ $library -ne $LIBRARY_RUBBERBAND ]]; then if [[ $(is_gpl_licensed $library) -eq 1 ]]; then
enable_library "$(get_library_name $library)" enable_library "$(get_library_name $library)" 1
fi fi
fi fi
done done
fi fi
# DISABLE 32-bit architectures on newer IOS versions # IF HELP DISPLAYED EXIT
if [[ ${DETECTED_IOS_SDK_VERSION} == 11* ]] || [[ ${DETECTED_IOS_SDK_VERSION} == 12* ]] || [[ ${DETECTED_IOS_SDK_VERSION} == 13* ]]; then if [[ -n ${DISPLAY_HELP} ]]; then
if [[ -z ${BUILD_FORCE} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARMV7}]} -eq 1 ]]; then display_help
echo -e "INFO: Disabled armv7 architecture which is not supported on SDK ${DETECTED_IOS_SDK_VERSION}\n" 1>>"${BASEDIR}"/build.log 2>&1 exit 0
disable_arch "armv7"
fi
if [[ -z ${BUILD_FORCE} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARMV7S}]} -eq 1 ]]; then
echo -e "INFO: Disabled armv7s architecture which is not supported on SDK ${DETECTED_IOS_SDK_VERSION}\n" 1>>"${BASEDIR}"/build.log 2>&1
disable_arch "armv7s"
fi
if [[ -z ${BUILD_FORCE} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_I386}]} -eq 1 ]]; then
echo -e "INFO: Disabled i386 architecture which is not supported on SDK ${DETECTED_IOS_SDK_VERSION}\n" 1>>"${BASEDIR}"/build.log 2>&1
disable_arch "i386"
fi
# DISABLE arm64e architecture on older IOS versions
elif [[ ${DETECTED_IOS_SDK_VERSION} != 10* ]]; then
if [[ -z ${BUILD_FORCE} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARM64E}]} -eq 1 ]]; then
echo -e "INFO: Disabled arm64e architecture which is not supported on SDK ${DETECTED_IOS_SDK_VERSION}\n" 1>>"${BASEDIR}"/build.log 2>&1
disable_arch "arm64e"
fi
fi fi
# DISABLE x86-64-mac-catalyst architecture on IOS versions lower than 13 # DISABLE NOT SUPPORTED ARCHITECTURES
if [[ ${DETECTED_IOS_SDK_VERSION} != 13* ]] && [[ -z ${BUILD_FORCE} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_X86_64_MAC_CATALYST}]} -eq 1 ]]; then disable_architecture_not_supported_on_detected_sdk_version "${ARCH_ARMV7}" "${DETECTED_IOS_SDK_VERSION}"
echo -e "INFO: Disabled x86-64-mac-catalyst architecture which is not supported on SDK ${DETECTED_IOS_SDK_VERSION}\n" 1>>"${BASEDIR}"/build.log 2>&1 disable_architecture_not_supported_on_detected_sdk_version "${ARCH_ARMV7S}" "${DETECTED_IOS_SDK_VERSION}"
disable_arch "x86-64-mac-catalyst" disable_architecture_not_supported_on_detected_sdk_version "${ARCH_I386}" "${DETECTED_IOS_SDK_VERSION}"
fi disable_architecture_not_supported_on_detected_sdk_version "${ARCH_ARM64E}" "${DETECTED_IOS_SDK_VERSION}"
disable_architecture_not_supported_on_detected_sdk_version "${ARCH_X86_64_MAC_CATALYST}" "${DETECTED_IOS_SDK_VERSION}"
# CHECK SOME RULES FOR .xcframework BUNDLES
# DISABLE x86-64-mac-catalyst when x86-64 is enabled in xcf bundles # 1. DISABLE x86-64-mac-catalyst WHEN x86-64 IS ENABLED IN xcframework BUNDLES
if [[ -z ${FFMPEG_KIT_XCF_BUILD} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_X86_64}]} -eq 1 ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_X86_64_MAC_CATALYST}]} -eq 1 ]]; then if [[ -z ${FFMPEG_KIT_XCF_BUILD} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_X86_64}]} -eq 1 ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_X86_64_MAC_CATALYST}]} -eq 1 ]]; then
echo -e "INFO: Disabled x86-64-mac-catalyst architecture which can not co-exist with x86-64 in a framework bundle / universal fat library.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "INFO: Disabled x86-64-mac-catalyst architecture which can not co-exist with x86-64 in a framework bundle / universal fat library.\n" 1>>"${BASEDIR}"/build.log 2>&1
disable_arch "x86-64-mac-catalyst" disable_arch "x86-64-mac-catalyst"
fi fi
# DISABLE arm64e when arm64 is enabled in xcf bundles # 2. DISABLE arm64e WHEN arm64 IS ENABLED IN xcframework BUNDLES
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARM64E}]} -eq 1 ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARM64}]} -eq 1 ]]; then if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARM64E}]} -eq 1 ]] && [[ ${ENABLED_ARCHITECTURES[${ARCH_ARM64}]} -eq 1 ]]; then
echo -e "INFO: Disabled arm64e architecture which can not co-exist with arm64 in an xcframework bundle.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "INFO: Disabled arm64e architecture which can not co-exist with arm64 in an xcframework bundle.\n" 1>>"${BASEDIR}"/build.log 2>&1
disable_arch "arm64e" disable_arch "arm64e"
fi fi
# 3. DO NOT ALLOW --lts AND --xcframework OPTIONS TOGETHER
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]] && [[ -n ${FFMPEG_KIT_LTS_BUILD} ]]; then
echo -e "\n(*) LTS packages does not support xcframework bundles.\n"
exit 1
fi
echo -e "\nBuilding ffmpeg-kit ${BUILD_TYPE_ID}static library for iOS\n" echo -e "\nBuilding ffmpeg-kit ${BUILD_TYPE_ID}static library for iOS\n"
echo -e -n "INFO: Building ffmpeg-kit ${BUILD_VERSION} ${BUILD_TYPE_ID}for iOS: " 1>>"${BASEDIR}"/build.log 2>&1 echo -e -n "INFO: Building ffmpeg-kit ${BUILD_VERSION} ${BUILD_TYPE_ID}for iOS: " 1>>"${BASEDIR}"/build.log 2>&1
echo -e "$(date)" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "$(date)\n" 1>>"${BASEDIR}"/build.log 2>&1
# PRINT BUILD SUMMARY # PRINT BUILD SUMMARY
print_enabled_architectures print_enabled_architectures
@ -382,7 +187,7 @@ print_reconfigure_requested_libraries
print_rebuild_requested_libraries print_rebuild_requested_libraries
print_redownload_requested_libraries print_redownload_requested_libraries
# CHECK GPL FLAG AND DOWNLOAD LIBRARIES # VALIDATE GPL FLAGS
for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVIDSTAB,$LIBRARY_RUBBERBAND}; do for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVIDSTAB,$LIBRARY_RUBBERBAND}; do
if [[ ${ENABLED_LIBRARIES[$gpl_library]} -eq 1 ]]; then if [[ ${ENABLED_LIBRARIES[$gpl_library]} -eq 1 ]]; then
library_name=$(get_library_name ${gpl_library}) library_name=$(get_library_name ${gpl_library})
@ -391,20 +196,20 @@ for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVI
echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n"
echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" 1>>"${BASEDIR}"/build.log 2>&1
exit 1 exit 1
else
DOWNLOAD_RESULT=$(download_gpl_library_source "${library_name}")
if [[ ${DOWNLOAD_RESULT} -ne 0 ]]; then
echo -e "\n(*) Failed to download GPL library ${library_name} source. Please check build.log file for details. If the problem persists refer to offline building instructions.\n"
echo -e "\n(*) Failed to download GPL library ${library_name} source.\n" 1>>"${BASEDIR}"/build.log 2>&1
exit 1
fi
fi fi
fi fi
done done
echo -n -e "\nDownloading sources: "
echo -e "INFO: Downloading source code of ffmpeg and enabled external libraries.\n" 1>>"${BASEDIR}"/build.log 2>&1
# DOWNLOAD LIBRARY SOURCES
downloaded_enabled_library_sources "${ENABLED_LIBRARIES[@]}"
# THIS WILL SAVE ARCHITECTURES TO BUILD
TARGET_ARCH_LIST=() TARGET_ARCH_LIST=()
# BUILD ALL ENABLED ARCHITECTURES # BUILD ENABLED LIBRARIES ON ENABLED ARCHITECTURES
for run_arch in {0..10}; do for run_arch in {0..10}; do
if [[ ${ENABLED_ARCHITECTURES[$run_arch]} -eq 1 ]]; then if [[ ${ENABLED_ARCHITECTURES[$run_arch]} -eq 1 ]]; then
export ARCH=$(get_arch_name $run_arch) export ARCH=$(get_arch_name $run_arch)
@ -414,6 +219,7 @@ for run_arch in {0..10}; do
export LIPO="$(xcrun --sdk "$(get_sdk_name)" -f lipo)" export LIPO="$(xcrun --sdk "$(get_sdk_name)" -f lipo)"
# EXECUTE MAIN BUILD SCRIPT
. "${BASEDIR}"/scripts/main-ios.sh "${ENABLED_LIBRARIES[@]}" . "${BASEDIR}"/scripts/main-ios.sh "${ENABLED_LIBRARIES[@]}"
case ${ARCH} in case ${ARCH} in
x86-64) x86-64)
@ -429,7 +235,7 @@ for run_arch in {0..10}; do
TARGET_ARCH_LIST+=("${TARGET_ARCH}") TARGET_ARCH_LIST+=("${TARGET_ARCH}")
# CLEAR FLAGS # CLEAR FLAGS
for library in {0..60}; do for library in {0..57}; do
library_name=$(get_library_name ${library}) library_name=$(get_library_name ${library})
unset "$(echo "OK_${library_name}" | sed "s/\-/\_/g")" unset "$(echo "OK_${library_name}" | sed "s/\-/\_/g")"
unset "$(echo "DEPENDENCY_REBUILT_${library_name}" | sed "s/\-/\_/g")" unset "$(echo "DEPENDENCY_REBUILT_${library_name}" | sed "s/\-/\_/g")"
@ -439,11 +245,13 @@ done
FFMPEG_LIBS="libavcodec libavdevice libavfilter libavformat libavutil libswresample libswscale" FFMPEG_LIBS="libavcodec libavdevice libavfilter libavformat libavutil libswresample libswscale"
# BUILD STATIC LIBRARIES
BUILD_LIBRARY_EXTENSION="a" BUILD_LIBRARY_EXTENSION="a"
# BUILD FFMPEG-KIT
if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
# BUILDING PACKAGES # INITIALIZE TARGET FOLDERS
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then
echo -e -n "\n\nCreating xcframeworks under prebuilt: " echo -e -n "\n\nCreating xcframeworks under prebuilt: "
@ -458,12 +266,16 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
mkdir -p "${BASEDIR}/prebuilt/ios-framework" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${BASEDIR}/prebuilt/ios-framework" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
fi fi
# 1. EXTERNAL LIBRARIES # CREATE ENABLED LIBRARY PACKAGES. IT IS EITHER
for library in {0..6} {8..37} {39..44}; do # .framework and fat/universal library
# OR
# .xcframework
for library in {0..57}; do
if [[ ${ENABLED_LIBRARIES[$library]} -eq 1 ]]; then if [[ ${ENABLED_LIBRARIES[$library]} -eq 1 ]]; then
library_name=$(get_library_name ${library}) library_name=$(get_library_name ${library})
package_config_file_name=$(get_package_config_file_name ${library}) package_config_file_name=$(get_package_config_file_name ${library})
# EACH ENABLED LIBRARY HAS TO HAVE A .pc FILE AND A VERSION
library_version=$(get_external_library_version "${package_config_file_name}") library_version=$(get_external_library_version "${package_config_file_name}")
if [[ -z ${library_version} ]]; then if [[ -z ${library_version} ]]; then
echo -e "Failed to detect version for ${library_name} from ${package_config_file_name}.pc\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "Failed to detect version for ${library_name} from ${package_config_file_name}.pc\n" 1>>"${BASEDIR}"/build.log 2>&1
@ -473,6 +285,7 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
echo -e "Creating external library package for ${library_name}\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "Creating external library package for ${library_name}\n" 1>>"${BASEDIR}"/build.log 2>&1
# SOME CUSTOM CODE TO HANDLE LIBRARIES THAT PRODUCE MULTIPLE LIBRARY FILES
if [[ ${LIBRARY_LIBTHEORA} == "$library" ]]; then if [[ ${LIBRARY_LIBTHEORA} == "$library" ]]; then
LIBRARY_CREATED=$(create_external_library_package $library "libtheora" "libtheora.a" "${library_version}") LIBRARY_CREATED=$(create_external_library_package $library "libtheora" "libtheora.a" "${library_version}")
@ -557,6 +370,7 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
else else
# LIBRARIES WHICH HAVE ONLY ONE LIBRARY FILE ARE CREATED HERE
library_name=$(get_library_name $((library))) library_name=$(get_library_name $((library)))
static_archive_name=$(get_static_archive_name $((library))) static_archive_name=$(get_static_archive_name $((library)))
LIBRARY_CREATED=$(create_external_library_package $library "$library_name" "$static_archive_name" "${library_version}") LIBRARY_CREATED=$(create_external_library_package $library "$library_name" "$static_archive_name" "${library_version}")
@ -570,12 +384,15 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
fi fi
done done
# 2. FFMPEG & FFMPEG KIT # CREATE FFMPEG & FFMPEG KIT PACKAGES
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then
# FFMPEG # CREATE .xcframework BUNDLE IF ENABLED
# CREATE FFMPEG
for FFMPEG_LIB in ${FFMPEG_LIBS}; do for FFMPEG_LIB in ${FFMPEG_LIBS}; do
# INITIALIZE FFMPEG FRAMEWORK DIRECTORY
XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/${FFMPEG_LIB}.xcframework XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/${FFMPEG_LIB}.xcframework
mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
@ -585,33 +402,33 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
# arm64e NOT INCLUDED IN .xcframework BUNDLES
if [[ ${TARGET_ARCH} != "arm64e" ]]; then if [[ ${TARGET_ARCH} != "arm64e" ]]; then
FFMPEG_LIB_UPPERCASE=$(echo "${FFMPEG_LIB}" | tr '[a-z]' '[A-Z]') FFMPEG_LIB_UPPERCASE=$(echo "${FFMPEG_LIB}" | tr '[a-z]' '[A-Z]')
FFMPEG_LIB_CAPITALCASE=$(to_capital_case "${FFMPEG_LIB}") FFMPEG_LIB_CAPITALCASE=$(to_capital_case "${FFMPEG_LIB}")
# EXTRACT FFMPEG VERSION
FFMPEG_LIB_MAJOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR" "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR//g;s/\ //g") FFMPEG_LIB_MAJOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR" "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR//g;s/\ //g")
FFMPEG_LIB_MINOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR" "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR//g;s/\ //g") FFMPEG_LIB_MINOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR" "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR//g;s/\ //g")
FFMPEG_LIB_MICRO=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO" "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO//g;s/\ //g") FFMPEG_LIB_MICRO=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO" "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO//g;s/\ //g")
FFMPEG_LIB_VERSION="${FFMPEG_LIB_MAJOR}.${FFMPEG_LIB_MINOR}.${FFMPEG_LIB_MICRO}" FFMPEG_LIB_VERSION="${FFMPEG_LIB_MAJOR}.${FFMPEG_LIB_MINOR}.${FFMPEG_LIB_MICRO}"
# INITIALIZE SUB-FRAMEWORK DIRECTORY
FFMPEG_LIB_FRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/.tmp/ios-${TARGET_ARCH}/${FFMPEG_LIB}.framework FFMPEG_LIB_FRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/.tmp/ios-${TARGET_ARCH}/${FFMPEG_LIB}.framework
rm -rf "${FFMPEG_LIB_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 rm -rf "${FFMPEG_LIB_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_LIB_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${FFMPEG_LIB_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/* ${FFMPEG_LIB_FRAMEWORK_PATH}/Headers 1>>"${BASEDIR}"/build.log 2>&1 cp -r "${BASEDIR}"/prebuilt/ios-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/* ${FFMPEG_LIB_FRAMEWORK_PATH}/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_LIB_FRAMEWORK_PATH}/${FFMPEG_LIB}" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_LIB_FRAMEWORK_PATH}/${FFMPEG_LIB}" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES # COPY THE LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then if [ ${GPL_ENABLED} == "yes" ]; then
# GPLv3.0
cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
else else
# LGPLv3.0
cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
fi fi
@ -624,12 +441,12 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}" BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}"
# EXECUTE CREATE FRAMEWORK COMMAND
COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1) COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1)
echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1 echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1
echo "" 1>>"${BASEDIR}"/build.log 2>&1 echo "" 1>>"${BASEDIR}"/build.log 2>&1
# DO NOT ALLOW EMPTY FRAMEWORKS
if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then
echo -e "failed\n" echo -e "failed\n"
exit 1 exit 1
@ -639,7 +456,9 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
done done
# FFMPEG KIT # CREATE FFMPEG
# INITIALIZE FFMPEG KIT FRAMEWORK DIRECTORY
XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/ffmpegkit.xcframework XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/ios-xcframework/ffmpegkit.xcframework
mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
@ -647,16 +466,21 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
# arm64e NOT INCLUDED IN .xcframework BUNDLES
if [[ ${TARGET_ARCH} != "arm64e" ]]; then if [[ ${TARGET_ARCH} != "arm64e" ]]; then
# INITIALIZE SUB-FRAMEWORK DIRECTORY
FFMPEG_KIT_FRAMEWORK_PATH="${BASEDIR}/prebuilt/ios-xcframework/.tmp/ios-${TARGET_ARCH}/ffmpegkit.framework" FFMPEG_KIT_FRAMEWORK_PATH="${BASEDIR}/prebuilt/ios-xcframework/.tmp/ios-${TARGET_ARCH}/ffmpegkit.framework"
rm -rf "${FFMPEG_KIT_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 rm -rf "${FFMPEG_KIT_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
build_modulemap "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules/module.modulemap" build_modulemap "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules/module.modulemap"
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH}"/ffmpeg-kit/include/* "${FFMPEG_KIT_FRAMEWORK_PATH}"/Headers 1>>"${BASEDIR}"/build.log 2>&1 cp -r "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH}"/ffmpeg-kit/include/* "${FFMPEG_KIT_FRAMEWORK_PATH}"/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg-kit/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_KIT_FRAMEWORK_PATH}/ffmpegkit" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}/prebuilt/ios-${TARGET_ARCH}/ffmpeg-kit/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_KIT_FRAMEWORK_PATH}/ffmpegkit" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES # COPY THE LICENSES
@ -667,33 +491,37 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
fi fi
BUILD_COMMAND+=" -framework ${FFMPEG_KIT_FRAMEWORK_PATH}" BUILD_COMMAND+=" -framework ${FFMPEG_KIT_FRAMEWORK_PATH}"
fi fi
done; done
BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}" BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}"
# EXECUTE CREATE FRAMEWORK COMMAND
COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1) COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1)
echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1 echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1
echo "" 1>>"${BASEDIR}"/build.log 2>&1 echo "" 1>>"${BASEDIR}"/build.log 2>&1
# DO NOT ALLOW EMPTY FRAMEWORKS
if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then
echo -e "failed\n" echo -e "failed\n"
exit 1 exit 1
fi fi
echo -e "Created ffmpegkit xcframework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "Created ffmpegkit xcframework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "ok\n" echo -e "ok\n"
else else
# CREATE .framework AND FAT/UNIVERSAL LIBRARY IF ENABLED
# CREATE FFMPEG
# INITIALIZE UNIVERSAL LIBRARY DIRECTORY
FFMPEG_UNIVERSAL="${BASEDIR}/prebuilt/ios-universal/ffmpeg-universal" FFMPEG_UNIVERSAL="${BASEDIR}/prebuilt/ios-universal/ffmpeg-universal"
mkdir -p "${FFMPEG_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${FFMPEG_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${FFMPEG_UNIVERSAL}/lib" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${FFMPEG_UNIVERSAL}/lib" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/ffmpeg/include/* ${FFMPEG_UNIVERSAL}/include 1>>"${BASEDIR}"/build.log 2>&1 cp -r "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/ffmpeg/include/* ${FFMPEG_UNIVERSAL}/include 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/ffmpeg/include/config.h "${FFMPEG_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/ffmpeg/include/config.h "${FFMPEG_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1
@ -706,8 +534,8 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
LIPO_COMMAND+=" -output ${FFMPEG_UNIVERSAL}/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" LIPO_COMMAND+=" -output ${FFMPEG_UNIVERSAL}/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}"
# EXECUTE CREATE UNIVERSAL LIBRARY COMMAND
${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1 ${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo -e "failed\n" echo -e "failed\n"
exit 1 exit 1
@ -716,28 +544,27 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
FFMPEG_LIB_UPPERCASE=$(echo "${FFMPEG_LIB}" | tr '[a-z]' '[A-Z]') FFMPEG_LIB_UPPERCASE=$(echo "${FFMPEG_LIB}" | tr '[a-z]' '[A-Z]')
FFMPEG_LIB_CAPITALCASE=$(to_capital_case "${FFMPEG_LIB}") FFMPEG_LIB_CAPITALCASE=$(to_capital_case "${FFMPEG_LIB}")
# EXTRACT FFMPEG VERSION
FFMPEG_LIB_MAJOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR//g;s/\ //g") FFMPEG_LIB_MAJOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR//g;s/\ //g")
FFMPEG_LIB_MINOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR//g;s/\ //g") FFMPEG_LIB_MINOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR//g;s/\ //g")
FFMPEG_LIB_MICRO=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO//g;s/\ //g") FFMPEG_LIB_MICRO=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO//g;s/\ //g")
FFMPEG_LIB_VERSION="${FFMPEG_LIB_MAJOR}.${FFMPEG_LIB_MINOR}.${FFMPEG_LIB_MICRO}" FFMPEG_LIB_VERSION="${FFMPEG_LIB_MAJOR}.${FFMPEG_LIB_MINOR}.${FFMPEG_LIB_MICRO}"
# INITIALIZE FRAMEWORK DIRECTORY
FFMPEG_LIB_FRAMEWORK_PATH="${BASEDIR}/prebuilt/ios-framework/${FFMPEG_LIB}.framework" FFMPEG_LIB_FRAMEWORK_PATH="${BASEDIR}/prebuilt/ios-framework/${FFMPEG_LIB}.framework"
rm -rf "${FFMPEG_LIB_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 rm -rf "${FFMPEG_LIB_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_LIB_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1 mkdir -p "${FFMPEG_LIB_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# COPY HEADER FILES
cp -r ${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/* ${FFMPEG_LIB_FRAMEWORK_PATH}/Headers 1>>"${BASEDIR}"/build.log 2>&1 cp -r ${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/* ${FFMPEG_LIB_FRAMEWORK_PATH}/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${FFMPEG_UNIVERSAL}/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_LIB_FRAMEWORK_PATH}/${FFMPEG_LIB}" 1>>"${BASEDIR}"/build.log 2>&1 cp "${FFMPEG_UNIVERSAL}/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_LIB_FRAMEWORK_PATH}/${FFMPEG_LIB}" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES # COPY FRAMEWORK LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then if [ ${GPL_ENABLED} == "yes" ]; then
# GPLv3.0
cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
else else
# LGPLv3.0
cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
fi fi
@ -746,14 +573,16 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
echo -e "Created ${FFMPEG_LIB} framework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "Created ${FFMPEG_LIB} framework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
done done
# COPY THE LICENSES # COPY UNIVERSAL LIBRARY LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then if [ ${GPL_ENABLED} == "yes" ]; then
cp "${BASEDIR}"/LICENSE.GPLv3 "${FFMPEG_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}"/LICENSE.GPLv3 "${FFMPEG_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
else else
cp "${BASEDIR}"/LICENSE.LGPLv3 "${FFMPEG_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1 cp "${BASEDIR}"/LICENSE.LGPLv3 "${FFMPEG_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
fi fi
# 3. FFMPEG KIT # FFMPEG KIT
# INITIALIZE FRAMEWORK AND UNIVERSAL LIBRARY DIRECTORIES
FFMPEG_KIT_VERSION=$(get_ffmpeg_kit_version) FFMPEG_KIT_VERSION=$(get_ffmpeg_kit_version)
FFMPEG_KIT_UNIVERSAL="${BASEDIR}/prebuilt/ios-universal/ffmpeg-kit-universal" FFMPEG_KIT_UNIVERSAL="${BASEDIR}/prebuilt/ios-universal/ffmpeg-kit-universal"
FFMPEG_KIT_FRAMEWORK_PATH="${BASEDIR}/prebuilt/ios-framework/ffmpegkit.framework" FFMPEG_KIT_FRAMEWORK_PATH="${BASEDIR}/prebuilt/ios-framework/ffmpegkit.framework"
@ -769,15 +598,18 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
done done
LIPO_COMMAND+=" -output ${FFMPEG_KIT_UNIVERSAL}/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" LIPO_COMMAND+=" -output ${FFMPEG_KIT_UNIVERSAL}/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}"
# EXECUTE CREATE UNIVERSAL LIBRARY COMMAND
${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1 ${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo -e "failed\n" echo -e "failed\n"
exit 1 exit 1
fi fi
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/ffmpeg-kit/include/* "${FFMPEG_KIT_UNIVERSAL}"/include 1>>"${BASEDIR}"/build.log 2>&1 cp -r "${BASEDIR}"/prebuilt/ios-"${TARGET_ARCH_LIST[0]}"/ffmpeg-kit/include/* "${FFMPEG_KIT_UNIVERSAL}"/include 1>>"${BASEDIR}"/build.log 2>&1
cp -r "${FFMPEG_KIT_UNIVERSAL}"/include/* "${FFMPEG_KIT_FRAMEWORK_PATH}"/Headers 1>>"${BASEDIR}"/build.log 2>&1 cp -r "${FFMPEG_KIT_UNIVERSAL}"/include/* "${FFMPEG_KIT_FRAMEWORK_PATH}"/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${FFMPEG_KIT_UNIVERSAL}/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_KIT_FRAMEWORK_PATH}/ffmpegkit" 1>>"${BASEDIR}"/build.log 2>&1 cp "${FFMPEG_KIT_UNIVERSAL}/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_KIT_FRAMEWORK_PATH}/ffmpegkit" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES # COPY THE LICENSES
@ -793,7 +625,6 @@ if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
build_modulemap "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules/module.modulemap" build_modulemap "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules/module.modulemap"
echo -e "Created ffmpegkit.framework and universal library successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1 echo -e "Created ffmpegkit.framework and universal library successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "ok\n" echo -e "ok\n"
fi fi
fi fi

@ -0,0 +1,600 @@
#!/bin/bash
# CHECK IF XCODE IS INSTALLED
if [ ! -x "$(command -v xcrun)" ]; then
echo -e "\n(*) xcrun command not found. Please check your Xcode installation\n"
exit 1
fi
# LOAD INITIAL SETTINGS
export BASEDIR="$(pwd)"
export FFMPEG_KIT_BUILD_TYPE="macos"
source "${BASEDIR}"/scripts/variable.sh
source "${BASEDIR}"/scripts/function-${FFMPEG_KIT_BUILD_TYPE}.sh
# SET DEFAULTS SETTINGS
enable_default_macos_architectures
enable_main_build
# SELECT XCODE VERSION USED FOR BUILDING
XCODE_FOR_FFMPEG_KIT=$(ls ~/.xcode.for.ffmpeg.kit.sh)
if [[ -f ${XCODE_FOR_FFMPEG_KIT} ]]; then
source "${XCODE_FOR_FFMPEG_KIT}" 1>>"${BASEDIR}"/build.log 2>&1
fi
# DETECT MACOS SDK VERSION
DETECTED_MACOS_SDK_VERSION="$(xcrun --sdk macosx --show-sdk-version)"
echo -e "INFO: Using SDK ${DETECTED_MACOS_SDK_VERSION} by Xcode provided at $(xcode-select -p)\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "\nINFO: Build options: $*\n" 1>>"${BASEDIR}"/build.log 2>&1
# SET DEFAULT BUILD OPTIONS
GPL_ENABLED="no"
DISPLAY_HELP=""
BUILD_TYPE_ID=""
BUILD_FULL=""
FFMPEG_KIT_XCF_BUILD=""
BUILD_FORCE=""
BUILD_VERSION=$(git describe --tags --always 2>>"${BASEDIR}"/build.log)
if [[ -z ${BUILD_VERSION} ]]; then
echo -e "\n(*): Can not run git commands in this folder. See build.log.\n"
exit 1
fi
# PROCESS LTS BUILD OPTION FIRST AND SET BUILD TYPE: MAIN OR LTS
for argument in "$@"; do
if [[ "$argument" == "-l" ]] || [[ "$argument" == "--lts" ]]; then
enable_lts_build
BUILD_TYPE_ID+="LTS "
fi
done
# PROCESS BUILD OPTIONS
while [ ! $# -eq 0 ]; do
case $1 in
-h | --help)
DISPLAY_HELP="1"
;;
-v | --version)
display_version
exit 0
;;
--skip-*)
SKIP_LIBRARY=$(echo "$1" | sed -e 's/^--[A-Za-z]*-//g')
skip_library "${SKIP_LIBRARY}"
;;
--no-output-redirection)
no_output_redirection
;;
--no-workspace-cleanup-*)
NO_WORKSPACE_CLEANUP_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-[A-Za-z]*-[A-Za-z]*-//g')
no_workspace_cleanup_library "${NO_WORKSPACE_CLEANUP_LIBRARY}"
;;
-d | --debug)
enable_debug
;;
-s | --speed)
optimize_for_speed
;;
-l | --lts) ;;
-x | --xcframework)
FFMPEG_KIT_XCF_BUILD="1"
;;
-f | --force)
BUILD_FORCE="1"
;;
--reconf-*)
CONF_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
reconf_library "${CONF_LIBRARY}"
;;
--rebuild-*)
BUILD_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
rebuild_library "${BUILD_LIBRARY}"
;;
--redownload-*)
DOWNLOAD_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
redownload_library "${DOWNLOAD_LIBRARY}"
;;
--full)
BUILD_FULL="1"
;;
--enable-gpl)
GPL_ENABLED="yes"
;;
--enable-*)
ENABLED_LIBRARY=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
enable_library "${ENABLED_LIBRARY}"
;;
--disable-*)
DISABLED_ARCH=$(echo $1 | sed -e 's/^--[A-Za-z]*-//g')
disable_arch "${DISABLED_ARCH}"
;;
*)
print_unknown_option "$1"
;;
esac
shift
done
# VALIDATE THAT LTS RELEASES ARE BUILT USING THE CORRECT VERSION
if [[ -n ${FFMPEG_KIT_LTS_BUILD} ]] && [[ "${DETECTED_MACOS_SDK_VERSION}" != "${MACOS_MIN_VERSION}" ]]; then
if [[ -z ${BUILD_FORCE} ]]; then
echo -e "\n(*) LTS packages should be built using SDK ${MACOS_MIN_VERSION} but current configuration uses SDK ${DETECTED_MACOS_SDK_VERSION}\n"
exit 1
fi
fi
# PROCESS FULL OPTION AS LAST OPTION
if [[ -n ${BUILD_FULL} ]]; then
for library in {0..57}; do
if [ ${GPL_ENABLED} == "yes" ]; then
enable_library "$(get_library_name $library)" 1
else
if [[ $(is_gpl_licensed $library) -eq 1 ]]; then
enable_library "$(get_library_name $library)" 1
fi
fi
done
fi
# IF HELP DISPLAYED EXIT
if [[ -n ${DISPLAY_HELP} ]]; then
display_help
exit 0
fi
# CHECK SOME RULES FOR .xcframework BUNDLES
# 1. DO NOT ALLOW --lts AND --xcframework OPTIONS TOGETHER
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]] && [[ -n ${FFMPEG_KIT_LTS_BUILD} ]]; then
echo -e "\n(*) LTS packages does not support xcframework bundles.\n"
exit 1
fi
echo -e "\nBuilding ffmpeg-kit ${BUILD_TYPE_ID}static library for macOS\n"
echo -e -n "INFO: Building ffmpeg-kit ${BUILD_VERSION} ${BUILD_TYPE_ID}for macOS: " 1>>"${BASEDIR}"/build.log 2>&1
echo -e "$(date)\n" 1>>"${BASEDIR}"/build.log 2>&1
# PRINT BUILD SUMMARY
print_enabled_architectures
print_enabled_libraries
print_reconfigure_requested_libraries
print_rebuild_requested_libraries
print_redownload_requested_libraries
# VALIDATE GPL FLAGS
for gpl_library in {$LIBRARY_X264,$LIBRARY_XVIDCORE,$LIBRARY_X265,$LIBRARY_LIBVIDSTAB,$LIBRARY_RUBBERBAND}; do
if [[ ${ENABLED_LIBRARIES[$gpl_library]} -eq 1 ]]; then
library_name=$(get_library_name ${gpl_library})
if [ ${GPL_ENABLED} != "yes" ]; then
echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n"
echo -e "\n(*) Invalid configuration detected. GPL library ${library_name} enabled without --enable-gpl flag.\n" 1>>"${BASEDIR}"/build.log 2>&1
exit 1
fi
fi
done
echo -n -e "\nDownloading sources: "
echo -e "INFO: Downloading source code of ffmpeg and enabled external libraries.\n" 1>>"${BASEDIR}"/build.log 2>&1
# DOWNLOAD LIBRARY SOURCES
downloaded_enabled_library_sources "${ENABLED_LIBRARIES[@]}"
# THIS WILL SAVE ARCHITECTURES TO BUILD
TARGET_ARCH_LIST=()
# BUILD ENABLED LIBRARIES ON ENABLED ARCHITECTURES
for run_arch in {0..10}; do
if [[ ${ENABLED_ARCHITECTURES[$run_arch]} -eq 1 ]]; then
export ARCH=$(get_arch_name $run_arch)
export TARGET_SDK=$(get_target_sdk)
export SDK_PATH=$(get_sdk_path)
export SDK_NAME=$(get_sdk_name)
export LIPO="$(xcrun --sdk "$(get_sdk_name)" -f lipo)"
# EXECUTE MAIN BUILD SCRIPT
. "${BASEDIR}"/scripts/main-macos.sh "${ENABLED_LIBRARIES[@]}"
case ${ARCH} in
x86-64)
TARGET_ARCH="x86_64"
;;
*)
TARGET_ARCH="${ARCH}"
;;
esac
TARGET_ARCH_LIST+=("${TARGET_ARCH}")
# CLEAR FLAGS
for library in {0..57}; do
library_name=$(get_library_name ${library})
unset "$(echo "OK_${library_name}" | sed "s/\-/\_/g")"
unset "$(echo "DEPENDENCY_REBUILT_${library_name}" | sed "s/\-/\_/g")"
done
fi
done
FFMPEG_LIBS="libavcodec libavdevice libavfilter libavformat libavutil libswresample libswscale"
# BUILD STATIC LIBRARIES
BUILD_LIBRARY_EXTENSION="a"
# BUILD FFMPEG-KIT
if [[ -n ${TARGET_ARCH_LIST[0]} ]]; then
# INITIALIZE TARGET FOLDERS
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then
echo -e -n "\n\nCreating xcframeworks under prebuilt: "
rm -rf "${BASEDIR}/prebuilt/macos-xcframework" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${BASEDIR}/prebuilt/macos-xcframework" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
else
echo -e -n "\n\nCreating frameworks and universal libraries under prebuilt: "
rm -rf "${BASEDIR}/prebuilt/macos-universal" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${BASEDIR}/prebuilt/macos-universal" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
rm -rf "${BASEDIR}/prebuilt/macos-framework" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${BASEDIR}/prebuilt/macos-framework" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
fi
# CREATE ENABLED LIBRARY PACKAGES. IT IS EITHER
# .framework and fat/universal library
# OR
# .xcframework
for library in {0..57}; do
if [[ ${ENABLED_LIBRARIES[$library]} -eq 1 ]]; then
library_name=$(get_library_name ${library})
package_config_file_name=$(get_package_config_file_name ${library})
# EACH ENABLED LIBRARY HAS TO HAVE A .pc FILE AND A VERSION
library_version=$(get_external_library_version "${package_config_file_name}")
if [[ -z ${library_version} ]]; then
echo -e "Failed to detect version for ${library_name} from ${package_config_file_name}.pc\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "failed\n"
exit 1
fi
echo -e "Creating external library package for ${library_name}\n" 1>>"${BASEDIR}"/build.log 2>&1
# SOME CUSTOM CODE TO HANDLE LIBRARIES THAT PRODUCE MULTIPLE LIBRARY FILES
if [[ ${LIBRARY_LIBTHEORA} == "$library" ]]; then
LIBRARY_CREATED=$(create_external_library_package $library "libtheora" "libtheora.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libtheoraenc" "libtheoraenc.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libtheoradec" "libtheoradec.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
elif [[ ${LIBRARY_LIBVORBIS} == "$library" ]]; then
LIBRARY_CREATED=$(create_external_library_package $library "libvorbisfile" "libvorbisfile.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libvorbisenc" "libvorbisenc.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libvorbis" "libvorbis.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
elif [[ ${LIBRARY_LIBWEBP} == "$library" ]]; then
LIBRARY_CREATED=$(create_external_library_package $library "libwebpmux" "libwebpmux.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libwebpdemux" "libwebpdemux.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libwebp" "libwebp.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
elif [[ ${LIBRARY_OPENCOREAMR} == "$library" ]]; then
LIBRARY_CREATED=$(create_external_library_package $library "libopencore-amrnb" "libopencore-amrnb.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
elif [[ ${LIBRARY_NETTLE} == "$library" ]]; then
LIBRARY_CREATED=$(create_external_library_package $library "libnettle" "libnettle.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
LIBRARY_CREATED=$(create_external_library_package $library "libhogweed" "libhogweed.a" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
else
# LIBRARIES WHICH HAVE ONLY ONE LIBRARY FILE ARE CREATED HERE
library_name=$(get_library_name $((library)))
static_archive_name=$(get_static_archive_name $((library)))
LIBRARY_CREATED=$(create_external_library_package $library "$library_name" "$static_archive_name" "${library_version}")
if [[ ${LIBRARY_CREATED} -ne 0 ]]; then
echo -e "failed\n"
exit 1
fi
fi
fi
done
# CREATE FFMPEG & FFMPEG KIT PACKAGES
if [[ -n ${FFMPEG_KIT_XCF_BUILD} ]]; then
# CREATE .xcframework BUNDLE IF ENABLED
# CREATE FFMPEG
for FFMPEG_LIB in ${FFMPEG_LIBS}; do
# INITIALIZE FFMPEG FRAMEWORK DIRECTORY
XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/macos-xcframework/${FFMPEG_LIB}.xcframework
mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
echo -e "Creating package for ${FFMPEG_LIB}\n" 1>>"${BASEDIR}"/build.log 2>&1
BUILD_COMMAND="xcodebuild -create-xcframework "
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
FFMPEG_LIB_UPPERCASE=$(echo "${FFMPEG_LIB}" | tr '[a-z]' '[A-Z]')
FFMPEG_LIB_CAPITALCASE=$(to_capital_case "${FFMPEG_LIB}")
# EXTRACT FFMPEG VERSION
FFMPEG_LIB_MAJOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR" "${BASEDIR}/prebuilt/macos-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR//g;s/\ //g")
FFMPEG_LIB_MINOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR" "${BASEDIR}/prebuilt/macos-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR//g;s/\ //g")
FFMPEG_LIB_MICRO=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO" "${BASEDIR}/prebuilt/macos-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/version.h" | sed "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO//g;s/\ //g")
FFMPEG_LIB_VERSION="${FFMPEG_LIB_MAJOR}.${FFMPEG_LIB_MINOR}.${FFMPEG_LIB_MICRO}"
# INITIALIZE SUB-FRAMEWORK DIRECTORY
FFMPEG_LIB_FRAMEWORK_PATH=${BASEDIR}/prebuilt/macos-xcframework/.tmp/macos-${TARGET_ARCH}/${FFMPEG_LIB}.framework
rm -rf "${FFMPEG_LIB_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_LIB_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/macos-${TARGET_ARCH}/ffmpeg/include/${FFMPEG_LIB}/* ${FFMPEG_LIB_FRAMEWORK_PATH}/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${BASEDIR}/prebuilt/macos-${TARGET_ARCH}/ffmpeg/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_LIB_FRAMEWORK_PATH}/${FFMPEG_LIB}" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then
cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
else
cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
fi
build_info_plist "${FFMPEG_LIB_FRAMEWORK_PATH}/Info.plist" "${FFMPEG_LIB}" "com.arthenica.ffmpegkit.${FFMPEG_LIB_CAPITALCASE}" "${FFMPEG_LIB_VERSION}" "${FFMPEG_LIB_VERSION}"
BUILD_COMMAND+=" -framework ${FFMPEG_LIB_FRAMEWORK_PATH}"
done
BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}"
# EXECUTE CREATE FRAMEWORK COMMAND
COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1)
echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1
echo "" 1>>"${BASEDIR}"/build.log 2>&1
# DO NOT ALLOW EMPTY FRAMEWORKS
if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then
echo -e "failed\n"
exit 1
fi
echo -e "Created ${FFMPEG_LIB} xcframework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
done
# CREATE FFMPEG
# INITIALIZE FFMPEG KIT FRAMEWORK DIRECTORY
XCFRAMEWORK_PATH=${BASEDIR}/prebuilt/macos-xcframework/ffmpegkit.xcframework
mkdir -p "${XCFRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
BUILD_COMMAND="xcodebuild -create-xcframework "
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
# INITIALIZE SUB-FRAMEWORK DIRECTORY
FFMPEG_KIT_FRAMEWORK_PATH="${BASEDIR}/prebuilt/macos-xcframework/.tmp/macos-${TARGET_ARCH}/ffmpegkit.framework"
rm -rf "${FFMPEG_KIT_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
build_modulemap "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules/module.modulemap"
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/macos-"${TARGET_ARCH}"/ffmpeg-kit/include/* "${FFMPEG_KIT_FRAMEWORK_PATH}"/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${BASEDIR}/prebuilt/macos-${TARGET_ARCH}/ffmpeg-kit/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_KIT_FRAMEWORK_PATH}/ffmpegkit" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then
cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_KIT_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
else
cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_KIT_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
fi
BUILD_COMMAND+=" -framework ${FFMPEG_KIT_FRAMEWORK_PATH}"
done
BUILD_COMMAND+=" -output ${XCFRAMEWORK_PATH}"
# EXECUTE CREATE FRAMEWORK COMMAND
COMMAND_OUTPUT=$(${BUILD_COMMAND} 2>&1)
echo "${COMMAND_OUTPUT}" 1>>"${BASEDIR}"/build.log 2>&1
echo "" 1>>"${BASEDIR}"/build.log 2>&1
# DO NOT ALLOW EMPTY FRAMEWORKS
if [[ ${COMMAND_OUTPUT} == *"is empty in library"* ]]; then
echo -e "failed\n"
exit 1
fi
echo -e "Created ffmpegkit xcframework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "ok\n"
else
# CREATE .framework AND FAT/UNIVERSAL LIBRARY IF ENABLED
# CREATE FFMPEG
# INITIALIZE UNIVERSAL LIBRARY DIRECTORY
FFMPEG_UNIVERSAL="${BASEDIR}/prebuilt/macos-universal/ffmpeg-universal"
mkdir -p "${FFMPEG_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${FFMPEG_UNIVERSAL}/lib" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/macos-"${TARGET_ARCH_LIST[0]}"/ffmpeg/include/* ${FFMPEG_UNIVERSAL}/include 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/prebuilt/macos-"${TARGET_ARCH_LIST[0]}"/ffmpeg/include/config.h "${FFMPEG_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1
for FFMPEG_LIB in ${FFMPEG_LIBS}; do
LIPO_COMMAND="${LIPO} -create"
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
LIPO_COMMAND+=" "${BASEDIR}"/prebuilt/macos-${TARGET_ARCH}/ffmpeg/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}"
done
LIPO_COMMAND+=" -output ${FFMPEG_UNIVERSAL}/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}"
# EXECUTE CREATE UNIVERSAL LIBRARY COMMAND
${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -ne 0 ]; then
echo -e "failed\n"
exit 1
fi
FFMPEG_LIB_UPPERCASE=$(echo "${FFMPEG_LIB}" | tr '[a-z]' '[A-Z]')
FFMPEG_LIB_CAPITALCASE=$(to_capital_case "${FFMPEG_LIB}")
# EXTRACT FFMPEG VERSION
FFMPEG_LIB_MAJOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MAJOR//g;s/\ //g")
FFMPEG_LIB_MINOR=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed -e "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MINOR//g;s/\ //g")
FFMPEG_LIB_MICRO=$(grep "#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO" "${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/version.h" | sed "s/#define ${FFMPEG_LIB_UPPERCASE}_VERSION_MICRO//g;s/\ //g")
FFMPEG_LIB_VERSION="${FFMPEG_LIB_MAJOR}.${FFMPEG_LIB_MINOR}.${FFMPEG_LIB_MICRO}"
# INITIALIZE FRAMEWORK DIRECTORY
FFMPEG_LIB_FRAMEWORK_PATH="${BASEDIR}/prebuilt/macos-framework/${FFMPEG_LIB}.framework"
rm -rf "${FFMPEG_LIB_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_LIB_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
# COPY HEADER FILES
cp -r ${FFMPEG_UNIVERSAL}/include/${FFMPEG_LIB}/* ${FFMPEG_LIB_FRAMEWORK_PATH}/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${FFMPEG_UNIVERSAL}/lib/${FFMPEG_LIB}.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_LIB_FRAMEWORK_PATH}/${FFMPEG_LIB}" 1>>"${BASEDIR}"/build.log 2>&1
# COPY FRAMEWORK LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then
cp "${BASEDIR}/LICENSE.GPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
else
cp "${BASEDIR}/LICENSE.LGPLv3" "${FFMPEG_LIB_FRAMEWORK_PATH}/LICENSE" 1>>"${BASEDIR}"/build.log 2>&1
fi
build_info_plist "${FFMPEG_LIB_FRAMEWORK_PATH}/Info.plist" "${FFMPEG_LIB}" "com.arthenica.ffmpegkit.${FFMPEG_LIB_CAPITALCASE}" "${FFMPEG_LIB_VERSION}" "${FFMPEG_LIB_VERSION}"
echo -e "Created ${FFMPEG_LIB} framework successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
done
# COPY UNIVERSAL LIBRARY LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then
cp "${BASEDIR}"/LICENSE.GPLv3 "${FFMPEG_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
else
cp "${BASEDIR}"/LICENSE.LGPLv3 "${FFMPEG_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
fi
# FFMPEG KIT
# INITIALIZE FRAMEWORK AND UNIVERSAL LIBRARY DIRECTORIES
FFMPEG_KIT_VERSION=$(get_ffmpeg_kit_version)
FFMPEG_KIT_UNIVERSAL="${BASEDIR}/prebuilt/macos-universal/ffmpeg-kit-universal"
FFMPEG_KIT_FRAMEWORK_PATH="${BASEDIR}/prebuilt/macos-framework/ffmpegkit.framework"
mkdir -p "${FFMPEG_KIT_UNIVERSAL}/include" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${FFMPEG_KIT_UNIVERSAL}/lib" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
rm -rf "${FFMPEG_KIT_FRAMEWORK_PATH}" 1>>"${BASEDIR}"/build.log 2>&1
mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Headers" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
mkdir -p "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules" 1>>"${BASEDIR}"/build.log 2>&1 || exit 1
LIPO_COMMAND="${LIPO} -create"
for TARGET_ARCH in "${TARGET_ARCH_LIST[@]}"; do
LIPO_COMMAND+=" ${BASEDIR}/prebuilt/macos-${TARGET_ARCH}/ffmpeg-kit/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}"
done
LIPO_COMMAND+=" -output ${FFMPEG_KIT_UNIVERSAL}/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}"
# EXECUTE CREATE UNIVERSAL LIBRARY COMMAND
${LIPO_COMMAND} 1>>"${BASEDIR}"/build.log 2>&1
if [ $? -ne 0 ]; then
echo -e "failed\n"
exit 1
fi
# COPY HEADER FILES
cp -r "${BASEDIR}"/prebuilt/macos-"${TARGET_ARCH_LIST[0]}"/ffmpeg-kit/include/* "${FFMPEG_KIT_UNIVERSAL}"/include 1>>"${BASEDIR}"/build.log 2>&1
cp -r "${FFMPEG_KIT_UNIVERSAL}"/include/* "${FFMPEG_KIT_FRAMEWORK_PATH}"/Headers 1>>"${BASEDIR}"/build.log 2>&1
# COPY LIBRARY FILE
cp "${FFMPEG_KIT_UNIVERSAL}/lib/libffmpegkit.${BUILD_LIBRARY_EXTENSION}" "${FFMPEG_KIT_FRAMEWORK_PATH}/ffmpegkit" 1>>"${BASEDIR}"/build.log 2>&1
# COPY THE LICENSES
if [ ${GPL_ENABLED} == "yes" ]; then
cp "${BASEDIR}"/LICENSE.GPLv3 "${FFMPEG_KIT_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/LICENSE.GPLv3 "${FFMPEG_KIT_FRAMEWORK_PATH}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
else
cp "${BASEDIR}"/LICENSE.LGPLv3 "${FFMPEG_KIT_UNIVERSAL}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
cp "${BASEDIR}"/LICENSE.LGPLv3 "${FFMPEG_KIT_FRAMEWORK_PATH}"/LICENSE 1>>"${BASEDIR}"/build.log 2>&1
fi
build_info_plist "${FFMPEG_KIT_FRAMEWORK_PATH}/Info.plist" "ffmpegkit" "com.arthenica.ffmpegkit.FFmpegKit" "${FFMPEG_KIT_VERSION}" "${FFMPEG_KIT_VERSION}"
build_modulemap "${FFMPEG_KIT_FRAMEWORK_PATH}/Modules/module.modulemap"
echo -e "Created ffmpegkit.framework and universal library successfully.\n" 1>>"${BASEDIR}"/build.log 2>&1
echo -e "ok\n"
fi
fi

10
objc/.gitignore vendored

@ -0,0 +1,10 @@
/autom4te.cache/
/Makefile
/config.status
/configure.tmp
/.deps/
/.libs/
*.trs
/unittests
/test-driver
/config.log

File diff suppressed because it is too large Load Diff

@ -0,0 +1,3 @@
ACLOCAL_AMFLAGS = -I m4
SUBDIRS = src

@ -0,0 +1,806 @@
# Makefile.in generated by automake 1.16.2 from Makefile.am.
# @configure_input@
# Copyright (C) 1994-2020 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
@SET_MAKE@
VPATH = @srcdir@
am__is_gnu_make = { \
if test -z '$(MAKELEVEL)'; then \
false; \
elif test -n '$(MAKE_HOST)'; then \
true; \
elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
true; \
else \
false; \
fi; \
}
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
pkgdatadir = $(datadir)/@PACKAGE@
pkgincludedir = $(includedir)/@PACKAGE@
pkglibdir = $(libdir)/@PACKAGE@
pkglibexecdir = $(libexecdir)/@PACKAGE@
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
subdir = .
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \
$(am__configure_deps) $(am__DIST_COMMON)
am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
configure.lineno config.status.lineno
mkinstalldirs = $(install_sh) -d
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
AM_V_P = $(am__v_P_@AM_V@)
am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_@AM_V@)
am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_@AM_V@)
am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
am__v_at_0 = @
am__v_at_1 =
SOURCES =
DIST_SOURCES =
RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
ctags-recursive dvi-recursive html-recursive info-recursive \
install-data-recursive install-dvi-recursive \
install-exec-recursive install-html-recursive \
install-info-recursive install-pdf-recursive \
install-ps-recursive install-recursive installcheck-recursive \
installdirs-recursive pdf-recursive ps-recursive \
tags-recursive uninstall-recursive
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \
distclean-recursive maintainer-clean-recursive
am__recursive_targets = \
$(RECURSIVE_TARGETS) \
$(RECURSIVE_CLEAN_TARGETS) \
$(am__extra_recursive_targets)
AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
cscope distdir distdir-am dist dist-all distcheck
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
# Read a list of newline-separated strings from the standard input,
# and print each of them once, without duplicates. Input order is
# *not* preserved.
am__uniquify_input = $(AWK) '\
BEGIN { nonempty = 0; } \
{ items[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in items) print i; }; } \
'
# Make sure the list of sources is unique. This is necessary because,
# e.g., the same source file might be shared among _SOURCES variables
# for different programs/libraries.
am__define_uniq_tagged_files = \
list='$(am__tagged_files)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | $(am__uniquify_input)`
ETAGS = etags
CTAGS = ctags
CSCOPE = cscope
DIST_SUBDIRS = $(SUBDIRS)
am__DIST_COMMON = $(srcdir)/Makefile.in ar-lib compile config.guess \
config.sub install-sh ltmain.sh missing
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
distdir = $(PACKAGE)-$(VERSION)
top_distdir = $(distdir)
am__remove_distdir = \
if test -d "$(distdir)"; then \
find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \
&& rm -rf "$(distdir)" \
|| { sleep 5 && rm -rf "$(distdir)"; }; \
else :; fi
am__post_remove_distdir = $(am__remove_distdir)
am__relativize = \
dir0=`pwd`; \
sed_first='s,^\([^/]*\)/.*$$,\1,'; \
sed_rest='s,^[^/]*/*,,'; \
sed_last='s,^.*/\([^/]*\)$$,\1,'; \
sed_butlast='s,/*[^/]*$$,,'; \
while test -n "$$dir1"; do \
first=`echo "$$dir1" | sed -e "$$sed_first"`; \
if test "$$first" != "."; then \
if test "$$first" = ".."; then \
dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
else \
first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
if test "$$first2" = "$$first"; then \
dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
else \
dir2="../$$dir2"; \
fi; \
dir0="$$dir0"/"$$first"; \
fi; \
fi; \
dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
done; \
reldir="$$dir2"
DIST_ARCHIVES = $(distdir).tar.gz
GZIP_ENV = --best
DIST_TARGETS = dist-gzip
distuninstallcheck_listfiles = find . -type f -print
am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \
| sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$'
distcleancheck_listfiles = find . -type f -print
ACLOCAL = @ACLOCAL@
AMTAR = @AMTAR@
AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
AR = @AR@
AUTOCONF = @AUTOCONF@
AUTOHEADER = @AUTOHEADER@
AUTOMAKE = @AUTOMAKE@
AWK = @AWK@
CC = @CC@
CCDEPMODE = @CCDEPMODE@
CFLAGS = @CFLAGS@
CPP = @CPP@
CPPFLAGS = @CPPFLAGS@
CYGPATH_W = @CYGPATH_W@
DEFS = @DEFS@
DEPDIR = @DEPDIR@
DLLTOOL = @DLLTOOL@
DSYMUTIL = @DSYMUTIL@
DUMPBIN = @DUMPBIN@
ECHO_C = @ECHO_C@
ECHO_N = @ECHO_N@
ECHO_T = @ECHO_T@
EGREP = @EGREP@
EXEEXT = @EXEEXT@
FFMPEG_LIBS = @FFMPEG_LIBS@
FGREP = @FGREP@
GREP = @GREP@
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_SCRIPT = @INSTALL_SCRIPT@
INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
LD = @LD@
LDFLAGS = @LDFLAGS@
LIBOBJS = @LIBOBJS@
LIBS = @LIBS@
LIBTOOL = @LIBTOOL@
LIPO = @LIPO@
LN_S = @LN_S@
LTLIBOBJS = @LTLIBOBJS@
LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
MAINT = @MAINT@
MAKEINFO = @MAKEINFO@
MANIFEST_TOOL = @MANIFEST_TOOL@
MKDIR_P = @MKDIR_P@
NM = @NM@
NMEDIT = @NMEDIT@
OBJC = @OBJC@
OBJCDEPMODE = @OBJCDEPMODE@
OBJCFLAGS = @OBJCFLAGS@
OBJDUMP = @OBJDUMP@
OBJEXT = @OBJEXT@
OTOOL = @OTOOL@
OTOOL64 = @OTOOL64@
PACKAGE = @PACKAGE@
PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
PACKAGE_NAME = @PACKAGE_NAME@
PACKAGE_STRING = @PACKAGE_STRING@
PACKAGE_TARNAME = @PACKAGE_TARNAME@
PACKAGE_URL = @PACKAGE_URL@
PACKAGE_VERSION = @PACKAGE_VERSION@
PATH_SEPARATOR = @PATH_SEPARATOR@
RANLIB = @RANLIB@
SED = @SED@
SET_MAKE = @SET_MAKE@
SHELL = @SHELL@
STRIP = @STRIP@
VERSION = @VERSION@
abs_builddir = @abs_builddir@
abs_srcdir = @abs_srcdir@
abs_top_builddir = @abs_top_builddir@
abs_top_srcdir = @abs_top_srcdir@
ac_ct_AR = @ac_ct_AR@
ac_ct_CC = @ac_ct_CC@
ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
ac_ct_OBJC = @ac_ct_OBJC@
am__include = @am__include@
am__leading_dot = @am__leading_dot@
am__quote = @am__quote@
am__tar = @am__tar@
am__untar = @am__untar@
bindir = @bindir@
build = @build@
build_alias = @build_alias@
build_cpu = @build_cpu@
build_os = @build_os@
build_vendor = @build_vendor@
builddir = @builddir@
datadir = @datadir@
datarootdir = @datarootdir@
docdir = @docdir@
dvidir = @dvidir@
exec_prefix = @exec_prefix@
host = @host@
host_alias = @host_alias@
host_cpu = @host_cpu@
host_os = @host_os@
host_vendor = @host_vendor@
htmldir = @htmldir@
includedir = @includedir@
infodir = @infodir@
install_sh = @install_sh@
libdir = @libdir@
libexecdir = @libexecdir@
localedir = @localedir@
localstatedir = @localstatedir@
mandir = @mandir@
mkdir_p = @mkdir_p@
oldincludedir = @oldincludedir@
pdfdir = @pdfdir@
prefix = @prefix@
program_transform_name = @program_transform_name@
psdir = @psdir@
sbindir = @sbindir@
sharedstatedir = @sharedstatedir@
srcdir = @srcdir@
sysconfdir = @sysconfdir@
target_alias = @target_alias@
top_build_prefix = @top_build_prefix@
top_builddir = @top_builddir@
top_srcdir = @top_srcdir@
ACLOCAL_AMFLAGS = -I m4
SUBDIRS = src
all: all-recursive
.SUFFIXES:
am--refresh: Makefile
@:
$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \
$(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
echo ' $(SHELL) ./config.status'; \
$(SHELL) ./config.status;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__maybe_remake_depfiles)'; \
cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__maybe_remake_depfiles);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
$(SHELL) ./config.status --recheck
$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
$(am__cd) $(srcdir) && $(AUTOCONF)
$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
$(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
$(am__aclocal_m4_deps):
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
distclean-libtool:
-rm -f libtool config.lt
# This directory's subdirectories are mostly independent; you can cd
# into them and run 'make' without going through this Makefile.
# To change the values of 'make' variables: instead of editing Makefiles,
# (1) if the variable is set in 'config.status', edit 'config.status'
# (which will cause the Makefiles to be regenerated when you run 'make');
# (2) otherwise, pass the desired values on the 'make' command line.
$(am__recursive_targets):
@fail=; \
if $(am__make_keepgoing); then \
failcom='fail=yes'; \
else \
failcom='exit 1'; \
fi; \
dot_seen=no; \
target=`echo $@ | sed s/-recursive//`; \
case "$@" in \
distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
*) list='$(SUBDIRS)' ;; \
esac; \
for subdir in $$list; do \
echo "Making $$target in $$subdir"; \
if test "$$subdir" = "."; then \
dot_seen=yes; \
local_target="$$target-am"; \
else \
local_target="$$target"; \
fi; \
($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
|| eval $$failcom; \
done; \
if test "$$dot_seen" = "no"; then \
$(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
fi; test -z "$$fail"
ID: $(am__tagged_files)
$(am__define_uniq_tagged_files); mkid -fID $$unique
tags: tags-recursive
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
include_option=--etags-include; \
empty_fix=.; \
else \
include_option=--include; \
empty_fix=; \
fi; \
list='$(SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
test ! -f $$subdir/TAGS || \
set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
fi; \
done; \
$(am__define_uniq_tagged_files); \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: ctags-recursive
CTAGS: ctags
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
$(am__define_uniq_tagged_files); \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
cscope: cscope.files
test ! -s cscope.files \
|| $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS)
clean-cscope:
-rm -f cscope.files
cscope.files: clean-cscope cscopelist
cscopelist: cscopelist-recursive
cscopelist-am: $(am__tagged_files)
list='$(am__tagged_files)'; \
case "$(srcdir)" in \
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
*) sdir=$(subdir)/$(srcdir) ;; \
esac; \
for i in $$list; do \
if test -f "$$i"; then \
echo "$(subdir)/$$i"; \
else \
echo "$$sdir/$$i"; \
fi; \
done >> $(top_builddir)/cscope.files
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
-rm -f cscope.out cscope.in.out cscope.po.out cscope.files
distdir: $(BUILT_SOURCES)
$(MAKE) $(AM_MAKEFLAGS) distdir-am
distdir-am: $(DISTFILES)
$(am__remove_distdir)
test -d "$(distdir)" || mkdir "$(distdir)"
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
$(am__make_dryrun) \
|| test -d "$(distdir)/$$subdir" \
|| $(MKDIR_P) "$(distdir)/$$subdir" \
|| exit 1; \
dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
$(am__relativize); \
new_distdir=$$reldir; \
dir1=$$subdir; dir2="$(top_distdir)"; \
$(am__relativize); \
new_top_distdir=$$reldir; \
echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
($(am__cd) $$subdir && \
$(MAKE) $(AM_MAKEFLAGS) \
top_distdir="$$new_top_distdir" \
distdir="$$new_distdir" \
am__remove_distdir=: \
am__skip_length_check=: \
am__skip_mode_fix=: \
distdir) \
|| exit 1; \
fi; \
done
-test -n "$(am__skip_mode_fix)" \
|| find "$(distdir)" -type d ! -perm -755 \
-exec chmod u+rwx,go+rx {} \; -o \
! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
! -type d ! -perm -400 -exec chmod a+r {} \; -o \
! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
|| chmod -R a+r "$(distdir)"
dist-gzip: distdir
tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz
$(am__post_remove_distdir)
dist-bzip2: distdir
tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2
$(am__post_remove_distdir)
dist-lzip: distdir
tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz
$(am__post_remove_distdir)
dist-xz: distdir
tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz
$(am__post_remove_distdir)
dist-zstd: distdir
tardir=$(distdir) && $(am__tar) | zstd -c $${ZSTD_CLEVEL-$${ZSTD_OPT--19}} >$(distdir).tar.zst
$(am__post_remove_distdir)
dist-tarZ: distdir
@echo WARNING: "Support for distribution archives compressed with" \
"legacy program 'compress' is deprecated." >&2
@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
$(am__post_remove_distdir)
dist-shar: distdir
@echo WARNING: "Support for shar distribution archives is" \
"deprecated." >&2
@echo WARNING: "It will be removed altogether in Automake 2.0" >&2
shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz
$(am__post_remove_distdir)
dist-zip: distdir
-rm -f $(distdir).zip
zip -rq $(distdir).zip $(distdir)
$(am__post_remove_distdir)
dist dist-all:
$(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:'
$(am__post_remove_distdir)
# This target untars the dist file and tries a VPATH configuration. Then
# it guarantees that the distribution is self-contained by making another
# tarfile.
distcheck: dist
case '$(DIST_ARCHIVES)' in \
*.tar.gz*) \
eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\
*.tar.bz2*) \
bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\
*.tar.lz*) \
lzip -dc $(distdir).tar.lz | $(am__untar) ;;\
*.tar.xz*) \
xz -dc $(distdir).tar.xz | $(am__untar) ;;\
*.tar.Z*) \
uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
*.shar.gz*) \
eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\
*.zip*) \
unzip $(distdir).zip ;;\
*.tar.zst*) \
zstd -dc $(distdir).tar.zst | $(am__untar) ;;\
esac
chmod -R a-w $(distdir)
chmod u+w $(distdir)
mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst
chmod a-w $(distdir)
test -d $(distdir)/_build || exit 0; \
dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \
&& dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \
&& am__cwd=`pwd` \
&& $(am__cd) $(distdir)/_build/sub \
&& ../../configure \
$(AM_DISTCHECK_CONFIGURE_FLAGS) \
$(DISTCHECK_CONFIGURE_FLAGS) \
--srcdir=../.. --prefix="$$dc_install_base" \
&& $(MAKE) $(AM_MAKEFLAGS) \
&& $(MAKE) $(AM_MAKEFLAGS) dvi \
&& $(MAKE) $(AM_MAKEFLAGS) check \
&& $(MAKE) $(AM_MAKEFLAGS) install \
&& $(MAKE) $(AM_MAKEFLAGS) installcheck \
&& $(MAKE) $(AM_MAKEFLAGS) uninstall \
&& $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \
distuninstallcheck \
&& chmod -R a-w "$$dc_install_base" \
&& ({ \
(cd ../.. && umask 077 && mkdir "$$dc_destdir") \
&& $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \
&& $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \
&& $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \
distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \
} || { rm -rf "$$dc_destdir"; exit 1; }) \
&& rm -rf "$$dc_destdir" \
&& $(MAKE) $(AM_MAKEFLAGS) dist \
&& rm -rf $(DIST_ARCHIVES) \
&& $(MAKE) $(AM_MAKEFLAGS) distcleancheck \
&& cd "$$am__cwd" \
|| exit 1
$(am__post_remove_distdir)
@(echo "$(distdir) archives ready for distribution: "; \
list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x'
distuninstallcheck:
@test -n '$(distuninstallcheck_dir)' || { \
echo 'ERROR: trying to run $@ with an empty' \
'$$(distuninstallcheck_dir)' >&2; \
exit 1; \
}; \
$(am__cd) '$(distuninstallcheck_dir)' || { \
echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \
exit 1; \
}; \
test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \
|| { echo "ERROR: files left after uninstall:" ; \
if test -n "$(DESTDIR)"; then \
echo " (check DESTDIR support)"; \
fi ; \
$(distuninstallcheck_listfiles) ; \
exit 1; } >&2
distcleancheck: distclean
@if test '$(srcdir)' = . ; then \
echo "ERROR: distcleancheck can only run from a VPATH build" ; \
exit 1 ; \
fi
@test `$(distcleancheck_listfiles) | wc -l` -eq 0 \
|| { echo "ERROR: files left in build directory after distclean:" ; \
$(distcleancheck_listfiles) ; \
exit 1; } >&2
check-am: all-am
check: check-recursive
all-am: Makefile
installdirs: installdirs-recursive
installdirs-am:
install: install-recursive
install-exec: install-exec-recursive
install-data: install-data-recursive
uninstall: uninstall-recursive
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-recursive
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-recursive
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-recursive
-rm -f $(am__CONFIG_DISTCLEAN_FILES)
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-libtool \
distclean-tags
dvi: dvi-recursive
dvi-am:
html: html-recursive
html-am:
info: info-recursive
info-am:
install-data-am:
install-dvi: install-dvi-recursive
install-dvi-am:
install-exec-am:
install-html: install-html-recursive
install-html-am:
install-info: install-info-recursive
install-info-am:
install-man:
install-pdf: install-pdf-recursive
install-pdf-am:
install-ps: install-ps-recursive
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-recursive
-rm -f $(am__CONFIG_DISTCLEAN_FILES)
-rm -rf $(top_srcdir)/autom4te.cache
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-recursive
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-recursive
pdf-am:
ps: ps-recursive
ps-am:
uninstall-am:
.MAKE: $(am__recursive_targets) install-am install-strip
.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \
am--refresh check check-am clean clean-cscope clean-generic \
clean-libtool cscope cscopelist-am ctags ctags-am dist \
dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \
dist-xz dist-zip dist-zstd distcheck distclean \
distclean-generic distclean-libtool distclean-tags \
distcleancheck distdir distuninstallcheck dvi dvi-am html \
html-am info info-am install install-am install-data \
install-data-am install-dvi install-dvi-am install-exec \
install-exec-am install-html install-html-am install-info \
install-info-am install-man install-pdf install-pdf-am \
install-ps install-ps-am install-strip installcheck \
installcheck-am installdirs installdirs-am maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
uninstall-am
.PRECIOUS: Makefile
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:

1238
objc/aclocal.m4 vendored

File diff suppressed because it is too large Load Diff

@ -0,0 +1,271 @@
#! /bin/sh
# Wrapper for Microsoft lib.exe
me=ar-lib
scriptversion=2019-07-04.01; # UTC
# Copyright (C) 2010-2020 Free Software Foundation, Inc.
# Written by Peter Rosin <peda@lysator.liu.se>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
# func_error message
func_error ()
{
echo "$me: $1" 1>&2
exit 1
}
file_conv=
# func_file_conv build_file
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN* | MSYS*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv in
mingw)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin | msys)
file=`cygpath -m "$file" || echo "$file"`
;;
wine)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_at_file at_file operation archive
# Iterate over all members in AT_FILE performing OPERATION on ARCHIVE
# for each of them.
# When interpreting the content of the @FILE, do NOT use func_file_conv,
# since the user would need to supply preconverted file names to
# binutils ar, at least for MinGW.
func_at_file ()
{
operation=$2
archive=$3
at_file_contents=`cat "$1"`
eval set x "$at_file_contents"
shift
for member
do
$AR -NOLOGO $operation:"$member" "$archive" || exit $?
done
}
case $1 in
'')
func_error "no command. Try '$0 --help' for more information."
;;
-h | --h*)
cat <<EOF
Usage: $me [--help] [--version] PROGRAM ACTION ARCHIVE [MEMBER...]
Members may be specified in a file named with @FILE.
EOF
exit $?
;;
-v | --v*)
echo "$me, version $scriptversion"
exit $?
;;
esac
if test $# -lt 3; then
func_error "you must specify a program, an action and an archive"
fi
AR=$1
shift
while :
do
if test $# -lt 2; then
func_error "you must specify a program, an action and an archive"
fi
case $1 in
-lib | -LIB \
| -ltcg | -LTCG \
| -machine* | -MACHINE* \
| -subsystem* | -SUBSYSTEM* \
| -verbose | -VERBOSE \
| -wx* | -WX* )
AR="$AR $1"
shift
;;
*)
action=$1
shift
break
;;
esac
done
orig_archive=$1
shift
func_file_conv "$orig_archive"
archive=$file
# strip leading dash in $action
action=${action#-}
delete=
extract=
list=
quick=
replace=
index=
create=
while test -n "$action"
do
case $action in
d*) delete=yes ;;
x*) extract=yes ;;
t*) list=yes ;;
q*) quick=yes ;;
r*) replace=yes ;;
s*) index=yes ;;
S*) ;; # the index is always updated implicitly
c*) create=yes ;;
u*) ;; # TODO: don't ignore the update modifier
v*) ;; # TODO: don't ignore the verbose modifier
*)
func_error "unknown action specified"
;;
esac
action=${action#?}
done
case $delete$extract$list$quick$replace,$index in
yes,* | ,yes)
;;
yesyes*)
func_error "more than one action specified"
;;
*)
func_error "no action specified"
;;
esac
if test -n "$delete"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
for member
do
case $1 in
@*)
func_at_file "${1#@}" -REMOVE "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -REMOVE:"$file" "$archive" || exit $?
;;
esac
done
elif test -n "$extract"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
if test $# -gt 0; then
for member
do
case $1 in
@*)
func_at_file "${1#@}" -EXTRACT "$archive"
;;
*)
func_file_conv "$1"
$AR -NOLOGO -EXTRACT:"$file" "$archive" || exit $?
;;
esac
done
else
$AR -NOLOGO -LIST "$archive" | tr -d '\r' | sed -e 's/\\/\\\\/g' \
| while read member
do
$AR -NOLOGO -EXTRACT:"$member" "$archive" || exit $?
done
fi
elif test -n "$quick$replace"; then
if test ! -f "$orig_archive"; then
if test -z "$create"; then
echo "$me: creating $orig_archive"
fi
orig_archive=
else
orig_archive=$archive
fi
for member
do
case $1 in
@*)
func_file_conv "${1#@}"
set x "$@" "@$file"
;;
*)
func_file_conv "$1"
set x "$@" "$file"
;;
esac
shift
shift
done
if test -n "$orig_archive"; then
$AR -NOLOGO -OUT:"$archive" "$orig_archive" "$@" || exit $?
else
$AR -NOLOGO -OUT:"$archive" "$@" || exit $?
fi
elif test -n "$list"; then
if test ! -f "$orig_archive"; then
func_error "archive not found"
fi
$AR -NOLOGO -LIST "$archive" || exit $?
fi

@ -0,0 +1,3 @@
#!/bin/sh
autoreconf --force --install -I m4

@ -0,0 +1,348 @@
#! /bin/sh
# Wrapper for compilers which do not understand '-c -o'.
scriptversion=2018-03-07.03; # UTC
# Copyright (C) 1999-2020 Free Software Foundation, Inc.
# Written by Tom Tromey <tromey@cygnus.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
nl='
'
# We need space, tab and new line, in precisely that order. Quoting is
# there to prevent tools from complaining about whitespace usage.
IFS=" "" $nl"
file_conv=
# func_file_conv build_file lazy
# Convert a $build file to $host form and store it in $file
# Currently only supports Windows hosts. If the determined conversion
# type is listed in (the comma separated) LAZY, no conversion will
# take place.
func_file_conv ()
{
file=$1
case $file in
/ | /[!/]*) # absolute file, and not a UNC file
if test -z "$file_conv"; then
# lazily determine how to convert abs files
case `uname -s` in
MINGW*)
file_conv=mingw
;;
CYGWIN* | MSYS*)
file_conv=cygwin
;;
*)
file_conv=wine
;;
esac
fi
case $file_conv/,$2, in
*,$file_conv,*)
;;
mingw/*)
file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'`
;;
cygwin/* | msys/*)
file=`cygpath -m "$file" || echo "$file"`
;;
wine/*)
file=`winepath -w "$file" || echo "$file"`
;;
esac
;;
esac
}
# func_cl_dashL linkdir
# Make cl look for libraries in LINKDIR
func_cl_dashL ()
{
func_file_conv "$1"
if test -z "$lib_path"; then
lib_path=$file
else
lib_path="$lib_path;$file"
fi
linker_opts="$linker_opts -LIBPATH:$file"
}
# func_cl_dashl library
# Do a library search-path lookup for cl
func_cl_dashl ()
{
lib=$1
found=no
save_IFS=$IFS
IFS=';'
for dir in $lib_path $LIB
do
IFS=$save_IFS
if $shared && test -f "$dir/$lib.dll.lib"; then
found=yes
lib=$dir/$lib.dll.lib
break
fi
if test -f "$dir/$lib.lib"; then
found=yes
lib=$dir/$lib.lib
break
fi
if test -f "$dir/lib$lib.a"; then
found=yes
lib=$dir/lib$lib.a
break
fi
done
IFS=$save_IFS
if test "$found" != yes; then
lib=$lib.lib
fi
}
# func_cl_wrapper cl arg...
# Adjust compile command to suit cl
func_cl_wrapper ()
{
# Assume a capable shell
lib_path=
shared=:
linker_opts=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
eat=1
case $2 in
*.o | *.[oO][bB][jJ])
func_file_conv "$2"
set x "$@" -Fo"$file"
shift
;;
*)
func_file_conv "$2"
set x "$@" -Fe"$file"
shift
;;
esac
;;
-I)
eat=1
func_file_conv "$2" mingw
set x "$@" -I"$file"
shift
;;
-I*)
func_file_conv "${1#-I}" mingw
set x "$@" -I"$file"
shift
;;
-l)
eat=1
func_cl_dashl "$2"
set x "$@" "$lib"
shift
;;
-l*)
func_cl_dashl "${1#-l}"
set x "$@" "$lib"
shift
;;
-L)
eat=1
func_cl_dashL "$2"
;;
-L*)
func_cl_dashL "${1#-L}"
;;
-static)
shared=false
;;
-Wl,*)
arg=${1#-Wl,}
save_ifs="$IFS"; IFS=','
for flag in $arg; do
IFS="$save_ifs"
linker_opts="$linker_opts $flag"
done
IFS="$save_ifs"
;;
-Xlinker)
eat=1
linker_opts="$linker_opts $2"
;;
-*)
set x "$@" "$1"
shift
;;
*.cc | *.CC | *.cxx | *.CXX | *.[cC]++)
func_file_conv "$1"
set x "$@" -Tp"$file"
shift
;;
*.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO])
func_file_conv "$1" mingw
set x "$@" "$file"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -n "$linker_opts"; then
linker_opts="-link$linker_opts"
fi
exec "$@" $linker_opts
exit 1
}
eat=
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: compile [--help] [--version] PROGRAM [ARGS]
Wrapper for compilers which do not understand '-c -o'.
Remove '-o dest.o' from ARGS, run PROGRAM with the remaining
arguments, and rename the output as expected.
If you are trying to build a whole package this is not the
right script to run: please start by reading the file 'INSTALL'.
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "compile $scriptversion"
exit $?
;;
cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \
icl | *[/\\]icl | icl.exe | *[/\\]icl.exe )
func_cl_wrapper "$@" # Doesn't return...
;;
esac
ofile=
cfile=
for arg
do
if test -n "$eat"; then
eat=
else
case $1 in
-o)
# configure might choose to run compile as 'compile cc -o foo foo.c'.
# So we strip '-o arg' only if arg is an object.
eat=1
case $2 in
*.o | *.obj)
ofile=$2
;;
*)
set x "$@" -o "$2"
shift
;;
esac
;;
*.c)
cfile=$1
set x "$@" "$1"
shift
;;
*)
set x "$@" "$1"
shift
;;
esac
fi
shift
done
if test -z "$ofile" || test -z "$cfile"; then
# If no '-o' option was seen then we might have been invoked from a
# pattern rule where we don't need one. That is ok -- this is a
# normal compilation that the losing compiler can handle. If no
# '.c' file was seen then we are probably linking. That is also
# ok.
exec "$@"
fi
# Name of file we expect compiler to create.
cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
# Create the lock directory.
# Note: use '[/\\:.-]' here to ensure that we don't use the same name
# that we are using for the .o file. Also, base the name on the expected
# object file name, since that is what matters with a parallel build.
lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
while true; do
if mkdir "$lockdir" >/dev/null 2>&1; then
break
fi
sleep 1
done
# FIXME: race condition here if user kills between mkdir and trap.
trap "rmdir '$lockdir'; exit 1" 1 2 15
# Run the compile.
"$@"
ret=$?
if test -f "$cofile"; then
test "$cofile" = "$ofile" || mv "$cofile" "$ofile"
elif test -f "${cofile}bj"; then
test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile"
fi
rmdir "$lockdir"
exit $ret
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:

1667
objc/config.guess vendored

File diff suppressed because it is too large Load Diff

1793
objc/config.sub vendored

File diff suppressed because it is too large Load Diff

16076
objc/configure vendored

File diff suppressed because it is too large Load Diff

@ -0,0 +1,64 @@
# ffmpeg-kit 4.4 configure.ac
AC_INIT([ffmpeg-kit], [4.4], [https://github.com/tanersener/ffmpeg-kit/issues/new])
AC_CONFIG_SRCDIR([src/FFmpegKit.m])
AC_CONFIG_MACRO_DIR([m4])
AM_INIT_AUTOMAKE([-Wall -Werror foreign subdir-objects])
AM_MAINTAINER_MODE
# Check for os version
VERSION_OS=$(uname -s)
AC_DEFINE_UNQUOTED(VERSION_OS, "$VERSION_OS", [os version])
# Check host so we can infer target CPU (and assembly optimizations)
AC_CANONICAL_HOST
# Check for processor characteristics
AC_C_BIGENDIAN(AC_DEFINE([HIGHFIRST], [1], [big-endian machine]))
# Checks for programs.
cflags_bckup="$CFLAGS"
AC_PROG_CC
AM_PROG_AR
AC_PROG_OBJC
CFLAGS="$cflags_bckup"
FFMPEG_LIBS="-lavcodec -lavfilter -lavformat -lavutil -lswscale -lswresample"
AC_SUBST(FFMPEG_LIBS)
LT_INIT
# Checks for header files.
AC_CHECK_HEADERS([libavformat/avformat.h libavcodec/avcodec.h libavfilter/avfilter.h libavutil/avutil.h libswresample/swresample.h], [], [
AC_MSG_ERROR([unable to find ffmpeg headers])
])
AC_CHECK_HEADERS([fcntl.h limits.h stdint.h stdlib.h string.h sys/ioctl.h sys/time.h termios.h unistd.h])
AC_ARG_ENABLE([videotoolbox],
[ --enable-videotoolbox enable videotoolbox support],
[case "${enableval}" in
yes) videotoolbox=true ;;
no) videotoolbox=false ;;
*) AC_MSG_ERROR([bad value ${enableval} for --enable-videotoolbox]) ;;
esac],[videotoolbox=false])
AM_CONDITIONAL([FFMPEGKIT_VIDEOTOOLBOX], [test x$videotoolbox = xtrue])
# Checks for typedefs, structures, and compiler characteristics.
AC_C_INLINE
AC_TYPE_INT32_T
AC_TYPE_INT64_T
AC_TYPE_INT8_T
AC_TYPE_SIZE_T
AC_TYPE_UINT16_T
AC_TYPE_UINT32_T
AC_TYPE_UINT64_T
AC_TYPE_UINT8_T
# Checks for library functions.
AC_CHECK_FUNCS([dup2 floor memmove memset select strchr strcspn strerror strrchr strstr strtol malloc strcpy strlen vsnprintf])
AC_CONFIG_FILES([Makefile
src/Makefile])
AC_OUTPUT

@ -0,0 +1,791 @@
#! /bin/sh
# depcomp - compile a program generating dependencies as side-effects
scriptversion=2018-03-07.03; # UTC
# Copyright (C) 1999-2020 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
case $1 in
'')
echo "$0: No command. Try '$0 --help' for more information." 1>&2
exit 1;
;;
-h | --h*)
cat <<\EOF
Usage: depcomp [--help] [--version] PROGRAM [ARGS]
Run PROGRAMS ARGS to compile a file, generating dependencies
as side-effects.
Environment variables:
depmode Dependency tracking mode.
source Source file read by 'PROGRAMS ARGS'.
object Object file output by 'PROGRAMS ARGS'.
DEPDIR directory where to store dependencies.
depfile Dependency file to output.
tmpdepfile Temporary file to use when outputting dependencies.
libtool Whether libtool is used (yes/no).
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v | --v*)
echo "depcomp $scriptversion"
exit $?
;;
esac
# Get the directory component of the given path, and save it in the
# global variables '$dir'. Note that this directory component will
# be either empty or ending with a '/' character. This is deliberate.
set_dir_from ()
{
case $1 in
*/*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;;
*) dir=;;
esac
}
# Get the suffix-stripped basename of the given path, and save it the
# global variable '$base'.
set_base_from ()
{
base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'`
}
# If no dependency file was actually created by the compiler invocation,
# we still have to create a dummy depfile, to avoid errors with the
# Makefile "include basename.Plo" scheme.
make_dummy_depfile ()
{
echo "#dummy" > "$depfile"
}
# Factor out some common post-processing of the generated depfile.
# Requires the auxiliary global variable '$tmpdepfile' to be set.
aix_post_process_depfile ()
{
# If the compiler actually managed to produce a dependency file,
# post-process it.
if test -f "$tmpdepfile"; then
# Each line is of the form 'foo.o: dependency.h'.
# Do two passes, one to just change these to
# $object: dependency.h
# and one to simply output
# dependency.h:
# which is needed to avoid the deleted-header problem.
{ sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile"
sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile"
} > "$depfile"
rm -f "$tmpdepfile"
else
make_dummy_depfile
fi
}
# A tabulation character.
tab=' '
# A newline character.
nl='
'
# Character ranges might be problematic outside the C locale.
# These definitions help.
upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lower=abcdefghijklmnopqrstuvwxyz
digits=0123456789
alpha=${upper}${lower}
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
echo "depcomp: Variables source, object and depmode must be set" 1>&2
exit 1
fi
# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
depfile=${depfile-`echo "$object" |
sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
rm -f "$tmpdepfile"
# Avoid interferences from the environment.
gccflag= dashmflag=
# Some modes work just like other modes, but use different flags. We
# parameterize here, but still list the modes in the big case below,
# to make depend.m4 easier to write. Note that we *cannot* use a case
# here, because this file can only contain one case statement.
if test "$depmode" = hp; then
# HP compiler uses -M and no extra arg.
gccflag=-M
depmode=gcc
fi
if test "$depmode" = dashXmstdout; then
# This is just like dashmstdout with a different argument.
dashmflag=-xM
depmode=dashmstdout
fi
cygpath_u="cygpath -u -f -"
if test "$depmode" = msvcmsys; then
# This is just like msvisualcpp but w/o cygpath translation.
# Just convert the backslash-escaped backslashes to single forward
# slashes to satisfy depend.m4
cygpath_u='sed s,\\\\,/,g'
depmode=msvisualcpp
fi
if test "$depmode" = msvc7msys; then
# This is just like msvc7 but w/o cygpath translation.
# Just convert the backslash-escaped backslashes to single forward
# slashes to satisfy depend.m4
cygpath_u='sed s,\\\\,/,g'
depmode=msvc7
fi
if test "$depmode" = xlc; then
# IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information.
gccflag=-qmakedep=gcc,-MF
depmode=gcc
fi
case "$depmode" in
gcc3)
## gcc 3 implements dependency tracking that does exactly what
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
## it if -MD -MP comes after the -MF stuff. Hmm.
## Unfortunately, FreeBSD c89 acceptance of flags depends upon
## the command line argument order; so add the flags where they
## appear in depend2.am. Note that the slowdown incurred here
## affects only configure: in makefiles, %FASTDEP% shortcuts this.
for arg
do
case $arg in
-c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
*) set fnord "$@" "$arg" ;;
esac
shift # fnord
shift # $arg
done
"$@"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
mv "$tmpdepfile" "$depfile"
;;
gcc)
## Note that this doesn't just cater to obsosete pre-3.x GCC compilers.
## but also to in-use compilers like IMB xlc/xlC and the HP C compiler.
## (see the conditional assignment to $gccflag above).
## There are various ways to get dependency output from gcc. Here's
## why we pick this rather obscure method:
## - Don't want to use -MD because we'd like the dependencies to end
## up in a subdir. Having to rename by hand is ugly.
## (We might end up doing this anyway to support other compilers.)
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
## -MM, not -M (despite what the docs say). Also, it might not be
## supported by the other compilers which use the 'gcc' depmode.
## - Using -M directly means running the compiler twice (even worse
## than renaming).
if test -z "$gccflag"; then
gccflag=-MD,
fi
"$@" -Wp,"$gccflag$tmpdepfile"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
# The second -e expression handles DOS-style file names with drive
# letters.
sed -e 's/^[^:]*: / /' \
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
## This next piece of magic avoids the "deleted header file" problem.
## The problem is that when a header file which appears in a .P file
## is deleted, the dependency causes make to die (because there is
## typically no way to rebuild the header). We avoid this by adding
## dummy dependencies for each header file. Too bad gcc doesn't do
## this for us directly.
## Some versions of gcc put a space before the ':'. On the theory
## that the space means something, we add a space to the output as
## well. hp depmode also adds that space, but also prefixes the VPATH
## to the object. Take care to not repeat it in the output.
## Some versions of the HPUX 10.20 sed can't process this invocation
## correctly. Breaking it into two sed invocations is a workaround.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
sgi)
if test "$libtool" = yes; then
"$@" "-Wp,-MDupdate,$tmpdepfile"
else
"$@" -MDupdate "$tmpdepfile"
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
echo "$object : \\" > "$depfile"
# Clip off the initial element (the dependent). Don't try to be
# clever and replace this with sed code, as IRIX sed won't handle
# lines with more than a fixed number of characters (4096 in
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
# the IRIX cc adds comments like '#:fec' to the end of the
# dependency line.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \
| tr "$nl" ' ' >> "$depfile"
echo >> "$depfile"
# The second pass generates a dummy entry for each header file.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
>> "$depfile"
else
make_dummy_depfile
fi
rm -f "$tmpdepfile"
;;
xlc)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
aix)
# The C for AIX Compiler uses -M and outputs the dependencies
# in a .u file. In older versions, this file always lives in the
# current directory. Also, the AIX compiler puts '$object:' at the
# start of each line; $object doesn't have directory information.
# Version 6 uses the directory in both cases.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.u
tmpdepfile2=$base.u
tmpdepfile3=$dir.libs/$base.u
"$@" -Wc,-M
else
tmpdepfile1=$dir$base.u
tmpdepfile2=$dir$base.u
tmpdepfile3=$dir$base.u
"$@" -M
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
aix_post_process_depfile
;;
tcc)
# tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26
# FIXME: That version still under development at the moment of writing.
# Make that this statement remains true also for stable, released
# versions.
# It will wrap lines (doesn't matter whether long or short) with a
# trailing '\', as in:
#
# foo.o : \
# foo.c \
# foo.h \
#
# It will put a trailing '\' even on the last line, and will use leading
# spaces rather than leading tabs (at least since its commit 0394caf7
# "Emit spaces for -MD").
"$@" -MD -MF "$tmpdepfile"
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each non-empty line is of the form 'foo.o : \' or ' dep.h \'.
# We have to change lines of the first kind to '$object: \'.
sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile"
# And for each line of the second kind, we have to emit a 'dep.h:'
# dummy dependency, to avoid the deleted-header problem.
sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile"
rm -f "$tmpdepfile"
;;
## The order of this option in the case statement is important, since the
## shell code in configure will try each of these formats in the order
## listed in this file. A plain '-MD' option would be understood by many
## compilers, so we must ensure this comes after the gcc and icc options.
pgcc)
# Portland's C compiler understands '-MD'.
# Will always output deps to 'file.d' where file is the root name of the
# source file under compilation, even if file resides in a subdirectory.
# The object file name does not affect the name of the '.d' file.
# pgcc 10.2 will output
# foo.o: sub/foo.c sub/foo.h
# and will wrap long lines using '\' :
# foo.o: sub/foo.c ... \
# sub/foo.h ... \
# ...
set_dir_from "$object"
# Use the source, not the object, to determine the base name, since
# that's sadly what pgcc will do too.
set_base_from "$source"
tmpdepfile=$base.d
# For projects that build the same source file twice into different object
# files, the pgcc approach of using the *source* file root name can cause
# problems in parallel builds. Use a locking strategy to avoid stomping on
# the same $tmpdepfile.
lockdir=$base.d-lock
trap "
echo '$0: caught signal, cleaning up...' >&2
rmdir '$lockdir'
exit 1
" 1 2 13 15
numtries=100
i=$numtries
while test $i -gt 0; do
# mkdir is a portable test-and-set.
if mkdir "$lockdir" 2>/dev/null; then
# This process acquired the lock.
"$@" -MD
stat=$?
# Release the lock.
rmdir "$lockdir"
break
else
# If the lock is being held by a different process, wait
# until the winning process is done or we timeout.
while test -d "$lockdir" && test $i -gt 0; do
sleep 1
i=`expr $i - 1`
done
fi
i=`expr $i - 1`
done
trap - 1 2 13 15
if test $i -le 0; then
echo "$0: failed to acquire lock after $numtries attempts" >&2
echo "$0: check lockdir '$lockdir'" >&2
exit 1
fi
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
# Each line is of the form `foo.o: dependent.h',
# or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
# Do two passes, one to just change these to
# `$object: dependent.h' and one to simply `dependent.h:'.
sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
hp2)
# The "hp" stanza above does not work with aCC (C++) and HP's ia64
# compilers, which have integrated preprocessors. The correct option
# to use with these is +Maked; it writes dependencies to a file named
# 'foo.d', which lands next to the object file, wherever that
# happens to be.
# Much of this is similar to the tru64 case; see comments there.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir.libs/$base.d
"$@" -Wc,+Maked
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
"$@" +Maked
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
do
test -f "$tmpdepfile" && break
done
if test -f "$tmpdepfile"; then
sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile"
# Add 'dependent.h:' lines.
sed -ne '2,${
s/^ *//
s/ \\*$//
s/$/:/
p
}' "$tmpdepfile" >> "$depfile"
else
make_dummy_depfile
fi
rm -f "$tmpdepfile" "$tmpdepfile2"
;;
tru64)
# The Tru64 compiler uses -MD to generate dependencies as a side
# effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'.
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
# dependencies in 'foo.d' instead, so we check for that too.
# Subdirectories are respected.
set_dir_from "$object"
set_base_from "$object"
if test "$libtool" = yes; then
# Libtool generates 2 separate objects for the 2 libraries. These
# two compilations output dependencies in $dir.libs/$base.o.d and
# in $dir$base.o.d. We have to check for both files, because
# one of the two compilations can be disabled. We should prefer
# $dir$base.o.d over $dir.libs/$base.o.d because the latter is
# automatically cleaned when .libs/ is deleted, while ignoring
# the former would cause a distcleancheck panic.
tmpdepfile1=$dir$base.o.d # libtool 1.5
tmpdepfile2=$dir.libs/$base.o.d # Likewise.
tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504
"$@" -Wc,-MD
else
tmpdepfile1=$dir$base.d
tmpdepfile2=$dir$base.d
tmpdepfile3=$dir$base.d
"$@" -MD
fi
stat=$?
if test $stat -ne 0; then
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
exit $stat
fi
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
do
test -f "$tmpdepfile" && break
done
# Same post-processing that is required for AIX mode.
aix_post_process_depfile
;;
msvc7)
if test "$libtool" = yes; then
showIncludes=-Wc,-showIncludes
else
showIncludes=-showIncludes
fi
"$@" $showIncludes > "$tmpdepfile"
stat=$?
grep -v '^Note: including file: ' "$tmpdepfile"
if test $stat -ne 0; then
rm -f "$tmpdepfile"
exit $stat
fi
rm -f "$depfile"
echo "$object : \\" > "$depfile"
# The first sed program below extracts the file names and escapes
# backslashes for cygpath. The second sed program outputs the file
# name when reading, but also accumulates all include files in the
# hold buffer in order to output them again at the end. This only
# works with sed implementations that can handle large buffers.
sed < "$tmpdepfile" -n '
/^Note: including file: *\(.*\)/ {
s//\1/
s/\\/\\\\/g
p
}' | $cygpath_u | sort -u | sed -n '
s/ /\\ /g
s/\(.*\)/'"$tab"'\1 \\/p
s/.\(.*\) \\/\1:/
H
$ {
s/.*/'"$tab"'/
G
p
}' >> "$depfile"
echo >> "$depfile" # make sure the fragment doesn't end with a backslash
rm -f "$tmpdepfile"
;;
msvc7msys)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
#nosideeffect)
# This comment above is used by automake to tell side-effect
# dependency tracking mechanisms from slower ones.
dashmstdout)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout, regardless of -o.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# Remove '-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
test -z "$dashmflag" && dashmflag=-M
# Require at least two characters before searching for ':'
# in the target name. This is to cope with DOS-style filenames:
# a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise.
"$@" $dashmflag |
sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile"
rm -f "$depfile"
cat < "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process this sed invocation
# correctly. Breaking it into two sed invocations is a workaround.
tr ' ' "$nl" < "$tmpdepfile" \
| sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
dashXmstdout)
# This case only exists to satisfy depend.m4. It is never actually
# run, as this mode is specially recognized in the preamble.
exit 1
;;
makedepend)
"$@" || exit $?
# Remove any Libtool call
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# X makedepend
shift
cleared=no eat=no
for arg
do
case $cleared in
no)
set ""; shift
cleared=yes ;;
esac
if test $eat = yes; then
eat=no
continue
fi
case "$arg" in
-D*|-I*)
set fnord "$@" "$arg"; shift ;;
# Strip any option that makedepend may not understand. Remove
# the object too, otherwise makedepend will parse it as a source file.
-arch)
eat=yes ;;
-*|$object)
;;
*)
set fnord "$@" "$arg"; shift ;;
esac
done
obj_suffix=`echo "$object" | sed 's/^.*\././'`
touch "$tmpdepfile"
${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
rm -f "$depfile"
# makedepend may prepend the VPATH from the source file name to the object.
# No need to regex-escape $object, excess matching of '.' is harmless.
sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile"
# Some versions of the HPUX 10.20 sed can't process the last invocation
# correctly. Breaking it into two sed invocations is a workaround.
sed '1,2d' "$tmpdepfile" \
| tr ' ' "$nl" \
| sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \
| sed -e 's/$/ :/' >> "$depfile"
rm -f "$tmpdepfile" "$tmpdepfile".bak
;;
cpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
# Remove '-o $object'.
IFS=" "
for arg
do
case $arg in
-o)
shift
;;
$object)
shift
;;
*)
set fnord "$@" "$arg"
shift # fnord
shift # $arg
;;
esac
done
"$@" -E \
| sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
-e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
| sed '$ s: \\$::' > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
cat < "$tmpdepfile" >> "$depfile"
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvisualcpp)
# Important note: in order to support this mode, a compiler *must*
# always write the preprocessed file to stdout.
"$@" || exit $?
# Remove the call to Libtool.
if test "$libtool" = yes; then
while test "X$1" != 'X--mode=compile'; do
shift
done
shift
fi
IFS=" "
for arg
do
case "$arg" in
-o)
shift
;;
$object)
shift
;;
"-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
set fnord "$@"
shift
shift
;;
*)
set fnord "$@" "$arg"
shift
shift
;;
esac
done
"$@" -E 2>/dev/null |
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
rm -f "$depfile"
echo "$object : \\" > "$depfile"
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile"
echo "$tab" >> "$depfile"
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
rm -f "$tmpdepfile"
;;
msvcmsys)
# This case exists only to let depend.m4 do its work. It works by
# looking at the text of this script. This case will never be run,
# since it is checked for above.
exit 1
;;
none)
exec "$@"
;;
*)
echo "Unknown depmode $depmode" 1>&2
exit 1
;;
esac
exit 0
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:

@ -0,0 +1,529 @@
#!/bin/sh
# install - install a program, script, or datafile
scriptversion=2018-03-11.20; # UTC
# This originates from X11R5 (mit/util/scripts/install.sh), which was
# later released in X11R6 (xc/config/util/install.sh) with the
# following copyright and license.
#
# Copyright (C) 1994 X Consortium
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of the X Consortium shall not
# be used in advertising or otherwise to promote the sale, use or other deal-
# ings in this Software without prior written authorization from the X Consor-
# tium.
#
#
# FSF changes to this file are in the public domain.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# 'make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.
tab=' '
nl='
'
IFS=" $tab$nl"
# Set DOITPROG to "echo" to test this script.
doit=${DOITPROG-}
doit_exec=${doit:-exec}
# Put in absolute file names if you don't have them in your path;
# or use environment vars.
chgrpprog=${CHGRPPROG-chgrp}
chmodprog=${CHMODPROG-chmod}
chownprog=${CHOWNPROG-chown}
cmpprog=${CMPPROG-cmp}
cpprog=${CPPROG-cp}
mkdirprog=${MKDIRPROG-mkdir}
mvprog=${MVPROG-mv}
rmprog=${RMPROG-rm}
stripprog=${STRIPPROG-strip}
posix_mkdir=
# Desired mode of installed file.
mode=0755
chgrpcmd=
chmodcmd=$chmodprog
chowncmd=
mvcmd=$mvprog
rmcmd="$rmprog -f"
stripcmd=
src=
dst=
dir_arg=
dst_arg=
copy_on_change=false
is_target_a_directory=possibly
usage="\
Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
or: $0 [OPTION]... SRCFILES... DIRECTORY
or: $0 [OPTION]... -t DIRECTORY SRCFILES...
or: $0 [OPTION]... -d DIRECTORIES...
In the 1st form, copy SRCFILE to DSTFILE.
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
In the 4th, create DIRECTORIES.
Options:
--help display this help and exit.
--version display version info and exit.
-c (ignored)
-C install only if different (preserve the last data modification time)
-d create directories instead of installing files.
-g GROUP $chgrpprog installed files to GROUP.
-m MODE $chmodprog installed files to MODE.
-o USER $chownprog installed files to USER.
-s $stripprog installed files.
-t DIRECTORY install into DIRECTORY.
-T report an error if DSTFILE is a directory.
Environment variables override the default commands:
CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
RMPROG STRIPPROG
"
while test $# -ne 0; do
case $1 in
-c) ;;
-C) copy_on_change=true;;
-d) dir_arg=true;;
-g) chgrpcmd="$chgrpprog $2"
shift;;
--help) echo "$usage"; exit $?;;
-m) mode=$2
case $mode in
*' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
echo "$0: invalid mode: $mode" >&2
exit 1;;
esac
shift;;
-o) chowncmd="$chownprog $2"
shift;;
-s) stripcmd=$stripprog;;
-t)
is_target_a_directory=always
dst_arg=$2
# Protect names problematic for 'test' and other utilities.
case $dst_arg in
-* | [=\(\)!]) dst_arg=./$dst_arg;;
esac
shift;;
-T) is_target_a_directory=never;;
--version) echo "$0 $scriptversion"; exit $?;;
--) shift
break;;
-*) echo "$0: invalid option: $1" >&2
exit 1;;
*) break;;
esac
shift
done
# We allow the use of options -d and -T together, by making -d
# take the precedence; this is for compatibility with GNU install.
if test -n "$dir_arg"; then
if test -n "$dst_arg"; then
echo "$0: target directory not allowed when installing a directory." >&2
exit 1
fi
fi
if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
# When -d is used, all remaining arguments are directories to create.
# When -t is used, the destination is already specified.
# Otherwise, the last argument is the destination. Remove it from $@.
for arg
do
if test -n "$dst_arg"; then
# $@ is not empty: it contains at least $arg.
set fnord "$@" "$dst_arg"
shift # fnord
fi
shift # arg
dst_arg=$arg
# Protect names problematic for 'test' and other utilities.
case $dst_arg in
-* | [=\(\)!]) dst_arg=./$dst_arg;;
esac
done
fi
if test $# -eq 0; then
if test -z "$dir_arg"; then
echo "$0: no input file specified." >&2
exit 1
fi
# It's OK to call 'install-sh -d' without argument.
# This can happen when creating conditional directories.
exit 0
fi
if test -z "$dir_arg"; then
if test $# -gt 1 || test "$is_target_a_directory" = always; then
if test ! -d "$dst_arg"; then
echo "$0: $dst_arg: Is not a directory." >&2
exit 1
fi
fi
fi
if test -z "$dir_arg"; then
do_exit='(exit $ret); exit $ret'
trap "ret=129; $do_exit" 1
trap "ret=130; $do_exit" 2
trap "ret=141; $do_exit" 13
trap "ret=143; $do_exit" 15
# Set umask so as not to create temps with too-generous modes.
# However, 'strip' requires both read and write access to temps.
case $mode in
# Optimize common cases.
*644) cp_umask=133;;
*755) cp_umask=22;;
*[0-7])
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw='% 200'
fi
cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
*)
if test -z "$stripcmd"; then
u_plus_rw=
else
u_plus_rw=,u+rw
fi
cp_umask=$mode$u_plus_rw;;
esac
fi
for src
do
# Protect names problematic for 'test' and other utilities.
case $src in
-* | [=\(\)!]) src=./$src;;
esac
if test -n "$dir_arg"; then
dst=$src
dstdir=$dst
test -d "$dstdir"
dstdir_status=$?
else
# Waiting for this to be detected by the "$cpprog $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if test ! -f "$src" && test ! -d "$src"; then
echo "$0: $src does not exist." >&2
exit 1
fi
if test -z "$dst_arg"; then
echo "$0: no destination specified." >&2
exit 1
fi
dst=$dst_arg
# If destination is a directory, append the input filename.
if test -d "$dst"; then
if test "$is_target_a_directory" = never; then
echo "$0: $dst_arg: Is a directory" >&2
exit 1
fi
dstdir=$dst
dstbase=`basename "$src"`
case $dst in
*/) dst=$dst$dstbase;;
*) dst=$dst/$dstbase;;
esac
dstdir_status=0
else
dstdir=`dirname "$dst"`
test -d "$dstdir"
dstdir_status=$?
fi
fi
case $dstdir in
*/) dstdirslash=$dstdir;;
*) dstdirslash=$dstdir/;;
esac
obsolete_mkdir_used=false
if test $dstdir_status != 0; then
case $posix_mkdir in
'')
# Create intermediate dirs using mode 755 as modified by the umask.
# This is like FreeBSD 'install' as of 1997-10-28.
umask=`umask`
case $stripcmd.$umask in
# Optimize common cases.
*[2367][2367]) mkdir_umask=$umask;;
.*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
*[0-7])
mkdir_umask=`expr $umask + 22 \
- $umask % 100 % 40 + $umask % 20 \
- $umask % 10 % 4 + $umask % 2
`;;
*) mkdir_umask=$umask,go-w;;
esac
# With -d, create the new directory with the user-specified mode.
# Otherwise, rely on $mkdir_umask.
if test -n "$dir_arg"; then
mkdir_mode=-m$mode
else
mkdir_mode=
fi
posix_mkdir=false
case $umask in
*[123567][0-7][0-7])
# POSIX mkdir -p sets u+wx bits regardless of umask, which
# is incompatible with FreeBSD 'install' when (umask & 300) != 0.
;;
*)
# Note that $RANDOM variable is not portable (e.g. dash); Use it
# here however when possible just to lower collision chance.
tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
trap 'ret=$?; rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null; exit $ret' 0
# Because "mkdir -p" follows existing symlinks and we likely work
# directly in world-writeable /tmp, make sure that the '$tmpdir'
# directory is successfully created first before we actually test
# 'mkdir -p' feature.
if (umask $mkdir_umask &&
$mkdirprog $mkdir_mode "$tmpdir" &&
exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
then
if test -z "$dir_arg" || {
# Check for POSIX incompatibilities with -m.
# HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
# other-writable bit of parent directory when it shouldn't.
# FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
test_tmpdir="$tmpdir/a"
ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
case $ls_ld_tmpdir in
d????-?r-*) different_mode=700;;
d????-?--*) different_mode=755;;
*) false;;
esac &&
$mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
}
}
then posix_mkdir=:
fi
rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
else
# Remove any dirs left behind by ancient mkdir implementations.
rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
fi
trap '' 0;;
esac;;
esac
if
$posix_mkdir && (
umask $mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
)
then :
else
# The umask is ridiculous, or mkdir does not conform to POSIX,
# or it failed possibly due to a race condition. Create the
# directory the slow way, step by step, checking for races as we go.
case $dstdir in
/*) prefix='/';;
[-=\(\)!]*) prefix='./';;
*) prefix='';;
esac
oIFS=$IFS
IFS=/
set -f
set fnord $dstdir
shift
set +f
IFS=$oIFS
prefixes=
for d
do
test X"$d" = X && continue
prefix=$prefix$d
if test -d "$prefix"; then
prefixes=
else
if $posix_mkdir; then
(umask=$mkdir_umask &&
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
# Don't fail if two instances are running concurrently.
test -d "$prefix" || exit 1
else
case $prefix in
*\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
*) qprefix=$prefix;;
esac
prefixes="$prefixes '$qprefix'"
fi
fi
prefix=$prefix/
done
if test -n "$prefixes"; then
# Don't fail if two instances are running concurrently.
(umask $mkdir_umask &&
eval "\$doit_exec \$mkdirprog $prefixes") ||
test -d "$dstdir" || exit 1
obsolete_mkdir_used=true
fi
fi
fi
if test -n "$dir_arg"; then
{ test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
{ test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
else
# Make a couple of temp file names in the proper directory.
dsttmp=${dstdirslash}_inst.$$_
rmtmp=${dstdirslash}_rm.$$_
# Trap to clean up those temp files at exit.
trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
# Copy the file name to the temp name.
(umask $cp_umask &&
{ test -z "$stripcmd" || {
# Create $dsttmp read-write so that cp doesn't create it read-only,
# which would cause strip to fail.
if test -z "$doit"; then
: >"$dsttmp" # No need to fork-exec 'touch'.
else
$doit touch "$dsttmp"
fi
}
} &&
$doit_exec $cpprog "$src" "$dsttmp") &&
# and set any options; do chmod last to preserve setuid bits.
#
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $cpprog $src $dsttmp" command.
#
{ test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
{ test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
{ test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
# If -C, don't bother to copy if it wouldn't change the file.
if $copy_on_change &&
old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` &&
new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
set -f &&
set X $old && old=:$2:$4:$5:$6 &&
set X $new && new=:$2:$4:$5:$6 &&
set +f &&
test "$old" = "$new" &&
$cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
then
rm -f "$dsttmp"
else
# Rename the file to the real destination.
$doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
# The rename failed, perhaps because mv can't rename something else
# to itself, or perhaps because mv is so ancient that it does not
# support -f.
{
# Now remove or move aside any old file at destination location.
# We try this two ways since rm can't unlink itself on some
# systems and the destination file might be busy for other
# reasons. In this case, the final cleanup might fail but the new
# file should still install successfully.
{
test ! -f "$dst" ||
$doit $rmcmd -f "$dst" 2>/dev/null ||
{ $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
{ $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
} ||
{ echo "$0: cannot unlink or rename $dst" >&2
(exit 1); exit 1
}
} &&
# Now rename the file to the real destination.
$doit $mvcmd "$dsttmp" "$dst"
}
fi || exit 1
trap '' 0
fi
done
# Local variables:
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

8364
objc/m4/libtool.m4 vendored

File diff suppressed because it is too large Load Diff

437
objc/m4/ltoptions.m4 vendored

@ -0,0 +1,437 @@
# Helper functions for option handling. -*- Autoconf -*-
#
# Copyright (C) 2004-2005, 2007-2009, 2011-2015 Free Software
# Foundation, Inc.
# Written by Gary V. Vaughan, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 8 ltoptions.m4
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])])
# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME)
# ------------------------------------------
m4_define([_LT_MANGLE_OPTION],
[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])])
# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME)
# ---------------------------------------
# Set option OPTION-NAME for macro MACRO-NAME, and if there is a
# matching handler defined, dispatch to it. Other OPTION-NAMEs are
# saved as a flag.
m4_define([_LT_SET_OPTION],
[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl
m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]),
_LT_MANGLE_DEFUN([$1], [$2]),
[m4_warning([Unknown $1 option '$2'])])[]dnl
])
# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET])
# ------------------------------------------------------------
# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise.
m4_define([_LT_IF_OPTION],
[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])])
# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET)
# -------------------------------------------------------
# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME
# are set.
m4_define([_LT_UNLESS_OPTIONS],
[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
[m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option),
[m4_define([$0_found])])])[]dnl
m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3
])[]dnl
])
# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST)
# ----------------------------------------
# OPTION-LIST is a space-separated list of Libtool options associated
# with MACRO-NAME. If any OPTION has a matching handler declared with
# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about
# the unknown option and exit.
m4_defun([_LT_SET_OPTIONS],
[# Set options
m4_foreach([_LT_Option], m4_split(m4_normalize([$2])),
[_LT_SET_OPTION([$1], _LT_Option)])
m4_if([$1],[LT_INIT],[
dnl
dnl Simply set some default values (i.e off) if boolean options were not
dnl specified:
_LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no
])
_LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no
])
dnl
dnl If no reference was made to various pairs of opposing options, then
dnl we run the default mode handler for the pair. For example, if neither
dnl 'shared' nor 'disable-shared' was passed, we enable building of shared
dnl archives by default:
_LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED])
_LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC])
_LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC])
_LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install],
[_LT_ENABLE_FAST_INSTALL])
_LT_UNLESS_OPTIONS([LT_INIT], [aix-soname=aix aix-soname=both aix-soname=svr4],
[_LT_WITH_AIX_SONAME([aix])])
])
])# _LT_SET_OPTIONS
## --------------------------------- ##
## Macros to handle LT_INIT options. ##
## --------------------------------- ##
# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME)
# -----------------------------------------
m4_define([_LT_MANGLE_DEFUN],
[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])])
# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE)
# -----------------------------------------------
m4_define([LT_OPTION_DEFINE],
[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl
])# LT_OPTION_DEFINE
# dlopen
# ------
LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes
])
AU_DEFUN([AC_LIBTOOL_DLOPEN],
[_LT_SET_OPTION([LT_INIT], [dlopen])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the 'dlopen' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], [])
# win32-dll
# ---------
# Declare package support for building win32 dll's.
LT_OPTION_DEFINE([LT_INIT], [win32-dll],
[enable_win32_dll=yes
case $host in
*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*)
AC_CHECK_TOOL(AS, as, false)
AC_CHECK_TOOL(DLLTOOL, dlltool, false)
AC_CHECK_TOOL(OBJDUMP, objdump, false)
;;
esac
test -z "$AS" && AS=as
_LT_DECL([], [AS], [1], [Assembler program])dnl
test -z "$DLLTOOL" && DLLTOOL=dlltool
_LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl
test -z "$OBJDUMP" && OBJDUMP=objdump
_LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl
])# win32-dll
AU_DEFUN([AC_LIBTOOL_WIN32_DLL],
[AC_REQUIRE([AC_CANONICAL_HOST])dnl
_LT_SET_OPTION([LT_INIT], [win32-dll])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the 'win32-dll' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], [])
# _LT_ENABLE_SHARED([DEFAULT])
# ----------------------------
# implement the --enable-shared flag, and supports the 'shared' and
# 'disable-shared' LT_INIT options.
# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'.
m4_define([_LT_ENABLE_SHARED],
[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([shared],
[AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@],
[build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])],
[p=${PACKAGE-default}
case $enableval in
yes) enable_shared=yes ;;
no) enable_shared=no ;;
*)
enable_shared=no
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$pkg" = "X$p"; then
enable_shared=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[enable_shared=]_LT_ENABLE_SHARED_DEFAULT)
_LT_DECL([build_libtool_libs], [enable_shared], [0],
[Whether or not to build shared libraries])
])# _LT_ENABLE_SHARED
LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])])
# Old names:
AC_DEFUN([AC_ENABLE_SHARED],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared])
])
AC_DEFUN([AC_DISABLE_SHARED],
[_LT_SET_OPTION([LT_INIT], [disable-shared])
])
AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)])
AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_ENABLE_SHARED], [])
dnl AC_DEFUN([AM_DISABLE_SHARED], [])
# _LT_ENABLE_STATIC([DEFAULT])
# ----------------------------
# implement the --enable-static flag, and support the 'static' and
# 'disable-static' LT_INIT options.
# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'.
m4_define([_LT_ENABLE_STATIC],
[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([static],
[AS_HELP_STRING([--enable-static@<:@=PKGS@:>@],
[build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])],
[p=${PACKAGE-default}
case $enableval in
yes) enable_static=yes ;;
no) enable_static=no ;;
*)
enable_static=no
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$pkg" = "X$p"; then
enable_static=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[enable_static=]_LT_ENABLE_STATIC_DEFAULT)
_LT_DECL([build_old_libs], [enable_static], [0],
[Whether or not to build static libraries])
])# _LT_ENABLE_STATIC
LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])])
# Old names:
AC_DEFUN([AC_ENABLE_STATIC],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static])
])
AC_DEFUN([AC_DISABLE_STATIC],
[_LT_SET_OPTION([LT_INIT], [disable-static])
])
AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)])
AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AM_ENABLE_STATIC], [])
dnl AC_DEFUN([AM_DISABLE_STATIC], [])
# _LT_ENABLE_FAST_INSTALL([DEFAULT])
# ----------------------------------
# implement the --enable-fast-install flag, and support the 'fast-install'
# and 'disable-fast-install' LT_INIT options.
# DEFAULT is either 'yes' or 'no'. If omitted, it defaults to 'yes'.
m4_define([_LT_ENABLE_FAST_INSTALL],
[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl
AC_ARG_ENABLE([fast-install],
[AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@],
[optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])],
[p=${PACKAGE-default}
case $enableval in
yes) enable_fast_install=yes ;;
no) enable_fast_install=no ;;
*)
enable_fast_install=no
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for pkg in $enableval; do
IFS=$lt_save_ifs
if test "X$pkg" = "X$p"; then
enable_fast_install=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT)
_LT_DECL([fast_install], [enable_fast_install], [0],
[Whether or not to optimize for fast installation])dnl
])# _LT_ENABLE_FAST_INSTALL
LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])])
LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])])
# Old names:
AU_DEFUN([AC_ENABLE_FAST_INSTALL],
[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you put
the 'fast-install' option into LT_INIT's first parameter.])
])
AU_DEFUN([AC_DISABLE_FAST_INSTALL],
[_LT_SET_OPTION([LT_INIT], [disable-fast-install])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you put
the 'disable-fast-install' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], [])
dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], [])
# _LT_WITH_AIX_SONAME([DEFAULT])
# ----------------------------------
# implement the --with-aix-soname flag, and support the `aix-soname=aix'
# and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. DEFAULT
# is either `aix', `both' or `svr4'. If omitted, it defaults to `aix'.
m4_define([_LT_WITH_AIX_SONAME],
[m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl
shared_archive_member_spec=
case $host,$enable_shared in
power*-*-aix[[5-9]]*,yes)
AC_MSG_CHECKING([which variant of shared library versioning to provide])
AC_ARG_WITH([aix-soname],
[AS_HELP_STRING([--with-aix-soname=aix|svr4|both],
[shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])],
[case $withval in
aix|svr4|both)
;;
*)
AC_MSG_ERROR([Unknown argument to --with-aix-soname])
;;
esac
lt_cv_with_aix_soname=$with_aix_soname],
[AC_CACHE_VAL([lt_cv_with_aix_soname],
[lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT)
with_aix_soname=$lt_cv_with_aix_soname])
AC_MSG_RESULT([$with_aix_soname])
if test aix != "$with_aix_soname"; then
# For the AIX way of multilib, we name the shared archive member
# based on the bitwidth used, traditionally 'shr.o' or 'shr_64.o',
# and 'shr.imp' or 'shr_64.imp', respectively, for the Import File.
# Even when GNU compilers ignore OBJECT_MODE but need '-maix64' flag,
# the AIX toolchain works better with OBJECT_MODE set (default 32).
if test 64 = "${OBJECT_MODE-32}"; then
shared_archive_member_spec=shr_64
else
shared_archive_member_spec=shr
fi
fi
;;
*)
with_aix_soname=aix
;;
esac
_LT_DECL([], [shared_archive_member_spec], [0],
[Shared archive member basename, for filename based shared library versioning on AIX])dnl
])# _LT_WITH_AIX_SONAME
LT_OPTION_DEFINE([LT_INIT], [aix-soname=aix], [_LT_WITH_AIX_SONAME([aix])])
LT_OPTION_DEFINE([LT_INIT], [aix-soname=both], [_LT_WITH_AIX_SONAME([both])])
LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])])
# _LT_WITH_PIC([MODE])
# --------------------
# implement the --with-pic flag, and support the 'pic-only' and 'no-pic'
# LT_INIT options.
# MODE is either 'yes' or 'no'. If omitted, it defaults to 'both'.
m4_define([_LT_WITH_PIC],
[AC_ARG_WITH([pic],
[AS_HELP_STRING([--with-pic@<:@=PKGS@:>@],
[try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
[lt_p=${PACKAGE-default}
case $withval in
yes|no) pic_mode=$withval ;;
*)
pic_mode=default
# Look at the argument we got. We use all the common list separators.
lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR,
for lt_pkg in $withval; do
IFS=$lt_save_ifs
if test "X$lt_pkg" = "X$lt_p"; then
pic_mode=yes
fi
done
IFS=$lt_save_ifs
;;
esac],
[pic_mode=m4_default([$1], [default])])
_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl
])# _LT_WITH_PIC
LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])])
LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])])
# Old name:
AU_DEFUN([AC_LIBTOOL_PICMODE],
[_LT_SET_OPTION([LT_INIT], [pic-only])
AC_DIAGNOSE([obsolete],
[$0: Remove this warning and the call to _LT_SET_OPTION when you
put the 'pic-only' option into LT_INIT's first parameter.])
])
dnl aclocal-1.4 backwards compatibility:
dnl AC_DEFUN([AC_LIBTOOL_PICMODE], [])
## ----------------- ##
## LTDL_INIT Options ##
## ----------------- ##
m4_define([_LTDL_MODE], [])
LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive],
[m4_define([_LTDL_MODE], [nonrecursive])])
LT_OPTION_DEFINE([LTDL_INIT], [recursive],
[m4_define([_LTDL_MODE], [recursive])])
LT_OPTION_DEFINE([LTDL_INIT], [subproject],
[m4_define([_LTDL_MODE], [subproject])])
m4_define([_LTDL_TYPE], [])
LT_OPTION_DEFINE([LTDL_INIT], [installable],
[m4_define([_LTDL_TYPE], [installable])])
LT_OPTION_DEFINE([LTDL_INIT], [convenience],
[m4_define([_LTDL_TYPE], [convenience])])

124
objc/m4/ltsugar.m4 vendored

@ -0,0 +1,124 @@
# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*-
#
# Copyright (C) 2004-2005, 2007-2008, 2011-2015 Free Software
# Foundation, Inc.
# Written by Gary V. Vaughan, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 6 ltsugar.m4
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])])
# lt_join(SEP, ARG1, [ARG2...])
# -----------------------------
# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their
# associated separator.
# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier
# versions in m4sugar had bugs.
m4_define([lt_join],
[m4_if([$#], [1], [],
[$#], [2], [[$2]],
[m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])])
m4_define([_lt_join],
[m4_if([$#$2], [2], [],
[m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])])
# lt_car(LIST)
# lt_cdr(LIST)
# ------------
# Manipulate m4 lists.
# These macros are necessary as long as will still need to support
# Autoconf-2.59, which quotes differently.
m4_define([lt_car], [[$1]])
m4_define([lt_cdr],
[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])],
[$#], 1, [],
[m4_dquote(m4_shift($@))])])
m4_define([lt_unquote], $1)
# lt_append(MACRO-NAME, STRING, [SEPARATOR])
# ------------------------------------------
# Redefine MACRO-NAME to hold its former content plus 'SEPARATOR''STRING'.
# Note that neither SEPARATOR nor STRING are expanded; they are appended
# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked).
# No SEPARATOR is output if MACRO-NAME was previously undefined (different
# than defined and empty).
#
# This macro is needed until we can rely on Autoconf 2.62, since earlier
# versions of m4sugar mistakenly expanded SEPARATOR but not STRING.
m4_define([lt_append],
[m4_define([$1],
m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])])
# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...])
# ----------------------------------------------------------
# Produce a SEP delimited list of all paired combinations of elements of
# PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list
# has the form PREFIXmINFIXSUFFIXn.
# Needed until we can rely on m4_combine added in Autoconf 2.62.
m4_define([lt_combine],
[m4_if(m4_eval([$# > 3]), [1],
[m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl
[[m4_foreach([_Lt_prefix], [$2],
[m4_foreach([_Lt_suffix],
]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[,
[_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])])
# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ])
# -----------------------------------------------------------------------
# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited
# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ.
m4_define([lt_if_append_uniq],
[m4_ifdef([$1],
[m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1],
[lt_append([$1], [$2], [$3])$4],
[$5])],
[lt_append([$1], [$2], [$3])$4])])
# lt_dict_add(DICT, KEY, VALUE)
# -----------------------------
m4_define([lt_dict_add],
[m4_define([$1($2)], [$3])])
# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE)
# --------------------------------------------
m4_define([lt_dict_add_subkey],
[m4_define([$1($2:$3)], [$4])])
# lt_dict_fetch(DICT, KEY, [SUBKEY])
# ----------------------------------
m4_define([lt_dict_fetch],
[m4_ifval([$3],
m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]),
m4_ifdef([$1($2)], [m4_defn([$1($2)])]))])
# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE])
# -----------------------------------------------------------------
m4_define([lt_if_dict_fetch],
[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4],
[$5],
[$6])])
# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...])
# --------------------------------------------------------------
m4_define([lt_dict_filter],
[m4_if([$5], [], [],
[lt_join(m4_quote(m4_default([$4], [[, ]])),
lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]),
[lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl
])

@ -0,0 +1,23 @@
# ltversion.m4 -- version numbers -*- Autoconf -*-
#
# Copyright (C) 2004, 2011-2015 Free Software Foundation, Inc.
# Written by Scott James Remnant, 2004
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# @configure_input@
# serial 4179 ltversion.m4
# This file is part of GNU Libtool
m4_define([LT_PACKAGE_VERSION], [2.4.6])
m4_define([LT_PACKAGE_REVISION], [2.4.6])
AC_DEFUN([LTVERSION_VERSION],
[macro_version='2.4.6'
macro_revision='2.4.6'
_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
_LT_DECL(, macro_revision, 0)
])

@ -0,0 +1,99 @@
# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*-
#
# Copyright (C) 2004-2005, 2007, 2009, 2011-2015 Free Software
# Foundation, Inc.
# Written by Scott James Remnant, 2004.
#
# This file is free software; the Free Software Foundation gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
# serial 5 lt~obsolete.m4
# These exist entirely to fool aclocal when bootstrapping libtool.
#
# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN),
# which have later been changed to m4_define as they aren't part of the
# exported API, or moved to Autoconf or Automake where they belong.
#
# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN
# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us
# using a macro with the same name in our local m4/libtool.m4 it'll
# pull the old libtool.m4 in (it doesn't see our shiny new m4_define
# and doesn't know about Autoconf macros at all.)
#
# So we provide this file, which has a silly filename so it's always
# included after everything else. This provides aclocal with the
# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything
# because those macros already exist, or will be overwritten later.
# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6.
#
# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here.
# Yes, that means every name once taken will need to remain here until
# we give up compatibility with versions before 1.7, at which point
# we need to keep only those names which we still refer to.
# This is to help aclocal find these macros, as it can't see m4_define.
AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])])
m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])])
m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])])
m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])])
m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])])
m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])])
m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])])
m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])])
m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])])
m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])])
m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])])
m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])])
m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])])
m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])])
m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])])
m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])])
m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])])
m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])])
m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])])
m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])])
m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])])
m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])])
m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])])
m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])])
m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])])
m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])])
m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])])
m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])])
m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])])
m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])])
m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])])
m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])])
m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])])
m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])])
m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])])
m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])])
m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])])
m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])])
m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])])
m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])])
m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])])
m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])])
m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])])
m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])])
m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])])
m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])])
m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])])
m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])])
m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])])
m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])])
m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])])
m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])])
m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])])
m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])])
m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])])
m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])])
m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])])

@ -0,0 +1,215 @@
#! /bin/sh
# Common wrapper for a few potentially missing GNU programs.
scriptversion=2018-03-07.03; # UTC
# Copyright (C) 1996-2020 Free Software Foundation, Inc.
# Originally written by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
if test $# -eq 0; then
echo 1>&2 "Try '$0 --help' for more information"
exit 1
fi
case $1 in
--is-lightweight)
# Used by our autoconf macros to check whether the available missing
# script is modern enough.
exit 0
;;
--run)
# Back-compat with the calling convention used by older automake.
shift
;;
-h|--h|--he|--hel|--help)
echo "\
$0 [OPTION]... PROGRAM [ARGUMENT]...
Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due
to PROGRAM being missing or too old.
Options:
-h, --help display this help and exit
-v, --version output version information and exit
Supported PROGRAM values:
aclocal autoconf autoheader autom4te automake makeinfo
bison yacc flex lex help2man
Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and
'g' are ignored when checking the name.
Send bug reports to <bug-automake@gnu.org>."
exit $?
;;
-v|--v|--ve|--ver|--vers|--versi|--versio|--version)
echo "missing $scriptversion (GNU Automake)"
exit $?
;;
-*)
echo 1>&2 "$0: unknown '$1' option"
echo 1>&2 "Try '$0 --help' for more information"
exit 1
;;
esac
# Run the given program, remember its exit status.
"$@"; st=$?
# If it succeeded, we are done.
test $st -eq 0 && exit 0
# Also exit now if we it failed (or wasn't found), and '--version' was
# passed; such an option is passed most likely to detect whether the
# program is present and works.
case $2 in --version|--help) exit $st;; esac
# Exit code 63 means version mismatch. This often happens when the user
# tries to use an ancient version of a tool on a file that requires a
# minimum version.
if test $st -eq 63; then
msg="probably too old"
elif test $st -eq 127; then
# Program was missing.
msg="missing on your system"
else
# Program was found and executed, but failed. Give up.
exit $st
fi
perl_URL=https://www.perl.org/
flex_URL=https://github.com/westes/flex
gnu_software_URL=https://www.gnu.org/software
program_details ()
{
case $1 in
aclocal|automake)
echo "The '$1' program is part of the GNU Automake package:"
echo "<$gnu_software_URL/automake>"
echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:"
echo "<$gnu_software_URL/autoconf>"
echo "<$gnu_software_URL/m4/>"
echo "<$perl_URL>"
;;
autoconf|autom4te|autoheader)
echo "The '$1' program is part of the GNU Autoconf package:"
echo "<$gnu_software_URL/autoconf/>"
echo "It also requires GNU m4 and Perl in order to run:"
echo "<$gnu_software_URL/m4/>"
echo "<$perl_URL>"
;;
esac
}
give_advice ()
{
# Normalize program name to check for.
normalized_program=`echo "$1" | sed '
s/^gnu-//; t
s/^gnu//; t
s/^g//; t'`
printf '%s\n' "'$1' is $msg."
configure_deps="'configure.ac' or m4 files included by 'configure.ac'"
case $normalized_program in
autoconf*)
echo "You should only need it if you modified 'configure.ac',"
echo "or m4 files included by it."
program_details 'autoconf'
;;
autoheader*)
echo "You should only need it if you modified 'acconfig.h' or"
echo "$configure_deps."
program_details 'autoheader'
;;
automake*)
echo "You should only need it if you modified 'Makefile.am' or"
echo "$configure_deps."
program_details 'automake'
;;
aclocal*)
echo "You should only need it if you modified 'acinclude.m4' or"
echo "$configure_deps."
program_details 'aclocal'
;;
autom4te*)
echo "You might have modified some maintainer files that require"
echo "the 'autom4te' program to be rebuilt."
program_details 'autom4te'
;;
bison*|yacc*)
echo "You should only need it if you modified a '.y' file."
echo "You may want to install the GNU Bison package:"
echo "<$gnu_software_URL/bison/>"
;;
lex*|flex*)
echo "You should only need it if you modified a '.l' file."
echo "You may want to install the Fast Lexical Analyzer package:"
echo "<$flex_URL>"
;;
help2man*)
echo "You should only need it if you modified a dependency" \
"of a man page."
echo "You may want to install the GNU Help2man package:"
echo "<$gnu_software_URL/help2man/>"
;;
makeinfo*)
echo "You should only need it if you modified a '.texi' file, or"
echo "any other file indirectly affecting the aspect of the manual."
echo "You might want to install the Texinfo package:"
echo "<$gnu_software_URL/texinfo/>"
echo "The spurious makeinfo call might also be the consequence of"
echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might"
echo "want to install GNU make:"
echo "<$gnu_software_URL/make/>"
;;
*)
echo "You might have modified some files without having the proper"
echo "tools for further handling them. Check the 'README' file, it"
echo "often tells you about the needed prerequisites for installing"
echo "this package. You may also peek at any GNU archive site, in"
echo "case some other package contains this missing '$1' program."
;;
esac
}
give_advice "$1" | sed -e '1s/^/WARNING: /' \
-e '2,$s/^/ /' >&2
# Propagate the correct exit status (expected to be 127 for a program
# not found, 63 for a program that failed due to version mismatch).
exit $st
# Local variables:
# eval: (add-hook 'before-save-hook 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC0"
# time-stamp-end: "; # UTC"
# End:

@ -0,0 +1,6 @@
/Makefile
/.deps/
*.o
*.lo
/.libs/
*.la

@ -0,0 +1,51 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/machine.h>
#include <Foundation/Foundation.h>
/**
* This class is used to detect running architecture.
*/
@interface ArchDetect : NSObject
/**
* Returns running cpu architecture name.
*
* @return running cpu architecture name as NSString
*/
+ (NSString*)getCpuArch;
/**
* Returns loaded architecture name.
*
* @return loaded architecture name as NSString
*/
+ (NSString*)getArch;
/**
* Returns whether FFmpegKit release is a long term release or not.
*
* @return yes=1 or no=0
*/
+ (int)isLTSBuild;
@end

@ -0,0 +1,184 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ArchDetect.h"
#include "FFmpegKitConfig.h"
#include "FFmpegKit.h"
@implementation ArchDetect
+ (void)initialize {
[FFmpegKitConfig class];
[FFmpegKit class];
}
/**
* Returns running cpu architecture name.
*
* @return running cpu architecture name as NSString
*/
+ (NSString*)getCpuArch {
NSMutableString *cpu = [[NSMutableString alloc] init];
size_t size;
cpu_type_t type;
cpu_subtype_t subtype;
size = sizeof(type);
sysctlbyname("hw.cputype", &type, &size, NULL, 0);
size = sizeof(subtype);
sysctlbyname("hw.cpusubtype", &subtype, &size, NULL, 0);
if (type == CPU_TYPE_X86_64) {
[cpu appendString:@"x86_64"];
} else if (type == CPU_TYPE_X86) {
[cpu appendString:@"x86"];
switch(subtype) {
case CPU_SUBTYPE_X86_64_H:
[cpu appendString:@"_64h"];
break;
case CPU_SUBTYPE_X86_64_ALL:
[cpu appendString:@"_64all"];
break;
case CPU_SUBTYPE_X86_ARCH1:
[cpu appendString:@"_arch1"];
break;
}
} else if (type == CPU_TYPE_I386) {
[cpu appendString:@"i386"];
} else if (type == CPU_TYPE_ARM64) {
[cpu appendString:@"arm64"];
switch(subtype) {
case CPU_SUBTYPE_ARM64_V8:
[cpu appendString:@"v8"];
break;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 120100
case CPU_SUBTYPE_ARM64E:
[cpu appendString:@"e"];
break;
#endif
}
} else if (type == CPU_TYPE_ARM) {
[cpu appendString:@"arm"];
switch(subtype) {
case CPU_SUBTYPE_ARM_XSCALE:
[cpu appendString:@"xscale"];
break;
case CPU_SUBTYPE_ARM_V4T:
[cpu appendString:@"v4t"];
break;
case CPU_SUBTYPE_ARM_V5TEJ:
[cpu appendString:@"v5tej"];
break;
case CPU_SUBTYPE_ARM_V6:
[cpu appendString:@"v6"];
break;
case CPU_SUBTYPE_ARM_V6M:
[cpu appendString:@"v6m"];
break;
case CPU_SUBTYPE_ARM_V7:
[cpu appendString:@"v7"];
break;
case CPU_SUBTYPE_ARM_V7EM:
[cpu appendString:@"v7em"];
break;
case CPU_SUBTYPE_ARM_V7F:
[cpu appendString:@"v7f"];
break;
case CPU_SUBTYPE_ARM_V7K:
[cpu appendString:@"v7k"];
break;
case CPU_SUBTYPE_ARM_V7M:
[cpu appendString:@"v7m"];
break;
case CPU_SUBTYPE_ARM_V7S:
[cpu appendString:@"v7s"];
break;
case CPU_SUBTYPE_ARM_V8:
[cpu appendString:@"v8"];
break;
}
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 120100
} else if (type == CPU_TYPE_ARM64_32) {
[cpu appendString:@"arm64_32"];
switch(subtype) {
case CPU_SUBTYPE_ARM64_32_V8:
[cpu appendString:@"v8"];
break;
}
#endif
} else {
[cpu appendString:[NSString stringWithFormat:@"%d", type]];
}
return cpu;
}
/**
* Returns loaded architecture name.
*
* @return loaded architecture name as NSString
*/
+ (NSString*)getArch {
NSMutableString *arch = [[NSMutableString alloc] init];
#ifdef FFMPEG_KIT_ARMV7
[arch appendString:@"armv7"];
#elif FFMPEG_KIT_ARMV7S
[arch appendString:@"armv7s"];
#elif FFMPEG_KIT_ARM64
[arch appendString:@"arm64"];
#elif FFMPEG_KIT_ARM64E
[arch appendString:@"arm64e"];
#elif FFMPEG_KIT_I386
[arch appendString:@"i386"];
#elif FFMPEG_KIT_X86_64
[arch appendString:@"x86_64"];
#elif FFMPEG_KIT_X86_64_MAC_CATALYST
[arch appendString:@"x86_64_mac_catalyst"];
#endif
return arch;
}
/**
* Returns whether FFmpegKit release is a long term release or not.
*
* @return yes=1 or no=0
*/
+ (int)isLTSBuild {
#if defined(FFMPEG_KIT_LTS)
return 1;
#else
return 0;
#endif
}
@end

@ -0,0 +1,31 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Foundation/Foundation.h>
/**
* Represents an atomic long data type.
*/
@interface AtomicLong : NSObject
- (instancetype)initWithInitialValue:(long)initialValue;
- (long)incrementAndGet;
@end

@ -0,0 +1,47 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AtomicLong.h"
@implementation AtomicLong {
NSRecursiveLock *lock;
long value;
}
- (instancetype)initWithInitialValue:(long)initialValue {
self = [super init];
if (self) {
value = initialValue;
}
return self;
}
- (long)incrementAndGet {
long returnValue;
[lock lock];
value += 1;
returnValue = value;
[lock unlock];
return returnValue;
}
@end

@ -0,0 +1,26 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Use this delegate to receive an asynchronous execution result.
*/
@protocol ExecuteDelegate<NSObject>
@required
- (void)executeCallback:(long)executionId :(int)returnCode;
@end

@ -0,0 +1,35 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Foundation/Foundation.h>
/**
* Represents an ongoing FFmpeg execution.
*/
@interface FFmpegExecution : NSObject
- (instancetype)initWithExecutionId:(long)newExecutionId andArguments:(NSArray*)arguments;
- (NSDate*)getStartTime;
- (long)getExecutionId;
- (NSString*)getCommand;
@end

@ -0,0 +1,52 @@
/*
* Copyright (c) 2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FFmpegExecution.h"
#include "FFmpegKit.h"
@implementation FFmpegExecution {
NSDate* startTime;
long executionId;
NSString* command;
}
- (instancetype)initWithExecutionId:(long)newExecutionId andArguments:(NSArray*)arguments {
self = [super init];
if (self) {
startTime = [NSDate date];
executionId = newExecutionId;
command = [FFmpegKit argumentsToString:arguments];
}
return self;
}
- (NSDate*)getStartTime {
return startTime;
}
- (long)getExecutionId {
return executionId;
}
- (NSString*)getCommand {
return command;
}
@end

@ -0,0 +1,137 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <stdlib.h>
#include <Foundation/Foundation.h>
#include "ExecuteDelegate.h"
/** Global library version */
extern NSString *const FFMPEG_KIT_VERSION;
/**
* Main class for FFmpeg operations.
*/
@interface FFmpegKit : NSObject
/**
* Synchronously executes FFmpeg with arguments provided.
*
* @param arguments FFmpeg command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
+ (int)executeWithArguments:(NSArray*)arguments;
/**
* Asynchronously executes FFmpeg with arguments provided. Space character is used to split command into arguments.
*
* @param arguments FFmpeg command options/arguments as string array
* @param delegate delegate that will be notified when execution is completed
* @return returns a unique id that represents this execution
*/
+ (int)executeWithArgumentsAsync:(NSArray*)arguments withCallback:(id<ExecuteDelegate>)delegate;
/**
* Asynchronously executes FFmpeg with arguments provided. Space character is used to split command into arguments.
*
* @param arguments FFmpeg command options/arguments as string array
* @param delegate delegate that will be notified when execution is completed
* @param queue dispatch queue that will be used to run this asynchronous operation
* @return returns a unique id that represents this execution
*/
+ (int)executeWithArgumentsAsync:(NSArray*)arguments withCallback:(id<ExecuteDelegate>)delegate andDispatchQueue:(dispatch_queue_t)queue;
/**
* Synchronously executes FFmpeg command provided. Space character is used to split command into arguments.
*
* @param command FFmpeg command
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
+ (int)execute:(NSString*)command;
/**
* Asynchronously executes FFmpeg command provided. Space character is used to split command into arguments.
*
* @param command FFmpeg command
* @param delegate delegate that will be notified when execution is completed
* @return returns a unique id that represents this execution
*/
+ (int)executeAsync:(NSString*)command withCallback:(id<ExecuteDelegate>)delegate;
/**
* Asynchronously executes FFmpeg command provided. Space character is used to split command into arguments.
*
* @param command FFmpeg command
* @param delegate delegate that will be notified when execution is completed
* @param queue dispatch queue that will be used to run this asynchronous operation
* @return returns a unique id that represents this execution
*/
+ (int)executeAsync:(NSString*)command withCallback:(id<ExecuteDelegate>)delegate andDispatchQueue:(dispatch_queue_t)queue;
/**
* Synchronously executes FFmpeg command provided. Delimiter parameter is used to split command into arguments.
*
* @param command FFmpeg command
* @param delimiter arguments delimiter
* @deprecated argument splitting mechanism used in this method is pretty simple and prone to errors. Consider
* using a more advanced method like execute or executeWithArguments
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
+ (int)execute:(NSString*)command delimiter:(NSString*)delimiter __attribute__((deprecated));
/**
* Cancels an ongoing operation.
*
* This function does not wait for termination to complete and returns immediately.
*/
+ (void)cancel;
/**
* Cancels an ongoing operation.
*
* This function does not wait for termination to complete and returns immediately.
*
* @param executionId execution id
*/
+ (void)cancel:(long)executionId;
/**
* Parses the given command into arguments.
*
* @param command string command
* @return array of arguments
*/
+ (NSArray*)parseArguments:(NSString*)command;
/**
* <p>Combines arguments into a string.
*
* @param arguments arguments
* @return string containing all arguments
*/
+ (NSString*)argumentsToString:(NSArray*)arguments;
/**
* <p>Lists ongoing executions.
*
* @return list of ongoing executions
*/
+ (NSArray*)listExecutions;
@end

@ -0,0 +1,310 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fftools_ffmpeg.h"
#include "FFmpegKit.h"
#include "ArchDetect.h"
#include "AtomicLong.h"
#include "FFmpegExecution.h"
#include "FFmpegKitConfig.h"
/** Forward declaration for function defined in fftools_ffmpeg.c */
int ffmpeg_execute(int argc, char **argv);
@implementation FFmpegKit
/** Global library version */
NSString *const FFMPEG_KIT_VERSION = @"4.4";
extern int lastReturnCode;
extern NSMutableString *lastCommandOutput;
long const DEFAULT_EXECUTION_ID = 0;
AtomicLong *executionIdCounter;
extern __thread volatile long executionId;
int cancelRequested(long executionId);
void addExecution(long executionId);
void removeExecution(long executionId);
NSMutableArray *executions;
NSLock *executionsLock;
extern int configuredLogLevel;
+ (void)initialize {
[FFmpegKitConfig class];
executionIdCounter = [[AtomicLong alloc] initWithInitialValue:3000];
executions = [[NSMutableArray alloc] init];
executionsLock = [[NSLock alloc] init];
NSLog(@"Loaded ffmpeg-kit-%@-%@-%@-%@\n", [FFmpegKitConfig getPackageName], [ArchDetect getArch], [FFmpegKitConfig getVersion], [FFmpegKitConfig getBuildDate]);
}
+ (int)executeWithId:(long)newExecutionId andArguments:(NSArray*)arguments {
lastCommandOutput = [[NSMutableString alloc] init];
// SETS DEFAULT LOG LEVEL BEFORE STARTING A NEW EXECUTION
av_log_set_level(configuredLogLevel);
FFmpegExecution* currentFFmpegExecution = [[FFmpegExecution alloc] initWithExecutionId:newExecutionId andArguments:arguments];
[executionsLock lock];
[executions addObject: currentFFmpegExecution];
[executionsLock unlock];
char **commandCharPArray = (char **)av_malloc(sizeof(char*) * ([arguments count] + 1));
/* PRESERVING CALLING FORMAT
*
* ffmpeg <arguments>
*/
commandCharPArray[0] = (char *)av_malloc(sizeof(char) * ([LIB_NAME length] + 1));
strcpy(commandCharPArray[0], [LIB_NAME UTF8String]);
for (int i=0; i < [arguments count]; i++) {
NSString *argument = [arguments objectAtIndex:i];
commandCharPArray[i + 1] = (char *) [argument UTF8String];
}
// REGISTER THE ID BEFORE STARTING EXECUTION
executionId = newExecutionId;
addExecution(newExecutionId);
// RUN
lastReturnCode = ffmpeg_execute(([arguments count] + 1), commandCharPArray);
// ALWAYS REMOVE THE ID FROM THE MAP
removeExecution(newExecutionId);
// CLEANUP
av_free(commandCharPArray[0]);
av_free(commandCharPArray);
[executionsLock lock];
[executions removeObject: currentFFmpegExecution];
[executionsLock unlock];
return lastReturnCode;
}
/**
* Synchronously executes FFmpeg with arguments provided.
*
* @param arguments FFmpeg command options/arguments as string array
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
+ (int)executeWithArguments:(NSArray*)arguments {
return [self executeWithId:DEFAULT_EXECUTION_ID andArguments:arguments];
}
/**
* Asynchronously executes FFmpeg with arguments provided. Space character is used to split command into arguments.
*
* @param arguments FFmpeg command options/arguments as string array
* @param delegate delegate that will be notified when execution is completed
* @return a unique id that represents this execution
*/
+ (int)executeWithArgumentsAsync:(NSArray*)arguments withCallback:(id<ExecuteDelegate>)delegate {
return [self executeWithArgumentsAsync:arguments withCallback:delegate andDispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}
/**
* Asynchronously executes FFmpeg with arguments provided. Space character is used to split command into arguments.
*
* @param arguments FFmpeg command options/arguments as string array
* @param delegate delegate that will be notified when execution is completed
* @param queue dispatch queue that will be used to run this asynchronous operation
* @return a unique id that represents this execution
*/
+ (int)executeWithArgumentsAsync:(NSArray*)arguments withCallback:(id<ExecuteDelegate>)delegate andDispatchQueue:(dispatch_queue_t)queue {
const long newExecutionId = [executionIdCounter incrementAndGet];
dispatch_async(queue, ^{
const int returnCode = [self executeWithId:newExecutionId andArguments:arguments];
if (delegate != nil) {
[delegate executeCallback:executionId:returnCode];
}
});
return newExecutionId;
}
/**
* Synchronously executes FFmpeg command provided. Space character is used to split command into arguments.
*
* @param command FFmpeg command
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
+ (int)execute:(NSString*)command {
return [self executeWithArguments: [self parseArguments: command]];
}
/**
* Asynchronously executes FFmpeg command provided. Space character is used to split command into arguments.
*
* @param command FFmpeg command
* @param delegate delegate that will be notified when execution is completed
* @return a unique id that represents this execution
*/
+ (int)executeAsync:(NSString*)command withCallback:(id<ExecuteDelegate>)delegate {
return [self executeAsync:command withCallback:delegate andDispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}
/**
* Asynchronously executes FFmpeg command provided. Space character is used to split command into arguments.
*
* @param command FFmpeg command
* @param delegate delegate that will be notified when execution is completed
* @param queue dispatch queue that will be used to run this asynchronous operation
* @return a unique id that represents this execution
*/
+ (int)executeAsync:(NSString*)command withCallback:(id<ExecuteDelegate>)delegate andDispatchQueue:(dispatch_queue_t)queue {
return [self executeWithArgumentsAsync:[self parseArguments:command] withCallback:delegate andDispatchQueue:queue];
}
/**
* Synchronously executes FFmpeg command provided. Delimiter parameter is used to split command into arguments.
*
* @param command FFmpeg command
* @param delimiter arguments delimiter
* @return zero on successful execution, 255 on user cancel and non-zero on error
*/
+ (int)execute:(NSString*)command delimiter:(NSString*)delimiter {
// SPLITTING ARGUMENTS
NSArray* argumentArray = [command componentsSeparatedByString:(delimiter == nil ? @" ": delimiter)];
return [self executeWithArguments:argumentArray];
}
/**
* Cancels an ongoing operation.
*
* This function does not wait for termination to complete and returns immediately.
*/
+ (void)cancel {
cancel_operation(DEFAULT_EXECUTION_ID);
}
/**
* Cancels an ongoing operation.
*
* This function does not wait for termination to complete and returns immediately.
*
* @param executionId execution id
*/
+ (void)cancel:(long)executionId {
cancel_operation(executionId);
}
/**
* Parses the given command into arguments.
*
* @param command string command
* @return array of arguments
*/
+ (NSArray*)parseArguments:(NSString*)command {
NSMutableArray *argumentArray = [[NSMutableArray alloc] init];
NSMutableString *currentArgument = [[NSMutableString alloc] init];
bool singleQuoteStarted = false;
bool doubleQuoteStarted = false;
for (int i = 0; i < command.length; i++) {
unichar previousChar;
if (i > 0) {
previousChar = [command characterAtIndex:(i - 1)];
} else {
previousChar = 0;
}
unichar currentChar = [command characterAtIndex:i];
if (currentChar == ' ') {
if (singleQuoteStarted || doubleQuoteStarted) {
[currentArgument appendFormat: @"%C", currentChar];
} else if ([currentArgument length] > 0) {
[argumentArray addObject: currentArgument];
currentArgument = [[NSMutableString alloc] init];
}
} else if (currentChar == '\'' && (previousChar == 0 || previousChar != '\\')) {
if (singleQuoteStarted) {
singleQuoteStarted = false;
} else if (doubleQuoteStarted) {
[currentArgument appendFormat: @"%C", currentChar];
} else {
singleQuoteStarted = true;
}
} else if (currentChar == '\"' && (previousChar == 0 || previousChar != '\\')) {
if (doubleQuoteStarted) {
doubleQuoteStarted = false;
} else if (singleQuoteStarted) {
[currentArgument appendFormat: @"%C", currentChar];
} else {
doubleQuoteStarted = true;
}
} else {
[currentArgument appendFormat: @"%C", currentChar];
}
}
if ([currentArgument length] > 0) {
[argumentArray addObject: currentArgument];
}
return argumentArray;
}
/**
* <p>Combines arguments into a string.
*
* @param arguments arguments
* @return string containing all arguments
*/
+ (NSString*)argumentsToString:(NSArray*)arguments {
if (arguments == nil) {
return @"null";
}
NSMutableString *string = [NSMutableString stringWithString:@""];
for (int i=0; i < [arguments count]; i++) {
NSString *argument = [arguments objectAtIndex:i];
if (i > 0) {
[string appendString:@" "];
}
[string appendString:argument];
}
return string;
}
/**
* <p>Lists ongoing executions.
*
* @return list of ongoing executions
*/
+ (NSArray*)listExecutions {
[executionsLock lock];
NSArray *array = [NSArray arrayWithArray:executions];
[executionsLock unlock];
return array;
}
@end

@ -0,0 +1,266 @@
/*
* Copyright (c) 2018-2020 Taner Sener
*
* This file is part of FFmpegKit.
*
* FFmpegKit 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 3 of the License, or
* (at your option) any later version.
*
* FFmpegKit 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 FFmpegKit. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <Foundation/Foundation.h>
#include "LogDelegate.h"
#include "StatisticsDelegate.h"
/** Common return code values */
extern int const RETURN_CODE_SUCCESS;
extern int const RETURN_CODE_CANCEL;
/** Identifier used for IOS logging. */
extern NSString *const LIB_NAME;
/**
* Print no output.
*/
#define AV_LOG_QUIET -8
/**
* Something went really wrong and we will crash now.
*/
#define AV_LOG_PANIC 0
/**
* Something went wrong and recovery is not possible.
* For example, no header was found for a format which depends
* on headers or an illegal combination of parameters is used.
*/
#define AV_LOG_FATAL 8
/**
* Something went wrong and cannot losslessly be recovered.
* However, not all future data is affected.
*/
#define AV_LOG_ERROR 16
/**
* Something somehow does not look correct. This may or may not
* lead to problems. An example would be the use of '-vstrict -2'.
*/
#define AV_LOG_WARNING 24
/**
* Standard information.
*/
#define AV_LOG_INFO 32
/**
* Detailed information.
*/
#define AV_LOG_VERBOSE 40
/**
* Stuff which is only useful for libav* developers.
*/
#define AV_LOG_DEBUG 48
/**
* This class is used to configure FFmpegKit library utilities/tools.
*
* 1. LogDelegate: This class redirects FFmpeg/FFprobe output to NSLog by default. As
* an alternative, it is possible not to print messages to NSLog and pass them to a
* LogDelegate function. This function can decide whether to print these logs, show them
* inside another container or ignore them.
*
* 2. setLogLevel:/getLogLevel: Use this methods to set/get
* FFmpeg/FFprobe log severity.
*
* 3. StatsDelegate: It is possible to receive statistics about ongoing
* operation by defining a StatsDelegate or by calling
* getLastReceivedStats method.
*
* 4. Font configuration: It is possible to register custom fonts with
* setFontconfigConfigurationPath: and
* setFontDirectory:with: methods.
*
*/
@interface FFmpegKitConfig : NSObject
/**
* Enables log and statistics redirection.
* When redirection is not enabled FFmpeg/FFprobe logs are printed to stderr. By enabling
* redirection, they are routed to NSLog and can be routed further to a log delegate.
* Statistics redirection behaviour is similar. Statistics are not printed at all if
* redirection is not enabled. If it is enabled then it is possible to define a statistics
* delegate but if you don't, they are not printed anywhere and only saved as
* 'lastReceivedStatistics' data which can be polled with
* '{@link #'getLastReceivedStatistics()'.
* Note that redirection is enabled by default. If you do not want to use its functionality
* please use 'disableRedirection()' to disable it.
*/
+ (void)enableRedirection;
/**
* Disables log and statistics redirection.
*/
+ (void)disableRedirection;
/**
* Returns log level.
*
* @return log level
*/
+ (int)getLogLevel;
/**
* Sets log level.
*
* @param level log level
*/
+ (void)setLogLevel:(int)level;
/**
* Converts int log level to string.
*
* @param level value
* @return string value
*/
+ (NSString*)logLevelToString:(int)level;
/**
* Sets a LogDelegate. logCallback method inside LogDelegate is used to redirect logs.
*
* @param newLogDelegate log delegate or nil to disable a previously defined delegate
*/
+ (void)setLogDelegate:(id<LogDelegate>)newLogDelegate;
/**
* Sets a StatisticsDelegate. statisticsCallback method inside StatisticsDelegate is used to redirect statistics.
*
* @param newStatisticsDelegate statistics delegate or nil to disable a previously defined delegate
*/
+ (void)setStatisticsDelegate:(id<StatisticsDelegate>)newStatisticsDelegate;
/**
* Returns the last received statistics data. It is recommended to call it before starting a new execution.
*
* @return last received statistics data
*/
+ (Statistics*)getLastReceivedStatistics;
/**
* Resets last received statistics.
*/
+ (void)resetStatistics;
/**
* Sets and overrides fontconfig configuration directory.
*
* @param path directory which contains fontconfig configuration (fonts.conf)
*/
+ (void)setFontconfigConfigurationPath:(NSString*)path;
/**
* Registers fonts inside the given path, so they are available to use in FFmpeg filters.
*
* Note that you need to build FFmpegKit with fontconfig
* enabled or use a prebuilt package with fontconfig inside to use this feature.
*
* @param fontDirectoryPath directory which contains fonts (.ttf and .otf files)
* @param fontNameMapping custom font name mappings, useful to access your fonts with more friendly names
*/
+ (void)setFontDirectory:(NSString*)fontDirectoryPath with:(NSDictionary*)fontNameMapping;
/**
* Returns package name.
*
* @return guessed package name according to supported external libraries
*/
+ (NSString*)getPackageName;
/**
* Returns supported external libraries.
*
* @return array of supported external libraries
*/
+ (NSArray*)getExternalLibraries;
/**
* Creates a new named pipe to use in FFmpeg operations.
*
* Please note that creator is responsible of closing created pipes.
*
* @return the full path of named pipe
*/
+ (NSString*)registerNewFFmpegPipe;
/**
* Closes a previously created FFmpeg pipe.
*
* @param ffmpegPipePath full path of ffmpeg pipe
*/
+ (void)closeFFmpegPipe:(NSString*)ffmpegPipePath;
/**
* Returns FFmpeg version bundled within the library.
*
* @return FFmpeg version
*/
+ (NSString*)getFFmpegVersion;
/**
* Returns FFmpegKit library version.
*
* @return FFmpegKit version
*/
+ (NSString*)getVersion;
/**
* Returns FFmpegKit library build date.
*
* @return FFmpegKit library build date
*/
+ (NSString*)getBuildDate;
/**
* Returns return code of last executed command.
*
* @return return code of last executed command
*/
+ (int)getLastReturnCode;
/**
* Returns log output of last executed single FFmpeg/FFprobe command.
*
* This method does not support executing multiple concurrent commands. If you execute
* multiple commands at the same time, this method will return output from all executions.
*
* Please note that disabling redirection using FFmpegKitConfig.disableRedirection() method
* also disables this functionality.
*
* @return output of last executed command
*/
+ (NSString*)getLastCommandOutput;
/**
* Registers a new ignored signal. Ignored signals are not handled by the library.
*
* By default, the following 5 signals are handled: SIGINT, SIGQUIT, SIGPIPE, SIGTERM and SIGXCPU. Any of them can be
* ignored.
*
* @param signum signal number to ignore
*/
+ (void)ignoreSignal:(int)signum;
@end

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

Loading…
Cancel
Save