Skip to content
Snippets Groups Projects
Verified Commit bc39890e authored by Niklas Haas's avatar Niklas Haas
Browse files

libplacebo: initial commit

Code shamelessly stolen from mpv, except without all the awful parts.
(Just kidding, I still love mpv)
parents
No related branches found
No related tags found
No related merge requests found
/build
/tags
/TAGS
LICENSE 0 → 100644
libplacebo's code base is heavily derived from mpv, which is a fork of mplayer2,
which is a fork of MPlayer. Currently, this includes files inside the following
directories:
bstr/*
osdep/*
ta/*
All of the affected MPlayer/mplayer2/mpv code has been successfully relicensed
to LGPLv2.1+; which means that libplacebo as a whole is licensed under the GNU
Lesser General Public License version 2.1 or later. All new contributions must
be published under the same license.
Note to contributors: This project will remain LGPLv2.1+, so any new code that
is ported from mpv (or other sources) must be LGPLv2.1+ compatible, i.e.
porting GPL, LGPLv2 (without the "or later") or LGPLv3+ code is not allowed
and must be rewritten instead.
Appended is a complete copy of the LGPLv2.1 license text.
-------------------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
README.md 0 → 100644
# libplacebo
**libplacebo** is essentially the core rendering engine of
[mpv](https://mpv.io) turned into a library. This grew out of an interest to
accomplish the following goals:
- Clean up mpv's internal [RA](#rendering-abstraction) API and make it reusable for other projects.
- Provide a standard library of useful GPU-accelerated image processing
primitives based on GLSL, so projects like VLC or Firefox can use them
without incurring a heavy dependency on `libmpv`.
- Rewrite core parts of mpv's GPU-accelerated video renderer on top of
redesigned abstractions. (Basically, I wanted to eliminate code smell like
`shader_cache.c` and totally redesign `gpu/video.c`)
**NOTE**: libplacebo is currently in a very early stage. Expect the API to be
extremely unstable, and many parts to be missing. The API version as exported
by `common.h` will **NOT** change until I declare the API stable, which will
coincide with the first release. As such, libplacebo should currently only
be used for testing purposes. It is not a finished product by any means.
## Authors
libplacebo's main developer is Niklas Haas (@haasn), but the project would
not be possible without the immense contributions of Vincent Lang (@wm4), who
laid the groundwork for most of the code that ended up in libplacebo.
For a full list of past contributors to mpv, see the [mpv authorship
page](https://github.com/mpv-player/mpv/graphs/contributors).
## License
Since the code heavily derives from LGPLv2.1+-licensed parts of mpv, there's
little choice but to license libplacebo the same way.
## API Overview
The public API of libplacebo is currently split up into the following
components, the header files (and documentation) for which are available
inside the [`src/public/`](src/public/) directory.
- `context.h`: The main entry-point into the library. Controls memory
allocation, logging. and guards ABI/thread safety.
- `colorspace.h`: A collection of enums and structs for describing color
spaces, as well as a collection of helper functions for computing various
color space transformation matrices.
- `common.h`: A collection of miscellaneous utility types and macros that are
shared among multiple subsystems. Usually does not need to be included
directly.
- `config.h`: Macros defining information about the way libplacebo was built,
including the version strings and compiled-in features/dependencies. Usually
does not need to be included directly.
- `filters.h`: A collection of reusable reconstruction filter kernels, which
can be used for scaling. The generated weights arrays are semi-tailored to
the needs of libplacebo, but may be useful to somebody else regardless. Also
contains the structs needed to define a filter kernel for the purposes of
libplacebo's upscaling routines.
- `ra.h`: Exports the RA API used by libplacebo internally. For more
information, see the [rendering abstraction](#rendering-abstraction)
section.
- `shaders.h`: A collection of reusable GLSL primitives for various individual
tasks including color space transformations and (eventually) image sampling,
debanding, etc. These have an optional dependency on RA (ra.h), but can also
be used independently (with more restrictions).
## Rendering Abstraction
As part of the public API, libplacebo exports the **RA** API ("Rendering
Abstraction"). Basically, this is the API libplacebo uses internally to wrap
OpenGL, Vulkan, Direct3D etc. into a single unifying API subset that abstracts
away state, messy details, synchronization etc. into a very high-level API
suitable for libplacebo's image processing tasks.
It's made public both because it constitutes part of the public API of various
image processing functions, but also in the hopes that it will be useful for
other developers of GPU-accelerated image processing software. RA can be used
entirely independently of libplacebo's image processing, which is why it
uses its own namespace (`ra_` instead of `pl_`).
**NOTE**: The port of RA into libplacebo is currently very WIP, and right now
only the public API is exported - none of the actual implementations.
## Building
libplacebo is built using the [meson build system](http://mesonbuild.com/).
You can build the project using the following steps:
```bash
$ meson build && cd build
$ ninja
```
To rebuild the project on changes, re-run `ninja` from the `build` directory.
If you wish to install the build products to the configured prefix (typically
`/usr/local/`), you can run `ninja install`. Note that this is normally ill-
advised except for developers who know what they're doing. Regular users
should rely on distro packages.
## Using
Building a trivial project using libplacebo is straightforward:
```c
// build with -lplacebo
#include <libplacebo/context.h>
void main()
{
struct pl_context *ctx = pl_context_create(PL_API_VER);
// do something..
pl_context_destroy(&ctx);
}
```
For a full documentation of the API, refer to the above [API
Overview](#api-overview) as well as the [public header files](src/public/).
project('libplacebo', 'c',
license: 'LGPL2.1+',
default_options: ['c_std=c99'],
)
subdir('src')
bstr ("byte string") is an abstraction for working with strings in a
start/length representation rather than scanning for \0 terminators. This is
important for both handling arbitrary binary data as well as being more
efficient for large string operations.
bstr is based on the TA/talloc helpers.
All of the code is ported from mpv (https://mpv.io).
/*
* Copyright (c) 2017 the mpv developers
*
* mpv 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.
*
* mpv 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <strings.h>
#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include "ta/talloc.h"
#include "bstr.h"
#include "ctype.h"
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int bstrcmp(struct bstr str1, struct bstr str2)
{
int ret = 0;
if (str1.len && str2.len)
ret = memcmp(str1.start, str2.start, MIN(str1.len, str2.len));
if (!ret) {
if (str1.len == str2.len)
return 0;
else if (str1.len > str2.len)
return 1;
else
return -1;
}
return ret;
}
int bstrcasecmp(struct bstr str1, struct bstr str2)
{
int ret = 0;
if (str1.len && str2.len)
ret = strncasecmp(str1.start, str2.start, MIN(str1.len, str2.len));
if (!ret) {
if (str1.len == str2.len)
return 0;
else if (str1.len > str2.len)
return 1;
else
return -1;
}
return ret;
}
int bstrchr(struct bstr str, int c)
{
for (int i = 0; i < str.len; i++)
if (str.start[i] == c)
return i;
return -1;
}
int bstrrchr(struct bstr str, int c)
{
for (int i = str.len - 1; i >= 0; i--)
if (str.start[i] == c)
return i;
return -1;
}
int bstrcspn(struct bstr str, const char *reject)
{
int i;
for (i = 0; i < str.len; i++)
if (strchr(reject, str.start[i]))
break;
return i;
}
int bstrspn(struct bstr str, const char *accept)
{
int i;
for (i = 0; i < str.len; i++)
if (!strchr(accept, str.start[i]))
break;
return i;
}
int bstr_find(struct bstr haystack, struct bstr needle)
{
for (int i = 0; i < haystack.len; i++)
if (bstr_startswith(bstr_splice(haystack, i, haystack.len), needle))
return i;
return -1;
}
struct bstr bstr_lstrip(struct bstr str)
{
while (str.len && mp_isspace(*str.start)) {
str.start++;
str.len--;
}
return str;
}
struct bstr bstr_strip(struct bstr str)
{
str = bstr_lstrip(str);
while (str.len && mp_isspace(str.start[str.len - 1]))
str.len--;
return str;
}
struct bstr bstr_split(struct bstr str, const char *sep, struct bstr *rest)
{
int start;
for (start = 0; start < str.len; start++)
if (!strchr(sep, str.start[start]))
break;
str = bstr_cut(str, start);
int end = bstrcspn(str, sep);
if (rest) {
*rest = bstr_cut(str, end);
}
return bstr_splice(str, 0, end);
}
// Unlike with bstr_split(), tok is a string, and not a set of char.
// If tok is in str, return true, and: concat(out_left, tok, out_right) == str
// Otherwise, return false, and set out_left==str, out_right==""
bool bstr_split_tok(bstr str, const char *tok, bstr *out_left, bstr *out_right)
{
bstr bsep = bstr0(tok);
int pos = bstr_find(str, bsep);
if (pos < 0)
pos = str.len;
*out_left = bstr_splice(str, 0, pos);
*out_right = bstr_cut(str, pos + bsep.len);
return pos != str.len;
}
struct bstr bstr_splice(struct bstr str, int start, int end)
{
if (start < 0)
start += str.len;
if (end < 0)
end += str.len;
end = MIN(end, str.len);
start = MAX(start, 0);
end = MAX(end, start);
str.start += start;
str.len = end - start;
return str;
}
long long bstrtoll(struct bstr str, struct bstr *rest, int base)
{
str = bstr_lstrip(str);
char buf[51];
int len = MIN(str.len, 50);
memcpy(buf, str.start, len);
buf[len] = 0;
char *endptr;
long long r = strtoll(buf, &endptr, base);
if (rest)
*rest = bstr_cut(str, endptr - buf);
return r;
}
double bstrtod(struct bstr str, struct bstr *rest)
{
str = bstr_lstrip(str);
char buf[101];
int len = MIN(str.len, 100);
memcpy(buf, str.start, len);
buf[len] = 0;
char *endptr;
double r = strtod(buf, &endptr);
if (rest)
*rest = bstr_cut(str, endptr - buf);
return r;
}
struct bstr *bstr_splitlines(void *talloc_ctx, struct bstr str)
{
if (str.len == 0)
return NULL;
int count = 0;
for (int i = 0; i < str.len; i++)
if (str.start[i] == '\n')
count++;
if (str.start[str.len - 1] != '\n')
count++;
struct bstr *r = talloc_array_ptrtype(talloc_ctx, r, count);
unsigned char *p = str.start;
for (int i = 0; i < count - 1; i++) {
r[i].start = p;
while (*p++ != '\n');
r[i].len = p - r[i].start;
}
r[count - 1].start = p;
r[count - 1].len = str.start + str.len - p;
return r;
}
struct bstr bstr_splitchar(struct bstr str, struct bstr *rest, const char c)
{
int pos = bstrchr(str, c);
if (pos < 0)
pos = str.len;
if (rest)
*rest = bstr_cut(str, pos + 1);
return bstr_splice(str, 0, pos + 1);
}
struct bstr bstr_strip_linebreaks(struct bstr str)
{
if (bstr_endswith0(str, "\r\n")) {
str = bstr_splice(str, 0, str.len - 2);
} else if (bstr_endswith0(str, "\n")) {
str = bstr_splice(str, 0, str.len - 1);
}
return str;
}
bool bstr_eatstart(struct bstr *s, struct bstr prefix)
{
if (!bstr_startswith(*s, prefix))
return false;
*s = bstr_cut(*s, prefix.len);
return true;
}
bool bstr_eatend(struct bstr *s, struct bstr prefix)
{
if (!bstr_endswith(*s, prefix))
return false;
s->len -= prefix.len;
return true;
}
void bstr_lower(struct bstr str)
{
for (int i = 0; i < str.len; i++)
str.start[i] = mp_tolower(str.start[i]);
}
int bstr_sscanf(struct bstr str, const char *format, ...)
{
char *ptr = bstrdup0(NULL, str);
va_list va;
va_start(va, format);
int ret = vsscanf(ptr, format, va);
va_end(va);
talloc_free(ptr);
return ret;
}
static void resize_append(void *talloc_ctx, bstr *s, size_t append_min)
{
size_t size = talloc_get_size(s->start);
assert(s->len <= size);
if (append_min > size - s->len) {
if (append_min < size)
append_min = size; // preallocate in power of 2s
if (size >= SIZE_MAX / 2 || append_min >= SIZE_MAX / 2)
abort(); // oom
s->start = talloc_realloc_size(talloc_ctx, s->start, size + append_min);
}
}
// Append the string, so that *s = *s + append. s->start is expected to be
// a talloc allocation (which can be realloced) or NULL.
// This function will always implicitly append a \0 after the new string for
// convenience.
// talloc_ctx will be used as parent context, if s->start is NULL.
void bstr_xappend(void *talloc_ctx, bstr *s, bstr append)
{
if (!append.len)
return;
resize_append(talloc_ctx, s, append.len + 1);
memcpy(s->start + s->len, append.start, append.len);
s->len += append.len;
s->start[s->len] = '\0';
}
void bstr_xappend_asprintf(void *talloc_ctx, bstr *s, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
bstr_xappend_vasprintf(talloc_ctx, s, fmt, ap);
va_end(ap);
}
// Exactly as bstr_xappend(), but with a formatted string.
void bstr_xappend_vasprintf(void *talloc_ctx, bstr *s, const char *fmt,
va_list ap)
{
int size;
va_list copy;
va_copy(copy, ap);
size_t avail = talloc_get_size(s->start) - s->len;
char *dest = s->start ? s->start + s->len : NULL;
char c;
if (avail < 1)
dest = &c;
size = vsnprintf(dest, MAX(avail, 1), fmt, copy);
va_end(copy);
if (size < 0)
abort();
if (avail < 1 || size + 1 > avail) {
resize_append(talloc_ctx, s, size + 1);
vsnprintf(s->start + s->len, size + 1, fmt, ap);
}
s->len += size;
}
bool bstr_case_startswith(struct bstr s, struct bstr prefix)
{
struct bstr start = bstr_splice(s, 0, prefix.len);
return start.len == prefix.len && bstrcasecmp(start, prefix) == 0;
}
bool bstr_case_endswith(struct bstr s, struct bstr suffix)
{
struct bstr end = bstr_cut(s, -suffix.len);
return end.len == suffix.len && bstrcasecmp(end, suffix) == 0;
}
struct bstr bstr_strip_ext(struct bstr str)
{
int dotpos = bstrrchr(str, '.');
if (dotpos < 0)
return str;
return (struct bstr){str.start, dotpos};
}
struct bstr bstr_get_ext(struct bstr s)
{
int dotpos = bstrrchr(s, '.');
if (dotpos < 0)
return (struct bstr){NULL, 0};
return bstr_splice(s, dotpos + 1, s.len);
}
static int h_to_i(unsigned char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1; // invalid char
}
bool bstr_decode_hex(void *talloc_ctx, struct bstr hex, struct bstr *out)
{
if (!out)
return false;
char *arr = talloc_array(talloc_ctx, char, hex.len / 2);
int len = 0;
while (hex.len >= 2) {
int a = h_to_i(hex.start[0]);
int b = h_to_i(hex.start[1]);
hex = bstr_splice(hex, 2, hex.len);
if (a < 0 || b < 0) {
talloc_free(arr);
return false;
}
arr[len++] = (a << 4) | b;
}
*out = (struct bstr){ .start = arr, .len = len };
return true;
}
/*
* Copyright (c) 2017 the mpv developers
*
* mpv 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.
*
* mpv 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include "osdep/compiler.h"
#include "ta/talloc.h"
/* NOTE: 'len' is size_t, but most string-handling functions below assume
* that input size has been sanity checked and len fits in an int.
*/
typedef struct bstr {
unsigned char *start;
size_t len;
} bstr;
// If str.start is NULL, return NULL.
static inline char *bstrdup0(void *talloc_ctx, struct bstr str)
{
return talloc_strndup(talloc_ctx, (char *)str.start, str.len);
}
// Like bstrdup0(), but always return a valid C-string.
static inline char *bstrto0(void *talloc_ctx, struct bstr str)
{
return str.start ? bstrdup0(talloc_ctx, str) : talloc_strdup(talloc_ctx, "");
}
// Return start = NULL iff that is true for the original.
static inline struct bstr bstrdup(void *talloc_ctx, struct bstr str)
{
struct bstr r = { NULL, str.len };
if (str.start)
r.start = (unsigned char *)talloc_memdup(talloc_ctx, str.start, str.len);
return r;
}
static inline struct bstr bstr0(const char *s)
{
return (struct bstr){(unsigned char *)s, s ? strlen(s) : 0};
}
int bstrcmp(struct bstr str1, struct bstr str2);
int bstrcasecmp(struct bstr str1, struct bstr str2);
int bstrchr(struct bstr str, int c);
int bstrrchr(struct bstr str, int c);
int bstrspn(struct bstr str, const char *accept);
int bstrcspn(struct bstr str, const char *reject);
int bstr_find(struct bstr haystack, struct bstr needle);
struct bstr *bstr_splitlines(void *talloc_ctx, struct bstr str);
struct bstr bstr_lstrip(struct bstr str);
struct bstr bstr_strip(struct bstr str);
struct bstr bstr_split(struct bstr str, const char *sep, struct bstr *rest);
bool bstr_split_tok(bstr str, const char *tok, bstr *out_left, bstr *out_right);
struct bstr bstr_splice(struct bstr str, int start, int end);
long long bstrtoll(struct bstr str, struct bstr *rest, int base);
double bstrtod(struct bstr str, struct bstr *rest);
void bstr_lower(struct bstr str);
int bstr_sscanf(struct bstr str, const char *format, ...);
// Decode a string containing hexadecimal data. All whitespace will be silently
// ignored. When successful, this allocates a new array to store the output.
bool bstr_decode_hex(void *talloc_ctx, struct bstr hex, struct bstr *out);
// Return the text before the occurrence of a character, and return it. Change
// *rest to point to the text following this character. (rest can be NULL.)
struct bstr bstr_splitchar(struct bstr str, struct bstr *rest, const char c);
// Like bstr_splitchar. Trailing newlines are not stripped.
static inline struct bstr bstr_getline(struct bstr str, struct bstr *rest)
{
return bstr_splitchar(str, rest, '\n');
}
// Strip one trailing line break. This is intended for use with bstr_getline,
// and will remove the trailing \n or \r\n sequence.
struct bstr bstr_strip_linebreaks(struct bstr str);
void bstr_xappend(void *talloc_ctx, bstr *s, bstr append);
void bstr_xappend_asprintf(void *talloc_ctx, bstr *s, const char *fmt, ...)
PRINTF_ATTRIBUTE(3, 4);
void bstr_xappend_vasprintf(void *talloc_ctx, bstr *s, const char *fmt, va_list va)
PRINTF_ATTRIBUTE(3, 0);
// If s starts/ends with prefix, return true and return the rest of the string
// in s.
bool bstr_eatstart(struct bstr *s, struct bstr prefix);
bool bstr_eatend(struct bstr *s, struct bstr prefix);
bool bstr_case_startswith(struct bstr s, struct bstr prefix);
bool bstr_case_endswith(struct bstr s, struct bstr suffix);
struct bstr bstr_strip_ext(struct bstr str);
struct bstr bstr_get_ext(struct bstr s);
static inline struct bstr bstr_cut(struct bstr str, int n)
{
if (n < 0) {
n += str.len;
if (n < 0)
n = 0;
}
if (((size_t)n) > str.len)
n = str.len;
return (struct bstr){str.start + n, str.len - n};
}
static inline bool bstr_startswith(struct bstr str, struct bstr prefix)
{
if (str.len < prefix.len)
return false;
return !memcmp(str.start, prefix.start, prefix.len);
}
static inline bool bstr_startswith0(struct bstr str, const char *prefix)
{
return bstr_startswith(str, bstr0(prefix));
}
static inline bool bstr_endswith(struct bstr str, struct bstr suffix)
{
if (str.len < suffix.len)
return false;
return !memcmp(str.start + str.len - suffix.len, suffix.start, suffix.len);
}
static inline bool bstr_endswith0(struct bstr str, const char *suffix)
{
return bstr_endswith(str, bstr0(suffix));
}
static inline int bstrcmp0(struct bstr str1, const char *str2)
{
return bstrcmp(str1, bstr0(str2));
}
static inline bool bstr_equals(struct bstr str1, struct bstr str2)
{
if (str1.len != str2.len)
return false;
return str1.start == str2.start || bstrcmp(str1, str2) == 0;
}
static inline bool bstr_equals0(struct bstr str1, const char *str2)
{
return bstr_equals(str1, bstr0(str2));
}
static inline int bstrcasecmp0(struct bstr str1, const char *str2)
{
return bstrcasecmp(str1, bstr0(str2));
}
static inline int bstr_find0(struct bstr haystack, const char *needle)
{
return bstr_find(haystack, bstr0(needle));
}
static inline bool bstr_eatstart0(struct bstr *s, const char *prefix)
{
return bstr_eatstart(s, bstr0(prefix));
}
static inline bool bstr_eatend0(struct bstr *s, const char *prefix)
{
return bstr_eatend(s, bstr0(prefix));
}
// create a pair (not single value!) for "%.*s" printf syntax
#define BSTR_P(bstr) (int)((bstr).len), ((bstr).start ? (char*)(bstr).start : "")
#define WHITESPACE " \f\n\r\t\v"
#pragma once
// Roughly follows C semantics, but doesn't account for EOF, allows char as
// parameter, and is locale independent (always uses "C" locale).
static inline int mp_isprint(char c) { return (unsigned char)c >= 32; }
static inline int mp_isspace(char c) { return c == ' ' || c == '\f' || c == '\n' ||
c == '\r' || c == '\t' || c =='\v'; }
static inline int mp_isupper(char c) { return c >= 'A' && c <= 'Z'; }
static inline int mp_islower(char c) { return c >= 'a' && c <= 'z'; }
static inline int mp_isdigit(char c) { return c >= '0' && c <= '9'; }
static inline int mp_isalpha(char c) { return mp_isupper(c) || mp_islower(c); }
static inline int mp_isalnum(char c) { return mp_isalpha(c) || mp_isdigit(c); }
static inline char mp_tolower(char c) { return mp_isupper(c) ? c - 'A' + 'a' : c; }
static inline char mp_toupper(char c) { return mp_islower(c) ? c - 'a' + 'A' : c; }
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include "common.h"
bool pl_color_system_is_ycbcr_like(enum pl_color_system sys)
{
switch (sys) {
case PL_COLOR_SYSTEM_RGB:
case PL_COLOR_SYSTEM_XYZ:
return false;
case PL_COLOR_SYSTEM_UNKNOWN:
case PL_COLOR_SYSTEM_BT_601:
case PL_COLOR_SYSTEM_BT_709:
case PL_COLOR_SYSTEM_SMPTE_240M:
case PL_COLOR_SYSTEM_BT_2020_NC:
case PL_COLOR_SYSTEM_BT_2020_C:
case PL_COLOR_SYSTEM_YCGCO:
return true;
default: abort();
};
}
enum pl_color_system pl_color_system_guess_ycbcr(int width, int height)
{
if (width >= 1280 || height > 576) {
// Typical HD content
return PL_COLOR_SYSTEM_BT_709;
} else {
// Typical SD content
return PL_COLOR_SYSTEM_BT_601;
}
}
const struct pl_color_repr pl_color_repr_unknown = {0};
void pl_color_repr_merge(struct pl_color_repr *orig,
const struct pl_color_repr *new)
{
if (!orig->sys)
orig->sys = new->sys;
if (!orig->levels)
orig->levels = new->levels;
if (!orig->bit_depth)
orig->bit_depth = new->bit_depth;
}
bool pl_color_repr_equal(struct pl_color_repr c1, struct pl_color_repr c2)
{
return c1.sys == c2.sys &&
c1.levels == c2.levels &&
c1.bit_depth == c2.bit_depth;
}
float pl_color_repr_texture_mul(struct pl_color_repr repr, int new_bits)
{
int old_bits = repr.bit_depth;
int hi_bits = old_bits > new_bits ? old_bits : new_bits;
int lo_bits = old_bits < new_bits ? old_bits : new_bits;
assert(hi_bits >= lo_bits);
float mult = 1.0;
if (!hi_bits || !lo_bits)
return mult;
if (pl_color_system_is_ycbcr_like(repr.sys)) {
// High bit depth YUV uses a range shifted from 8-bit
mult = (1LL << lo_bits) / ((1LL << hi_bits) - 1.0) * 255.0 / 256;
} else {
// Non-YUV always uses the full range available
mult = ((1LL << lo_bits) - 1.) / ((1LL << hi_bits) - 1.);
}
return new_bits >= old_bits ? mult : 1.0 / mult;
}
bool pl_color_primaries_is_wide_gamut(enum pl_color_primaries prim)
{
switch (prim) {
case PL_COLOR_PRIM_UNKNOWN:
case PL_COLOR_PRIM_BT_601_525:
case PL_COLOR_PRIM_BT_601_625:
case PL_COLOR_PRIM_BT_709:
case PL_COLOR_PRIM_BT_470M:
return false;
case PL_COLOR_PRIM_BT_2020:
case PL_COLOR_PRIM_APPLE:
case PL_COLOR_PRIM_ADOBE:
case PL_COLOR_PRIM_PRO_PHOTO:
case PL_COLOR_PRIM_CIE_1931:
case PL_COLOR_PRIM_DCI_P3:
case PL_COLOR_PRIM_V_GAMUT:
case PL_COLOR_PRIM_S_GAMUT:
return true;
default: abort();
}
}
enum pl_color_primaries pl_color_primaries_guess(int width, int height)
{
// HD content
if (width >= 1280 || height > 576)
return PL_COLOR_PRIM_BT_709;
switch (height) {
case 576: // Typical PAL content, including anamorphic/squared
return PL_COLOR_PRIM_BT_601_625;
case 480: // Typical NTSC content, including squared
case 486: // NTSC Pro or anamorphic NTSC
return PL_COLOR_PRIM_BT_601_525;
default: // No good metric, just pick BT.709 to minimize damage
return PL_COLOR_PRIM_BT_709;
}
}
float pl_color_transfer_nominal_peak(enum pl_color_transfer trc)
{
switch (trc) {
case PL_COLOR_TRC_UNKNOWN:
case PL_COLOR_TRC_BT_1886:
case PL_COLOR_TRC_SRGB:
case PL_COLOR_TRC_LINEAR:
case PL_COLOR_TRC_GAMMA18:
case PL_COLOR_TRC_GAMMA22:
case PL_COLOR_TRC_GAMMA28:
case PL_COLOR_TRC_PRO_PHOTO:
return 1.0;
case PL_COLOR_TRC_PQ: return 10000.0 / PL_COLOR_REF_WHITE;
case PL_COLOR_TRC_HLG: return 12.0;
case PL_COLOR_TRC_V_LOG: return 46.0855;
case PL_COLOR_TRC_S_LOG1: return 6.52;
case PL_COLOR_TRC_S_LOG2: return 9.212;
default: abort();
}
}
bool pl_color_light_is_scene_referred(enum pl_color_light light)
{
switch (light) {
case PL_COLOR_LIGHT_UNKNOWN:
case PL_COLOR_LIGHT_DISPLAY:
return false;
case PL_COLOR_LIGHT_SCENE_HLG:
case PL_COLOR_LIGHT_SCENE_709_1886:
case PL_COLOR_LIGHT_SCENE_1_2:
return true;
default: abort();
}
}
const struct pl_color_space pl_color_space_unknown = {0};
const struct pl_color_space pl_color_space_srgb = {
.primaries = PL_COLOR_PRIM_BT_709,
.transfer = PL_COLOR_TRC_SRGB,
.light = PL_COLOR_LIGHT_DISPLAY,
};
const struct pl_color_space pl_color_space_bt709 = {
.primaries = PL_COLOR_PRIM_BT_709,
.transfer = PL_COLOR_TRC_BT_1886,
.light = PL_COLOR_LIGHT_DISPLAY,
};
const struct pl_color_space pl_color_space_hdr10 = {
.primaries = PL_COLOR_PRIM_BT_2020,
.transfer = PL_COLOR_TRC_PQ,
.light = PL_COLOR_LIGHT_DISPLAY,
};
const struct pl_color_space pl_color_space_bt2020_hlg = {
.primaries = PL_COLOR_PRIM_BT_2020,
.transfer = PL_COLOR_TRC_HLG,
.light = PL_COLOR_LIGHT_SCENE_HLG,
};
void pl_color_space_merge(struct pl_color_space *orig,
const struct pl_color_space *new)
{
if (!orig->primaries)
orig->primaries = new->primaries;
if (!orig->transfer)
orig->transfer = new->transfer;
if (!orig->light)
orig->light = new->light;
if (!orig->sig_peak)
orig->sig_peak = new->sig_peak;
}
bool pl_color_space_equal(struct pl_color_space c1, struct pl_color_space c2)
{
return c1.primaries == c2.primaries &&
c1.transfer == c2.transfer &&
c1.light == c2.light &&
c1.sig_peak == c2.sig_peak;
}
const struct pl_color_adjustment pl_color_adjustment_neutral = {
.brightness = 0.0,
.contrast = 1.0,
.saturation = 1.0,
.hue = 0.0,
.gamma = 1.0,
};
void pl_chroma_location_offset(enum pl_chroma_location loc, int *x, int *y)
{
switch (loc) {
case PL_CHROMA_UNKNOWN:
case PL_CHROMA_CENTER:
*x = 0;
*y = 0;
return;
case PL_CHROMA_LEFT:
*x = -1;
*y = 0;
return;
default: abort();
}
}
struct pl_raw_primaries pl_raw_primaries_get(enum pl_color_primaries prim)
{
/*
Values from: ITU-R Recommendations BT.470-6, BT.601-7, BT.709-5, BT.2020-0
https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-6-199811-S!!PDF-E.pdf
https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.601-7-201103-I!!PDF-E.pdf
https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.709-5-200204-I!!PDF-E.pdf
https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.2020-0-201208-I!!PDF-E.pdf
Other colorspaces from https://en.wikipedia.org/wiki/RGB_color_space#Specifications
*/
// CIE standard illuminant series
static const struct pl_cie_xy
d50 = {0.34577, 0.35850},
d65 = {0.31271, 0.32902},
c = {0.31006, 0.31616},
e = {1.0/3.0, 1.0/3.0};
switch (prim) {
case PL_COLOR_PRIM_BT_470M:
return (struct pl_raw_primaries) {
.red = {0.670, 0.330},
.green = {0.210, 0.710},
.blue = {0.140, 0.080},
.white = c
};
case PL_COLOR_PRIM_BT_601_525:
return (struct pl_raw_primaries) {
.red = {0.630, 0.340},
.green = {0.310, 0.595},
.blue = {0.155, 0.070},
.white = d65
};
case PL_COLOR_PRIM_BT_601_625:
return (struct pl_raw_primaries) {
.red = {0.640, 0.330},
.green = {0.290, 0.600},
.blue = {0.150, 0.060},
.white = d65
};
// This is the default assumption if no colorspace information could
// be determined, eg. for files which have no video channel.
case PL_COLOR_PRIM_UNKNOWN:
case PL_COLOR_PRIM_BT_709:
return (struct pl_raw_primaries) {
.red = {0.640, 0.330},
.green = {0.300, 0.600},
.blue = {0.150, 0.060},
.white = d65
};
case PL_COLOR_PRIM_BT_2020:
return (struct pl_raw_primaries) {
.red = {0.708, 0.292},
.green = {0.170, 0.797},
.blue = {0.131, 0.046},
.white = d65
};
case PL_COLOR_PRIM_APPLE:
return (struct pl_raw_primaries) {
.red = {0.625, 0.340},
.green = {0.280, 0.595},
.blue = {0.115, 0.070},
.white = d65
};
case PL_COLOR_PRIM_ADOBE:
return (struct pl_raw_primaries) {
.red = {0.640, 0.330},
.green = {0.210, 0.710},
.blue = {0.150, 0.060},
.white = d65
};
case PL_COLOR_PRIM_PRO_PHOTO:
return (struct pl_raw_primaries) {
.red = {0.7347, 0.2653},
.green = {0.1596, 0.8404},
.blue = {0.0366, 0.0001},
.white = d50
};
case PL_COLOR_PRIM_CIE_1931:
return (struct pl_raw_primaries) {
.red = {0.7347, 0.2653},
.green = {0.2738, 0.7174},
.blue = {0.1666, 0.0089},
.white = e
};
// From SMPTE RP 431-2
case PL_COLOR_PRIM_DCI_P3:
return (struct pl_raw_primaries) {
.red = {0.680, 0.320},
.green = {0.265, 0.690},
.blue = {0.150, 0.060},
.white = d65
};
// From Panasonic VARICAM reference manual
case PL_COLOR_PRIM_V_GAMUT:
return (struct pl_raw_primaries) {
.red = {0.730, 0.280},
.green = {0.165, 0.840},
.blue = {0.100, -0.03},
.white = d65
};
// From Sony S-Log reference manual
case PL_COLOR_PRIM_S_GAMUT:
return (struct pl_raw_primaries) {
.red = {0.730, 0.280},
.green = {0.140, 0.855},
.blue = {0.100, -0.05},
.white = d65
};
default: abort();
}
}
static void invert_matrix3x3(float m[3][3])
{
float m00 = m[0][0], m01 = m[0][1], m02 = m[0][2],
m10 = m[1][0], m11 = m[1][1], m12 = m[1][2],
m20 = m[2][0], m21 = m[2][1], m22 = m[2][2];
// calculate the adjoint
m[0][0] = (m11 * m22 - m21 * m12);
m[0][1] = -(m01 * m22 - m21 * m02);
m[0][2] = (m01 * m12 - m11 * m02);
m[1][0] = -(m10 * m22 - m20 * m12);
m[1][1] = (m00 * m22 - m20 * m02);
m[1][2] = -(m00 * m12 - m10 * m02);
m[2][0] = (m10 * m21 - m20 * m11);
m[2][1] = -(m00 * m21 - m20 * m01);
m[2][2] = (m00 * m11 - m10 * m01);
// calculate the determinant (as inverse == 1/det * adjoint,
// adjoint * m == identity * det, so this calculates the det)
float det = m00 * m[0][0] + m10 * m[0][1] + m20 * m[0][2];
det = 1.0f / det;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
m[i][j] *= det;
}
}
// A := A * B
static void mul_matrix3x3(float a[3][3], float b[3][3])
{
float a00 = a[0][0], a01 = a[0][1], a02 = a[0][2],
a10 = a[1][0], a11 = a[1][1], a12 = a[1][2],
a20 = a[2][0], a21 = a[2][1], a22 = a[2][2];
for (int i = 0; i < 3; i++) {
a[0][i] = a00 * b[0][i] + a01 * b[1][i] + a02 * b[2][i];
a[1][i] = a10 * b[0][i] + a11 * b[1][i] + a12 * b[2][i];
a[2][i] = a20 * b[0][i] + a21 * b[1][i] + a22 * b[2][i];
}
}
struct pl_color_matrix pl_color_matrix_invert(struct pl_color_matrix out)
{
invert_matrix3x3(out.m);
return out;
}
// based on DarkPlaces engine (relicensed from GPL to LGPL)
struct pl_color_transform pl_color_transform_invert(struct pl_color_transform in)
{
struct pl_color_transform out = { .mat = pl_color_matrix_invert(in.mat) };
float m00 = out.mat.m[0][0], m01 = out.mat.m[0][1], m02 = out.mat.m[0][2],
m10 = out.mat.m[1][0], m11 = out.mat.m[1][1], m12 = out.mat.m[1][2],
m20 = out.mat.m[2][0], m21 = out.mat.m[2][1], m22 = out.mat.m[2][2];
// fix the constant coefficient
// rgb = M * yuv + C
// M^-1 * rgb = yuv + M^-1 * C
// yuv = M^-1 * rgb - M^-1 * C
// ^^^^^^^^^^
out.c[0] = -(m00 * in.c[0] + m01 * in.c[1] + m02 * in.c[2]);
out.c[1] = -(m10 * in.c[0] + m11 * in.c[1] + m12 * in.c[2]);
out.c[2] = -(m20 * in.c[0] + m21 * in.c[1] + m22 * in.c[2]);
return out;
}
// Compute the RGB/XYZ matrix as described here:
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
struct pl_color_matrix pl_get_rgb2xyz_matrix(struct pl_raw_primaries prim)
{
struct pl_color_matrix out = {{{0}}};
float S[3], X[4], Z[4];
// Convert from CIE xyY to XYZ. Note that Y=1 holds true for all primaries
X[0] = prim.red.x / prim.red.y;
X[1] = prim.green.x / prim.green.y;
X[2] = prim.blue.x / prim.blue.y;
X[3] = prim.white.x / prim.white.y;
Z[0] = (1 - prim.red.x - prim.red.y) / prim.red.y;
Z[1] = (1 - prim.green.x - prim.green.y) / prim.green.y;
Z[2] = (1 - prim.blue.x - prim.blue.y) / prim.blue.y;
Z[3] = (1 - prim.white.x - prim.white.y) / prim.white.y;
// S = XYZ^-1 * W
for (int i = 0; i < 3; i++) {
out.m[0][i] = X[i];
out.m[1][i] = 1;
out.m[2][i] = Z[i];
}
invert_matrix3x3(out.m);
for (int i = 0; i < 3; i++)
S[i] = out.m[i][0] * X[3] + out.m[i][1] * 1 + out.m[i][2] * Z[3];
// M = [Sc * XYZc]
for (int i = 0; i < 3; i++) {
out.m[0][i] = S[i] * X[i];
out.m[1][i] = S[i] * 1;
out.m[2][i] = S[i] * Z[i];
}
return out;
}
struct pl_color_matrix pl_get_xyz2rgb_matrix(struct pl_raw_primaries prim)
{
// For simplicity, just invert the rgb2xyz matrix
struct pl_color_matrix out = pl_get_rgb2xyz_matrix(prim);
invert_matrix3x3(out.m);
return out;
}
// M := M * XYZd<-XYZs
static void apply_chromatic_adaptation(struct pl_cie_xy src,
struct pl_cie_xy dest, float m[3][3])
{
// If the white points are nearly identical, this is a wasteful identity
// operation.
if (fabs(src.x - dest.x) < 1e-6 && fabs(src.y - dest.y) < 1e-6)
return;
// XYZd<-XYZs = Ma^-1 * (I*[Cd/Cs]) * Ma
// http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
float C[3][2], tmp[3][3] = {{0}};
// Ma = Bradford matrix, arguably most popular method in use today.
// This is derived experimentally and thus hard-coded.
float bradford[3][3] = {
{ 0.8951, 0.2664, -0.1614 },
{ -0.7502, 1.7135, 0.0367 },
{ 0.0389, -0.0685, 1.0296 },
};
for (int i = 0; i < 3; i++) {
// source cone
C[i][0] = bradford[i][0] * pl_cie_X(src)
+ bradford[i][1] * 1
+ bradford[i][2] * pl_cie_Z(src);
// dest cone
C[i][1] = bradford[i][0] * pl_cie_X(dest)
+ bradford[i][1] * 1
+ bradford[i][2] * pl_cie_Z(dest);
}
// tmp := I * [Cd/Cs] * Ma
for (int i = 0; i < 3; i++)
tmp[i][i] = C[i][1] / C[i][0];
mul_matrix3x3(tmp, bradford);
// M := M * Ma^-1 * tmp
invert_matrix3x3(bradford);
mul_matrix3x3(m, bradford);
mul_matrix3x3(m, tmp);
}
struct pl_color_matrix pl_get_color_mapping_matrix(struct pl_raw_primaries src,
struct pl_raw_primaries dst,
enum pl_rendering_intent intent)
{
// In saturation mapping, we don't care about accuracy and just want
// primaries to map to primaries, making this an identity transformation.
if (intent == PL_INTENT_SATURATION) {
return (struct pl_color_matrix) {{
{ 1, 0, 0 },
{ 0, 1, 0 },
{ 0, 0, 1 }
}};
}
// RGBd<-RGBs = RGBd<-XYZd * XYZd<-XYZs * XYZs<-RGBs
// Equations from: http://www.brucelindbloom.com/index.html?Math.html
// Note: Perceptual is treated like relative colorimetric. There's no
// definition for perceptual other than "make it look good".
// RGBd<-XYZd matrix
struct pl_color_matrix out = pl_get_xyz2rgb_matrix(dst);
// Chromatic adaptation, except in absolute colorimetric intent
if (intent != PL_INTENT_ABSOLUTE_COLORIMETRIC)
apply_chromatic_adaptation(src.white, dst.white, out.m);
// XYZs<-RGBs
struct pl_color_matrix tmp = pl_get_rgb2xyz_matrix(src);
mul_matrix3x3(out.m, tmp.m);
return out;
}
/* Fill in the Y, U, V vectors of a yuv-to-rgb conversion matrix
* based on the given luma weights of the R, G and B components (lr, lg, lb).
* lr+lg+lb is assumed to equal 1.
* This function is meant for colorspaces satisfying the following
* conditions (which are true for common YUV colorspaces):
* - The mapping from input [Y, U, V] to output [R, G, B] is linear.
* - Y is the vector [1, 1, 1]. (meaning input Y component maps to 1R+1G+1B)
* - U maps to a value with zero R and positive B ([0, x, y], y > 0;
* i.e. blue and green only).
* - V maps to a value with zero B and positive R ([x, y, 0], x > 0;
* i.e. red and green only).
* - U and V are orthogonal to the luma vector [lr, lg, lb].
* - The magnitudes of the vectors U and V are the minimal ones for which
* the image of the set Y=[0...1],U=[-0.5...0.5],V=[-0.5...0.5] under the
* conversion function will cover the set R=[0...1],G=[0...1],B=[0...1]
* (the resulting matrix can be converted for other input/output ranges
* outside this function).
* Under these conditions the given parameters lr, lg, lb uniquely
* determine the mapping of Y, U, V to R, G, B.
*/
static struct pl_color_matrix luma_coeffs(float lr, float lg, float lb)
{
assert(fabs(lr+lg+lb - 1) < 1e-6);
return (struct pl_color_matrix) {{
{1, 0, 2 * (1-lr) },
{1, -2 * (1-lb) * lb/lg, -2 * (1-lr) * lr/lg },
{1, 2 * (1-lb), 0 },
}};
}
struct pl_color_transform pl_get_decoding_matrix(struct pl_color_repr repr,
struct pl_color_adjustment params,
enum pl_color_levels out_levels,
int out_bits)
{
struct pl_color_matrix m;
switch (repr.sys) {
case PL_COLOR_SYSTEM_UNKNOWN: // fall through
case PL_COLOR_SYSTEM_BT_709: m = luma_coeffs(0.2126, 0.7152, 0.0722); break;
case PL_COLOR_SYSTEM_BT_601: m = luma_coeffs(0.2990, 0.5870, 0.1140); break;
case PL_COLOR_SYSTEM_SMPTE_240M: m = luma_coeffs(0.2122, 0.7013, 0.0865); break;
case PL_COLOR_SYSTEM_BT_2020_NC: m = luma_coeffs(0.2627, 0.6780, 0.0593); break;
case PL_COLOR_SYSTEM_BT_2020_C:
// Note: This outputs into the [-0.5,0.5] range for chroma information.
m = (struct pl_color_matrix) {{
{0, 0, 1},
{1, 0, 0},
{0, 1, 0}
}};
break;
case PL_COLOR_SYSTEM_YCGCO:
m = (struct pl_color_matrix) {{
{1, -1, 1},
{1, 1, 0},
{1, -1, -1},
}};
break;
case PL_COLOR_SYSTEM_RGB:
m = (struct pl_color_matrix) {{
{1, 0, 0},
{0, 1, 0},
{0, 0, 1}
}};
break;
case PL_COLOR_SYSTEM_XYZ:
// For lack of anything saner to do, just assume the caller wants
// BT.709 primaries, which is a reasonable assumption.
m = pl_get_xyz2rgb_matrix(pl_raw_primaries_get(PL_COLOR_PRIM_BT_709));
break;
default: abort();
}
struct pl_color_transform out = { .mat = m };
// Apply hue and saturation in the correct way depending on the colorspace.
if (pl_color_system_is_ycbcr_like(repr.sys)) {
// Hue is equivalent to rotating input [U, V] subvector around the origin.
// Saturation scales [U, V].
float huecos = params.saturation * cos(params.hue);
float huesin = params.saturation * sin(params.hue);
for (int i = 0; i < 3; i++) {
float u = out.mat.m[i][1], v = out.mat.m[i][2];
out.mat.m[i][1] = huecos * u - huesin * v;
out.mat.m[i][2] = huesin * u + huecos * v;
}
}
// FIXME: apply saturation for RGB
float s = 1.0;
if (repr.bit_depth && out_bits)
s = pl_color_repr_texture_mul(repr, out_bits);
// As a convenience, we use the 255-scale values in the code below
s /= 255.0;
// NOTE: The yuvfull ranges as presented here are arguably ambiguous,
// and conflict with at least the full-range YCbCr/ICtCp values as defined
// by ITU-R BT.2100. If somebody ever complains about full-range YUV looking
// different from their reference display, this comment is probably why.
struct yuvlevels { double ymin, ymax, cmax, cmid; }
yuvlim = { 16*s, 235*s, 240*s, 128*s },
yuvfull = { 0*s, 255*s, 255*s, 128*s },
anyfull = { 0*s, 255*s, 255*s/2, 0 }, // cmax picked to make cmul=ymul
yuvlev;
if (pl_color_system_is_ycbcr_like(repr.sys)) {
switch (repr.levels) {
case PL_COLOR_LEVELS_UNKNOWN: // fall through
case PL_COLOR_LEVELS_TV: yuvlev = yuvlim; break;
case PL_COLOR_LEVELS_PC: yuvlev = yuvfull; break;
default: abort();
}
} else {
yuvlev = anyfull;
}
struct rgblevels { double min, max; }
rgblim = { 16/255., 235/255. },
rgbfull = { 0, 1 },
rgblev;
switch (out_levels) {
case PL_COLOR_LEVELS_UNKNOWN: // fall through
case PL_COLOR_LEVELS_PC: rgblev = rgbfull; break;
case PL_COLOR_LEVELS_TV: rgblev = rgblim; break;
default: abort();
}
double ymul = (rgblev.max - rgblev.min) / (yuvlev.ymax - yuvlev.ymin);
double cmul = (rgblev.max - rgblev.min) / (yuvlev.cmax - yuvlev.cmid) / 2;
// Contrast scales the output value range (gain)
ymul *= params.contrast;
cmul *= params.contrast;
for (int i = 0; i < 3; i++) {
out.mat.m[i][0] *= ymul;
out.mat.m[i][1] *= cmul;
out.mat.m[i][2] *= cmul;
// Set c so that Y=umin,UV=cmid maps to RGB=min (black to black),
// also add brightness offset (black lift)
out.c[i] = rgblev.min - out.mat.m[i][0] * yuvlev.ymin
- (out.mat.m[i][1] + out.mat.m[i][2]) * yuvlev.cmid
+ params.brightness;
}
return out;
}
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include "ta/talloc.h"
#include "config.h"
// Include all of the symbols that should be public in a way that marks them
// as being externally visible. (Otherwise, all symbols are hidden by default)
#pragma GCC visibility push(default)
#include "public/colorspace.h"
#include "public/common.h"
#include "public/context.h"
#include "public/filters.h"
#include "public/ra.h"
#include "public/shaders.h"
#pragma GCC visibility pop
// Align up to the nearest multiple of an arbitrary alignment, which may also
// be 0 to signal no alignment requirements.
#define PL_ALIGN(x, align) ((align) ? ((x) + (align) - 1) / (align) * (align) : (x))
// This is faster but must only be called on positive powers of two.
#define PL_ALIGN2(x, align) (((x) + (align) - 1) & ~((align) - 1))
// Returns the size of a static array with known size.
#define PL_ARRAY_SIZE(s) (sizeof(s) / sizeof((s)[0]))
// Swaps two variables
#define PL_SWAP(a, b) \
do { \
__typeof__ tmp = (a); \
(a) = (b); \
(b) = tmp; \
} while (0)
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBPLACEBO_CONFIG_H_
#define LIBPLACEBO_CONFIG_H_
// Increased any time the API changes.
#define PL_API_VER @apiver@
#endif // LIBPLACEBO_CONTEXT_H_
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include "common.h"
#include "context.h"
struct pl_context *pl_context_create(int api_ver)
{
if (api_ver != PL_API_VER) {
fprintf(stderr,
"*************************************************************\n"
"libplacebo: ABI mismatch detected!\n\n"
"This is usually indicative of a linking mismatch, and will\n"
"result in serious issues including stack corruption, random\n"
"crashes and arbitrary code exection. Aborting as a safety\n"
"precaution!\n");
abort();
}
struct pl_context *ctx = talloc_zero(NULL, struct pl_context);
return ctx;
}
void pl_context_destroy(struct pl_context **ctx)
{
TA_FREEP(ctx);
}
void pl_context_set_log_cb(struct pl_context *ctx, void *priv,
void (*fun)(void *priv, enum pl_log_level level,
const char *msg))
{
ctx->logfun = fun;
ctx->logpriv = priv;
}
void pl_context_set_log_level(struct pl_context *ctx, enum pl_log_level level)
{
ctx->loglevel = level;
}
void pl_msg(struct pl_context *ctx, enum pl_log_level lev, const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
pl_msg_va(ctx, lev, fmt, va);
va_end(va);
}
void pl_msg_va(struct pl_context *ctx, enum pl_log_level lev, const char *fmt,
va_list va)
{
if (!pl_msg_test(ctx, lev))
return;
ctx->logbuffer.len = 0;
bstr_xappend_vasprintf(ctx, &ctx->logbuffer, fmt, va);
ctx->logfun(ctx->logpriv, lev, ctx->logbuffer.start);
}
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdarg.h>
#include "bstr/bstr.h"
#include "common.h"
struct pl_context {
// Logging-related state:
enum pl_log_level loglevel;
struct bstr logbuffer;
void *logpriv;
void (*logfun)(void *priv, enum pl_log_level level, const char *msg);
};
// Logging-related functions
static inline bool pl_msg_test(struct pl_context *ctx, enum pl_log_level lev)
{
return ctx->logfun && ctx->loglevel >= lev;
}
void pl_msg(struct pl_context *ctx, enum pl_log_level lev, const char *fmt, ...)
PRINTF_ATTRIBUTE(3, 4);
void pl_msg_va(struct pl_context *ctx, enum pl_log_level lev, const char *fmt,
va_list va);
// Convenience macros
#define pl_fatal(log, ...) pl_msg(ctx, PL_LOG_FATAL, __VA_ARGS__)
#define pl_err(log, ...) pl_msg(ctx, PL_LOG_ERR, __VA_ARGS__)
#define pl_warn(log, ...) pl_msg(ctx, PL_LOG_WARN, __VA_ARGS__)
#define pl_info(log, ...) pl_msg(ctx, PL_LOG_INFO, __VA_ARGS__)
#define pl_debug(log, ...) pl_msg(ctx, PL_LOG_DEBUG, __VA_ARGS__)
#define pl_trace(log, ...) pl_msg(ctx, PL_LOG_TRACE, __VA_ARGS__)
#define PL_MSG(obj, lev, ...) pl_msg((obj)->ctx, lev, __VA_ARGS__)
#define PL_FATAL(obj, ...) PL_MSG(obj, PL_LOG_FATAL, __VA_ARGS__)
#define PL_ERR(obj, ...) PL_MSG(obj, PL_LOG_ERR, __VA_ARGS__)
#define PL_WARN(obj, ...) PL_MSG(obj, PL_LOG_WARN, __VA_ARGS__)
#define PL_INFO(obj, ...) PL_MSG(obj, PL_LOG_INFO, __VA_ARGS__)
#define PL_DEBUG(obj, ...) PL_MSG(obj, PL_LOG_DEBUG, __VA_ARGS__)
#define PL_TRACE(obj, ...) PL_MSG(obj, PL_LOG_TRACE, __VA_ARGS__)
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Some of the filter code originally derives (via mpv) from Glumpy:
* # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
* # Distributed under the (new) BSD License.
* (https://github.com/glumpy/glumpy/blob/master/glumpy/library/build-spatial-filters.py)
*
* The math underlying each filter function was written from scratch, with
* some algorithms coming from a number of different sources, including:
* - https://en.wikipedia.org/wiki/Window_function
* - https://en.wikipedia.org/wiki/Jinc
* - http://vector-agg.cvs.sourceforge.net/viewvc/vector-agg/agg-2.5/include/agg_image_filters.h
* - Vapoursynth plugin fmtconv (WTFPL Licensed), which is based on
* dither plugin for avisynth from the same author:
* https://github.com/vapoursynth/fmtconv/tree/master/src/fmtc
* - Paul Heckbert's "zoom"
* - XBMC: ConvolutionKernels.cpp etc.
* - https://github.com/AviSynth/jinc-resize (only used to verify the math)
*/
#include <math.h>
#include "common.h"
#include "context.h"
double pl_filter_sample(const struct pl_filter_config *c, double x)
{
double radius = c->kernel->radius;
// All filters are symmetric, and in particular only need to be defined
// for [0, radius].
x = fabs(x);
// Apply the blur and taper coefficients as needed
x = c->blur > 0.0 ? x / c->blur : x;
x = x <= c->taper ? 0.0 : (x - c->taper) / (1.0 - c->taper / radius);
// Return early for values outside of the kernel radius, since the functions
// are not necessarily valid outside of this interval. No such check is
// needed for the window, because it's always stretched to fit.
if (x > radius)
return 0.0;
double k = c->kernel->weight(c->kernel, x);
// Apply the optional windowing function
if (c->window)
k *= c->window->weight(c->window, x / radius * c->window->radius);
return k < 0 ? (1 - c->clamp) * k : k;
}
// Calculate a single filter row of a 1D filter, for a given phase value /
// subpixel offset `offset`. Writes exactly f->row_size values to *out.
static void compute_row(struct pl_filter *f, double offset, float *out)
{
assert(f->row_size > 0);
double sum = 0;
for (int i = 0; i < f->row_size; i++) {
double x = offset - (i - f->row_size / 2 + 1);
// Readjust the value range to account for a stretched kernel.
x *= f->params.config.kernel->radius / f->radius;
double weight = pl_filter_sample(&f->params.config, x);
out[i] = weight;
sum += weight;
}
// Normalize to preserve energy
if (sum > 0.0) {
for (int i = 0; i < f->row_size; i++)
out[i] /= sum;
}
}
static struct pl_filter_function *dupfilter(void *tactx,
const struct pl_filter_function *f)
{
return f ? talloc_memdup(tactx, (void *)f, sizeof(*f)) : NULL;
}
const struct pl_filter *pl_filter_generate(struct pl_context *ctx,
const struct pl_filter_params *params)
{
if (params->lut_entries <= 0 || !params->config.kernel) {
pl_fatal(ctx, "pl_filter_generate: Invalid params: missing lut_entries "
"or config.kernel\n");
return NULL;
}
struct pl_filter *f = talloc_zero(ctx, struct pl_filter);
f->params = *params;
f->params.config.kernel = dupfilter(f, params->config.kernel);
f->params.config.window = dupfilter(f, params->config.window);
// Compute the required filter radius
float radius = f->params.config.kernel->radius;
f->radius = radius;
if (params->filter_scale > 1.0)
f->radius *= params->filter_scale;
float *weights;
if (params->config.polar) {
// Compute a 1D array indexed by radius
weights = talloc_array(f, float, params->lut_entries);
f->radius_cutoff = 0.0;
for (int i = 0; i < params->lut_entries; i++) {
double x = radius * i / (params->lut_entries - 1);
weights[i] = pl_filter_sample(&f->params.config, x);
if (fabs(weights[i]) > params->cutoff)
f->radius_cutoff = x;
}
} else {
// Pick the most appropriate row size
f->row_size = ceil(f->radius * 2.0);
if (f->row_size > params->max_row_size) {
pl_info(ctx, "Required filter size %d exceeds the maximum allowed "
"size of %d. This may result in adverse effects (aliasing, "
"or moiré artifacts).", f->row_size, params->max_row_size);
f->row_size = params->max_row_size;
f->insufficient = true;
}
f->row_stride = PL_ALIGN(f->row_size, params->row_stride_align);
// Compute a 2D array indexed by the subpixel position
weights = talloc_zero_array(f, float, params->lut_entries * f->row_stride);
for (int i = 0; i < params->lut_entries; i++) {
compute_row(f, i / (double)(params->lut_entries - 1),
weights + f->row_stride * i);
}
}
f->weights = weights;
return f;
}
void pl_filter_free(const struct pl_filter **filter)
{
TA_FREEP((void **) filter);
}
const struct pl_named_filter_function *pl_find_named_filter_function(const char *name)
{
if (!name)
return NULL;
for (int i = 0; pl_named_filter_functions[i].function; i++) {
if (strcmp(pl_named_filter_functions[i].name, name) == 0)
return &pl_named_filter_functions[i];
}
return NULL;
}
const struct pl_named_filter_config *pl_find_named_filter(const char *name)
{
if (!name)
return NULL;
for (int i = 0; pl_named_filters[i].filter; i++) {
if (strcmp(pl_named_filters[i].name, name) == 0)
return &pl_named_filters[i];
}
return NULL;
}
// Built-in filter functions
static double box(const struct pl_filter_function *f, double x)
{
return 1.0;
}
const struct pl_filter_function pl_filter_function_box = {
.resizable = true,
.weight = box,
.radius = 0.5,
};
static double triangle(const struct pl_filter_function *f, double x)
{
return 1.0 - x / f->radius;
}
const struct pl_filter_function pl_filter_function_triangle = {
.resizable = true,
.weight = triangle,
.radius = 1.0,
};
static double hann(const struct pl_filter_function *f, double x)
{
return 0.5 + 0.5 * cos(M_PI * x);
}
const struct pl_filter_function pl_filter_function_hann = {
.weight = hann,
.radius = 1.0,
};
static double hamming(const struct pl_filter_function *f, double x)
{
return 0.54 + 0.46 * cos(M_PI * x);
}
const struct pl_filter_function pl_filter_function_hamming = {
.weight = hamming,
.radius = 1.0,
};
static double welch(const struct pl_filter_function *f, double x)
{
return 1.0 - x * x;
}
const struct pl_filter_function pl_filter_function_welch = {
.weight = welch,
.radius = 1.0,
};
static double bessel_i0(double x)
{
double s = 1.0;
double y = x * x / 4.0;
double t = y;
int i = 2;
while (t > 1e-12) {
s += t;
t *= y / (i * i);
i += 1;
}
return s;
}
static double kaiser(const struct pl_filter_function *f, double x)
{
double alpha = fmax(f->params[0], 0.0);
return bessel_i0(alpha * sqrt(1.0 - x * x)) / alpha;
}
const struct pl_filter_function pl_filter_function_kaiser = {
.tunable = {true},
.weight = kaiser,
.radius = 1.0,
.params = {2.0},
};
static double blackman(const struct pl_filter_function *f, double x)
{
double a = f->params[0];
double a0 = (1 - a) / 2.0, a1 = 1 / 2.0, a2 = a / 2.0;
x *= M_PI;
return a0 + a1 * cos(x) + a2 * cos(2 * x);
}
const struct pl_filter_function pl_filter_function_blackman = {
.tunable = {true},
.weight = blackman,
.radius = 1.0,
.params = {0.16},
};
static double gaussian(const struct pl_filter_function *f, double x)
{
return exp(-2.0 * x * x / f->params[0]);
}
const struct pl_filter_function pl_filter_function_gaussian = {
.resizable = true,
.tunable = {true},
.weight = gaussian,
.radius = 2.0,
.params = {1.0},
};
static double sinc(const struct pl_filter_function *f, double x)
{
if (x < 1e-8)
return 1.0;
x *= M_PI;
return sin(x) / x;
}
const struct pl_filter_function pl_filter_function_sinc = {
.resizable = true,
.weight = sinc,
.radius = 1.0,
};
static double jinc(const struct pl_filter_function *f, double x)
{
if (x < 1e-8)
return 1.0;
x *= M_PI;
return 2.0 * j1(x) / x;
}
const struct pl_filter_function pl_filter_function_jinc = {
.resizable = true,
.weight = jinc,
.radius = 1.2196698912665045, // first zero
};
static double sphinx(const struct pl_filter_function *f, double x)
{
if (x < 1e-8)
return 1.0;
x *= M_PI;
return 3.0 * (sin(x) - x * cos(x)) / (x * x * x);
}
const struct pl_filter_function pl_filter_function_sphinx = {
.resizable = true,
.weight = sphinx,
.radius = 1.4302966531242027, // first zero
};
static double bcspline(const struct pl_filter_function *f, double x)
{
double b = f->params[0],
c = f->params[1];
double p0 = (6.0 - 2.0 * b) / 6.0,
p2 = (-18.0 + 12.0 * b + 6.0 * c) / 6.0,
p3 = (12.0 - 9.0 * b - 6.0 * c) / 6.0,
q0 = (8.0 * b + 24.0 * c) / 6.0,
q1 = (-12.0 * b - 48.0 * c) / 6.0,
q2 = (6.0 * b + 30.0 * c) / 6.0,
q3 = (-b - 6.0 * c) / 6.0;
if (x < 1.0) {
return p0 + x * x * (p2 + x * p3);
} else if (x < 2.0) {
return q0 + x * (q1 + x * (q2 + x * q3));
}
return 0.0;
}
const struct pl_filter_function pl_filter_function_bcspline = {
.tunable = {true, true},
.weight = bcspline,
.radius = 2.0,
.params = {0.5, 0.5},
};
const struct pl_filter_function pl_filter_function_catmull_rom = {
.tunable = {true, true},
.weight = bcspline,
.radius = 2.0,
.params = {0.0, 0.5},
};
const struct pl_filter_function pl_filter_function_mitchell = {
.tunable = {true, true},
.weight = bcspline,
.radius = 2.0,
.params = {1/3.0, 1/3.0},
};
const struct pl_filter_function pl_filter_function_robidoux = {
.tunable = {true, true},
.weight = bcspline,
.radius = 2.0,
.params = {12 / (19 + 9 * M_SQRT2), 113 / (58 + 216 * M_SQRT2)},
};
const struct pl_filter_function pl_filter_function_robidouxsharp = {
.tunable = {true, true},
.weight = bcspline,
.radius = 2.0,
.params = {6 / (13 + 7 * M_SQRT2), 7 / (2 + 12 * M_SQRT2)},
};
#define POW3(x) ((x) <= 0 ? 0 : (x) * (x) * (x))
static double bicubic(const struct pl_filter_function *f, double x)
{
return (1.0/6.0) * ( 1 * POW3(x + 2)
- 4 * POW3(x + 1)
+ 6 * POW3(x + 0)
- 4 * POW3(x - 1));
}
const struct pl_filter_function pl_filter_function_bicubic = {
.weight = bicubic,
.radius = 2.0,
};
static double spline16(const struct pl_filter_function *f, double x)
{
if (x < 1.0) {
return ((x - 9.0/5.0 ) * x - 1.0/5.0 ) * x + 1.0;
} else {
return ((-1.0/3.0 * (x-1) + 4.0/5.0) * (x-1) - 7.0/15.0 ) * (x-1);
}
}
const struct pl_filter_function pl_filter_function_spline16 = {
.weight = spline16,
.radius = 2.0,
};
static double spline36(const struct pl_filter_function *f, double x)
{
if (x < 1.0) {
return ((13.0/11.0 * x - 453.0/209.0) * x - 3.0/209.0) * x + 1.0;
} else if (x < 2.0) {
return ((-6.0/11.0 * (x-1) + 270.0/209.0) * (x-1) - 156.0/ 209.0) * (x-1);
} else {
return ((1.0/11.0 * (x-2) - 45.0/209.0) * (x-2) + 26.0/209.0) * (x-2);
}
}
const struct pl_filter_function pl_filter_function_spline36 = {
.weight = spline36,
.radius = 3.0,
};
static double spline64(const struct pl_filter_function *f, double x)
{
if (x < 1.0) {
return ((49.0/41.0 * x - 6387.0/2911.0) * x - 3.0/2911.0) * x + 1.0;
} else if (x < 2.0) {
return ((-24.0/41.0 * (x-1) + 4032.0/2911.0) * (x-1) - 2328.0/2911.0) * (x-1);
} else if (x < 3.0) {
return ((6.0/41.0 * (x-2) - 1008.0/2911.0) * (x-2) + 582.0/2911.0) * (x-2);
} else {
return ((-1.0/41.0 * (x-3) + 168.0/2911.0) * (x-3) - 97.0/2911.0) * (x-3);
}
}
const struct pl_filter_function pl_filter_function_spline64 = {
.weight = spline64,
.radius = 4.0,
};
// Named filter functions
const struct pl_named_filter_function pl_named_filter_functions[] = {
{"box", &pl_filter_function_box},
{"dirichlet", &pl_filter_function_box}, // alias
{"triangle", &pl_filter_function_triangle},
{"hann", &pl_filter_function_hann},
{"hanning", &pl_filter_function_hann}, // alias
{"hamming", &pl_filter_function_hamming},
{"welch", &pl_filter_function_welch},
{"kaiser", &pl_filter_function_kaiser},
{"blackman", &pl_filter_function_blackman},
{"gaussian", &pl_filter_function_gaussian},
{"sinc", &pl_filter_function_sinc},
{"jinc", &pl_filter_function_jinc},
{"sphinx", &pl_filter_function_sphinx},
{"bcspline", &pl_filter_function_bcspline},
{"hermite", &pl_filter_function_bcspline}, // alias
{"catmull_rom", &pl_filter_function_catmull_rom},
{"mitchell", &pl_filter_function_mitchell},
{"robidoux", &pl_filter_function_robidoux},
{"robidouxsharp", &pl_filter_function_robidouxsharp},
{"bicubic", &pl_filter_function_bicubic},
{"spline16", &pl_filter_function_spline16},
{"spline36", &pl_filter_function_spline36},
{"spline64", &pl_filter_function_spline64},
{0},
};
// Built-in filter function presets
const struct pl_filter_config pl_filter_spline16 = {
.kernel = &pl_filter_function_spline16,
};
const struct pl_filter_config pl_filter_spline36 = {
.kernel = &pl_filter_function_spline36,
};
const struct pl_filter_config pl_filter_spline64 = {
.kernel = &pl_filter_function_spline64,
};
const struct pl_filter_config pl_filter_box = {
.kernel = &pl_filter_function_box,
};
const struct pl_filter_config pl_filter_triangle = {
.kernel = &pl_filter_function_triangle,
};
const struct pl_filter_config pl_filter_gaussian = {
.kernel = &pl_filter_function_gaussian,
};
// Sinc configured to three taps
static const struct pl_filter_function sinc3 = {
.resizable = true,
.weight = sinc,
.radius = 3.0,
};
const struct pl_filter_config pl_filter_sinc = {
.kernel = &sinc3,
};
const struct pl_filter_config pl_filter_lanczos = {
.kernel = &sinc3,
.window = &pl_filter_function_sinc,
};
const struct pl_filter_config pl_filter_ginseng = {
.kernel = &sinc3,
.window = &pl_filter_function_jinc,
};
// Jinc configured to three taps
static const struct pl_filter_function jinc3 = {
.resizable = true,
.weight = jinc,
.radius = 3.2383154841662362, // third zero
};
const struct pl_filter_config pl_filter_ewa_jinc = {
.kernel = &jinc3,
.polar = true,
};
const struct pl_filter_config pl_filter_ewa_lanczos = {
.kernel = &jinc3,
.window = &pl_filter_function_jinc,
.polar = true,
};
const struct pl_filter_config pl_filter_ewa_ginseng = {
.kernel = &jinc3,
.window = &pl_filter_function_sinc,
.polar = true,
};
const struct pl_filter_config pl_filter_ewa_hann = {
.kernel = &jinc3,
.window = &pl_filter_function_hann,
.polar = true,
};
const struct pl_filter_config pl_filter_haasnsoft = {
.kernel = &jinc3,
.window = &pl_filter_function_hann,
// The blur is tuned to equal out orthogonal and diagonal contributions
// on a regular grid. This has the effect of almost completely killing
// aliasing.
.blur = 1.11,
.polar = true,
};
// Spline family
const struct pl_filter_config pl_filter_bicubic = {
.kernel = &pl_filter_function_bicubic,
};
const struct pl_filter_config pl_filter_catmull_rom = {
.kernel = &pl_filter_function_catmull_rom,
};
const struct pl_filter_config pl_filter_mitchell = {
.kernel = &pl_filter_function_mitchell,
};
const struct pl_filter_config pl_filter_robidoux = {
.kernel = &pl_filter_function_robidoux,
};
const struct pl_filter_config pl_filter_robidouxsharp = {
.kernel = &pl_filter_function_robidouxsharp,
};
const struct pl_filter_config pl_filter_ewa_robidoux = {
.kernel = &pl_filter_function_robidoux,
.polar = true,
};
const struct pl_filter_config pl_filter_ewa_robidouxsharp = {
.kernel = &pl_filter_function_robidouxsharp,
.polar = true,
};
// Named filter configs
const struct pl_named_filter_config pl_named_filters[] = {
{"spline16", &pl_filter_spline16},
{"spline36", &pl_filter_spline36},
{"spline64", &pl_filter_spline64},
{"box", &pl_filter_box},
{"nearest", &pl_filter_box}, // alias
{"triangle", &pl_filter_triangle},
{"bilinear", &pl_filter_triangle}, // alias
{"gaussian", &pl_filter_gaussian},
{"sinc", &pl_filter_sinc},
{"lanczos", &pl_filter_lanczos},
{"ginseng", &pl_filter_ginseng},
{"ewa_jinc", &pl_filter_ewa_jinc},
{"ewa_lanczos", &pl_filter_ewa_lanczos},
{"ewa_ginseng", &pl_filter_ewa_ginseng},
{"ewa_hann", &pl_filter_ewa_hann},
{"ewa_hanning", &pl_filter_ewa_hann}, // alias
{"haasnsoft", &pl_filter_haasnsoft},
{"bicubic", &pl_filter_bicubic},
{"catmull_rom", &pl_filter_catmull_rom},
{"mitchell", &pl_filter_mitchell},
{"robidoux", &pl_filter_robidoux},
{"robidouxsharp", &pl_filter_robidouxsharp},
{"ewa_robidoux", &pl_filter_ewa_robidoux},
{"ewa_robidouxsharp", &pl_filter_ewa_robidouxsharp},
{0},
};
# Updated any time the API changes
apiver = 0
# Build options mostly taken from mpv
add_global_arguments([
'-D_ISOC99_SOURCE', '-D_GNU_SOURCE',
'-fvisibility=hidden',
# Warnings
'-Wall', '-Wundef', '-Wmissing-prototypes', '-Wshadow', '-Wparentheses',
'-Wpointer-arith', '-Wno-pointer-sign',
], language: 'c')
cc = meson.get_compiler('c')
# Dependencies
deps = [
# libm
cc.find_library('m', required: false),
]
# Configuration
conf = configuration_data()
conf.set('apiver', apiver)
configure_file(
input: 'config.h.in',
output: 'config.h',
install_dir: 'libplacebo',
configuration: conf,
)
# Source files
sources = [
'colorspace.c',
'context.c',
'filters.c',
'ra.c',
'shaders.c',
# Helpers ported from mpv
'bstr/bstr.c',
'ta/ta.c',
'ta/ta_utils.c',
'ta/talloc.c',
]
shared_library('placebo', sources,
install: true,
dependencies: deps,
soversion: apiver,
)
headers = [
'public/colorspace.h',
'public/common.h',
'public/context.h',
'public/filters.h',
'public/ra.h',
'public/shaders.h',
]
install_headers(headers, subdir: 'libplacebo')
// Copyright (c) 2017 mpv developers
#pragma once
#define MP_EXPAND_ARGS(...) __VA_ARGS__
#ifdef __GNUC__
#define PRINTF_ATTRIBUTE(a1, a2) __attribute__ ((format(printf, a1, a2)))
#define MP_NORETURN __attribute__((noreturn))
#else
#define PRINTF_ATTRIBUTE(a1, a2)
#define MP_NORETURN
#endif
// Broken crap with __USE_MINGW_ANSI_STDIO
#if defined(__MINGW32__) && defined(__GNUC__) && !defined(__clang__)
#undef PRINTF_ATTRIBUTE
#define PRINTF_ATTRIBUTE(a1, a2) __attribute__ ((format (gnu_printf, a1, a2)))
#endif
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBPLACEBO_COLORSPACE_H_
#define LIBPLACEBO_COLORSPACE_H_
#include <stdbool.h>
// The underlying colorspace representation (e.g. RGB, XYZ or YCbCr)
enum pl_color_system {
PL_COLOR_SYSTEM_UNKNOWN = 0,
// YCbCr-like colorspaces:
PL_COLOR_SYSTEM_BT_601, // ITU-R Rec. BT.601 (SD)
PL_COLOR_SYSTEM_BT_709, // ITU-R Rec. BT.709 (HD)
PL_COLOR_SYSTEM_SMPTE_240M, // SMPTE-240M
PL_COLOR_SYSTEM_BT_2020_NC, // ITU-R Rec. BT.2020 (non-constant luminance)
PL_COLOR_SYSTEM_BT_2020_C, // ITU-R Rec. BT.2020 (constant luminance)
PL_COLOR_SYSTEM_YCGCO, // YCgCo (derived from RGB)
// Other colorspaces:
PL_COLOR_SYSTEM_RGB, // Red, Green and Blue
PL_COLOR_SYSTEM_XYZ, // CIE 1931 XYZ
PL_COLOR_SYSTEM_COUNT
};
bool pl_color_system_is_ycbcr_like(enum pl_color_system sys);
// Guesses the best YCbCr-like colorspace based on a image given resolution.
// This only picks conservative values. (In particular, BT.2020 is never
// auto-guessed, even for 4K resolution content)
enum pl_color_system pl_color_system_guess_ycbcr(int width, int height);
// The numerical range of the representation (where applicable).
enum pl_color_levels {
PL_COLOR_LEVELS_UNKNOWN = 0,
PL_COLOR_LEVELS_TV, // TV range, e.g. 16-235
PL_COLOR_LEVELS_PC, // PC range, e.g. 0-255
PL_COLOR_LEVELS_COUNT,
};
// Struct describing the underlying color system and representation. This
// information is needed to convert an encoded color to a normalized RGB triple
// in the range 0-1.
struct pl_color_repr {
enum pl_color_system sys;
enum pl_color_levels levels;
int bit_depth; // applies to each component, 0 = unknown
};
extern const struct pl_color_repr pl_color_repr_unknown;
// Replaces unknown values in the first struct by those of the second struct.
void pl_color_repr_merge(struct pl_color_repr *orig,
const struct pl_color_repr *new);
// Returns whether two colorspace representations are exactly identical.
bool pl_color_repr_equal(struct pl_color_repr c1, struct pl_color_repr c2);
// Returns a representation-dependent multiplication factor for converting from
// one bit depth to another. For YCbCr-like color spaces, this is equal to
// directly shifting the 8-bit range; i.e. 0-255 becomes 0-1020, not 0-1023.
float pl_color_repr_texture_mul(struct pl_color_repr repr, int new_bits);
// The colorspace's primaries (gamut)
enum pl_color_primaries {
PL_COLOR_PRIM_UNKNOWN = 0,
// Standard gamut:
PL_COLOR_PRIM_BT_601_525, // ITU-R Rec. BT.601 (525-line = NTSC, SMPTE-C)
PL_COLOR_PRIM_BT_601_625, // ITU-R Rec. BT.601 (625-line = PAL, SECAM)
PL_COLOR_PRIM_BT_709, // ITU-R Rec. BT.709 (HD), also sRGB
PL_COLOR_PRIM_BT_470M, // ITU-R Rec. BT.470 M
// Wide gamut:
PL_COLOR_PRIM_BT_2020, // ITU-R Rec. BT.2020 (UltraHD)
PL_COLOR_PRIM_APPLE, // Apple RGB
PL_COLOR_PRIM_ADOBE, // Adobe RGB (1998)
PL_COLOR_PRIM_PRO_PHOTO, // ProPhoto RGB (ROMM)
PL_COLOR_PRIM_CIE_1931, // CIE 1931 RGB primaries
PL_COLOR_PRIM_DCI_P3, // DCI-P3 (Digital Cinema)
PL_COLOR_PRIM_V_GAMUT, // Panasonic V-Gamut (VARICAM)
PL_COLOR_PRIM_S_GAMUT, // Sony S-Gamut
PL_COLOR_PRIM_COUNT
};
bool pl_color_primaries_is_wide_gamut(enum pl_color_primaries prim);
// Guesses the best primaries based on a resolution. This always guesses
// conservatively, i.e. it will never return a wide gamut color space even if
// the resolution is 4K.
enum pl_color_primaries pl_color_primaries_guess(int width, int height);
// The colorspace's transfer function (gamma / EOTF)
enum pl_color_transfer {
PL_COLOR_TRC_UNKNOWN = 0,
// Standard dynamic range:
PL_COLOR_TRC_BT_1886, // ITU-R Rec. BT.1886 (CRT emulation + OOTF)
PL_COLOR_TRC_SRGB, // IEC 61966-2-4 sRGB (CRT emulation)
PL_COLOR_TRC_LINEAR, // Linear light content
PL_COLOR_TRC_GAMMA18, // Pure power gamma 1.8
PL_COLOR_TRC_GAMMA22, // Pure power gamma 2.2
PL_COLOR_TRC_GAMMA28, // Pure power gamma 2.8
PL_COLOR_TRC_PRO_PHOTO, // ProPhoto RGB (ROMM)
// High dynamic range:
PL_COLOR_TRC_PQ, // ITU-R BT.2100 PQ (perceptual quantizer), aka SMPTE ST2048
PL_COLOR_TRC_HLG, // ITU-R BT.2100 HLG (hybrid log-gamma), aka ARIB STD-B67
PL_COLOR_TRC_V_LOG, // Panasonic V-Log (VARICAM)
PL_COLOR_TRC_S_LOG1, // Sony S-Log1
PL_COLOR_TRC_S_LOG2, // Sony S-Log2
PL_COLOR_TRC_COUNT
};
// Returns the nominal peak of a given transfer function, relative to the
// reference white. This refers to the highest encodable signal level.
// Always equal to 1.0 for SDR curves.
float pl_color_transfer_nominal_peak(enum pl_color_transfer trc);
static inline bool pl_color_transfer_is_hdr(enum pl_color_transfer trc)
{
return pl_color_transfer_nominal_peak(trc) > 1.0;
}
// This defines the standard reference white level (in cd/m^2) that is assumed
// throughout standards such as those from by ITU-R, EBU, etc.
// This is particularly relevant for HDR conversions, as this value is used
// as a reference for conversions between absolute transfer curves (e.g. PQ)
// and relative transfer curves (e.g. SDR, HLG).
#define PL_COLOR_REF_WHITE 100.0
// The semantic interpretation of the decoded image, how is it mastered?
enum pl_color_light {
PL_COLOR_LIGHT_UNKNOWN = 0,
PL_COLOR_LIGHT_DISPLAY, // Display-referred, output as-is
PL_COLOR_LIGHT_SCENE_HLG, // Scene-referred, HLG OOTF
PL_COLOR_LIGHT_SCENE_709_1886, // Scene-referred, OOTF = 709/1886 interaction
PL_COLOR_LIGHT_SCENE_1_2, // Scene-referred, OOTF = gamma 1.2
PL_COLOR_LIGHT_COUNT
};
bool pl_color_light_is_scene_referred(enum pl_color_light light);
// Rendering intent for colorspace transformations. These constants match the
// ICC specification (Table 23)
enum pl_rendering_intent {
PL_INTENT_PERCEPTUAL = 0,
PL_INTENT_RELATIVE_COLORIMETRIC = 1,
PL_INTENT_SATURATION = 2,
PL_INTENT_ABSOLUTE_COLORIMETRIC = 3
};
// Struct describing a physical color space. This information is needed to
// turn a normalized RGB triple into its physical meaning, as well as to convert
// between color spaces.
struct pl_color_space {
enum pl_color_primaries primaries;
enum pl_color_transfer transfer;
enum pl_color_light light;
// The highest value that occurs in the signal, relative to the reference
// white. (0 = unknown)
float sig_peak;
};
// Replaces unknown values in the first struct by those of the second struct.
void pl_color_space_merge(struct pl_color_space *orig,
const struct pl_color_space *new);
// Returns whether two colorspaces are exactly identical.
bool pl_color_space_equal(struct pl_color_space c1, struct pl_color_space c2);
// Some common color spaces
extern const struct pl_color_space pl_color_space_unknown;
extern const struct pl_color_space pl_color_space_srgb;
extern const struct pl_color_space pl_color_space_bt709;
extern const struct pl_color_space pl_color_space_hdr10;
extern const struct pl_color_space pl_color_space_bt2020_hlg;
// This represents metadata about extra operations to perform during colorspace
// conversion, which correspond to artistic adjustments of the color.
struct pl_color_adjustment {
// Brightness boost. 0.0 = neutral, 1.0 = solid white, -1.0 = solid black
float brightness;
// Contrast boost. 1.0 = neutral, 0.0 = solid black
float contrast;
// Saturation gain. 1.0 = neutral, 0.0 = grayscale
float saturation;
// Hue shift, corresponding to a rotation around the [U, V] subvector.
// Only meaningful for YCbCr-like colorspaces. 0.0 = neutral
float hue;
// Gamma adjustment. 1.0 = neutral, 0.0 = solid black
float gamma;
};
// A struct pre-filled with all-neutral values.
extern const struct pl_color_adjustment pl_color_adjustment_neutral;
// Represents the chroma placement with respect to the luma samples. This is
// only relevant for YCbCr-like colorspaces with chroma subsampling.
enum pl_chroma_location {
PL_CHROMA_UNKNOWN = 0,
PL_CHROMA_LEFT, // MPEG2/4, H.264
PL_CHROMA_CENTER, // MPEG1, JPEG
PL_CHROMA_COUNT,
};
// Fills *x and *y with the offset in half-pixels corresponding to a given
// chroma location.
void pl_chroma_location_offset(enum pl_chroma_location loc, int *x, int *y);
// Represents a single CIE xy coordinate (i.e. CIE Yxy with Y = 1.0)
struct pl_cie_xy {
float x, y;
};
// Recovers (X / Y) from a CIE xy value.
static inline float pl_cie_X(struct pl_cie_xy xy) {
return xy.x / xy.y;
}
// Recovers (Z / Y) from a CIE xy value.
static inline float pl_cie_Z(struct pl_cie_xy xy) {
return (1 - xy.x - xy.y) / xy.y;
}
// Represents the raw physical primaries corresponding to a color space.
struct pl_raw_primaries {
struct pl_cie_xy red, green, blue, white;
};
// Returns the raw primaries for a given color space.
struct pl_raw_primaries pl_raw_primaries_get(enum pl_color_primaries prim);
// Represents a row-major matrix, i.e. the following matrix
// [ a11 a12 a13 ]
// [ a21 a22 a23 ]
// [ a31 a32 a33 ]
// is represented in C like this:
// { { a11, a12, a13 },
// { a21, a22, a23 },
// { a31, a32, a33 } };
struct pl_color_matrix {
float m[3][3];
};
// Inverts a color matrix. Only use where precision is not that important.
struct pl_color_matrix pl_color_matrix_invert(struct pl_color_matrix m);
// Represents an affine transformation, which is basically a 3x3 color matrix
// together with a column vector to add onto the output. The interpretation of
// `m` is identical to `pl_color_matrix`.
struct pl_color_transform {
struct pl_color_matrix mat;
float c[3];
};
// Inverts a color transform. Only use where precision is not that important.
struct pl_color_transform pl_color_transform_invert(struct pl_color_transform t);
// Returns an RGB->XYZ conversion matrix for a given set of primaries.
// Multiplying this into the RGB color transforms it to CIE XYZ, centered
// around the color space's white point.
struct pl_color_matrix pl_get_rgb2xyz_matrix(struct pl_raw_primaries prim);
// Similar to pl_get_rgb2xyz_matrix, but gives the inverse transformation.
struct pl_color_matrix pl_get_xyz2rgb_matrix(struct pl_raw_primaries prim);
// Returns a primary adaptation matrix, which converts from one set of
// primaries to another. This is an RGB->RGB transformation. For rendering
// intents other than PL_INTENT_ABSOLUTE_COLORIMETRIC, the white point is
// adapted using the Bradford matrix.
struct pl_color_matrix pl_get_color_mapping_matrix(struct pl_raw_primaries src,
struct pl_raw_primaries dst,
enum pl_rendering_intent intent);
// Returns a color decoding matrix for a given combination of source color
// representation, adjustment parameters, destination color levels, and output
// bit depth. If the output bit depth is specified as 0, the bit depth conversion
// step is skipped.
//
// This always performs a conversion to RGB; conversions from arbitrary color
// representations to other arbitrary other color representations, are
// currently not supported. Not all color systems support all of the color
// adjustment parameters. (In particular, hue/sat adjustments are currently
// only supported for YCbCr-like color systems)
//
// Note: For BT.2020 constant-luminance, this outputs chroma information in the
// range [-0.5, 0.5]. Since the CL system conversion is non-linear, further
// processing must be done by the caller. The channel order is CrYCb
struct pl_color_transform pl_get_decoding_matrix(struct pl_color_repr repr,
struct pl_color_adjustment params,
enum pl_color_levels out_levels,
int out_bits);
#endif // LIBPLACEBO_COLORSPACE_H_
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBPLACEBO_COMMON_H_
#define LIBPLACEBO_COMMON_H_
#include "context.h"
// Some common utility types
struct pl_rect2d {
int x0, y0;
int x1, y1;
};
struct pl_rect3d {
int x0, y0, z0;
int x1, y1, z1;
};
#define pl_rect_w(r) ((r).x1 - (r).x0)
#define pl_rect_h(r) ((r).y1 - (r).y0)
#define pl_rect_d(r) ((r).z1 - (r).z0)
#endif // LIBPLACEBO_COMMON_H_
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBPLACEBO_CONTEXT_H_
#define LIBPLACEBO_CONTEXT_H_
#include "config.h"
// The log level associated with a given log message.
enum pl_log_level {
PL_LOG_NONE = 0,
PL_LOG_FATAL, // results in total loss of function
PL_LOG_ERR, // serious error, may result in impaired function
PL_LOG_WARN, // warning. potentially harmful; probably user-relevant
PL_LOG_INFO, // informational message, also potentially harmless errors
PL_LOG_DEBUG, // verbose debug message, informational
PL_LOG_TRACE, // very verbose, benign trace of activity
PL_LOG_ALL = PL_LOG_TRACE,
};
// Meta-object to serve as a global entrypoint for the purposes of resource
// allocation, logging, etc.. Note on thread safety: the pl_context and
// everything allocated from it are *not* thread-safe except where otherwise
// noted. That is, multiple pl_context objects are safe to use from multiple
// threads, but a single pl_context and all of its derived resources and
// contexts must be used from a single thread at all times.
struct pl_context;
// Creates a new, blank pl_context. The argument must be given as PL_API_VER
// (this is used to detect ABI mismatch due to broken linking)
struct pl_context *pl_context_create(int api_ver);
// Except where otherwise noted, all objects allocated from this pl_context
// must be destroyed before the pl_context is destroyed.
//
// Note: As a rule of thumb, all _destroy functions take the pointer to the
// object to free as their parameter. This pointer is overwritten by NULL
// afterwards. Calling a _destroy function on &{NULL} is valid, but calling it
// on NULL itself is invalid.
void pl_context_destroy(struct pl_context **ctx);
// Associate a log callback with the context. All messages, informational or
// otherwise, will get redirected to this callback. The logged messages do not
// include a trailing newline.
void pl_context_set_log_cb(struct pl_context *ctx, void *priv,
void (*fun)(void *priv, enum pl_log_level level,
const char *msg));
// Set the maximum log level for which messages will be delivered to the log
// callback. Setting this to PL_LOG_ALL means all messages will be forwarded,
// but doing so indiscriminately can result in decreased performance as
// debugging code paths are enabled based on the configured log level.
void pl_context_set_log_level(struct pl_context *ctx, enum pl_log_level level);
#endif // LIBPLACEBO_CONTEXT_H_
/*
* This file is part of libplacebo.
*
* libplacebo 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.
*
* libplacebo 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 libplacebo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBPLACEBO_FILTER_KERNELS_H_
#define LIBPLACEBO_FILTER_KERNELS_H_
#include "context.h"
#define PL_FILTER_MAX_PARAMS 2
// Represents a single filter function, i.e. kernel or windowing function.
// To invoke a filter with a different configuration than the default, you can
// make a copy of this struct and modify the non-const fields before passing it
// to pl_filter_initialize.
struct pl_filter_function {
// These bools indicate whether or not `radius` and `params` may be
// modified by the user.
bool resizable;
bool tunable[PL_FILTER_MAX_PARAMS];
// The underlying filter function itself: Computes the weight as a function
// of the offset. All filter functions must be normalized such that x=0 is
// the center point, and in particular weight(0) = 1.0. The functions may
// be undefined for values of x outside [0, radius].
double (*weight)(const struct pl_filter_function *k, double x);
// This field may be used to adjust the function's radius. Defaults to the
// the radius needed to represent a single filter lobe (tap). If the
// function is not resizable, this field must not be modified - otherwise
// the result of filter evaluation is undefined.
float radius;
// These fields may be used to adjust the function. Defaults to the
// function's preferred defaults. if the relevant setting is not tunable,
// they are ignored entirely.
float params[PL_FILTER_MAX_PARAMS];
};
// Box filter: Entirely 1.0 within the radius, entirely 0.0 outside of it.
// This is also sometimes called a Dirichlet window
extern const struct pl_filter_function pl_filter_function_box;
// Triangle filter: Linear transitions from 1.0 at x=0 to 0.0 at x=radius.
// This is also sometimes called a Bartlett window.
extern const struct pl_filter_function pl_filter_function_triangle;
// Hann function: Cosine filter named after Julius von Hann. Also commonly
// mislabeled as a "Hanning" function, due to its similary to the Hamming
// function.
extern const struct pl_filter_function pl_filter_function_hann;
// Hamming function: Cosine filter named after Richard Hamming.
extern const struct pl_filter_function pl_filter_function_hamming;
// Welch filter: Polynomial function consisting of a single parabolic section.
extern const struct pl_filter_function pl_filter_function_welch;
// Kaiser filter: Approximation of the DPSS window using Bessel functions.
// Also sometimes called a Kaiser-Bessel window.
// Parameter [0]: Shape (alpha). Determines the trade-off between the main lobe
// and the side lobes.
extern const struct pl_filter_function pl_filter_function_kaiser;
// Blackman filter: Cosine filter named after Ralph Beebe Blackman.
// Parameter [0]: Scale (alpha). Influences the shape. The defaults result in
// zeros at the third and fourth sidelobes.
extern const struct pl_filter_function pl_filter_function_blackman;
// Gaussian function: Similar to the Gaussian distribution, this defines a
// bell curve function.
// Parameter [0]: Scale (t), increasing makes the result blurrier.
extern const struct pl_filter_function pl_filter_function_gaussian;
// Sinc function: Widely used for both kernels and windows, sinc(x) = sin(x)/x.
extern const struct pl_filter_function pl_filter_function_sinc;
// Jinc function: Similar to sinc, but extended to the 2D domain. Widely
// used as the kernel of polar (EWA) filters. Also sometimes called a Sombrero
// function.
extern const struct pl_filter_function pl_filter_function_jinc;
// Sphinx function: Similar to sinc and jinx, but extended to the 3D domain.
// The name is derived from "spherical" sinc. Can be used to filter 3D signals
// in theory.
extern const struct pl_filter_function pl_filter_function_sphinx;
// B/C-tunable Spline function: This is a family of commonly used spline
// functions with two tunable parameters. Does not need to be windowed.
// Parameter [0]: "B"
// Parameter [1]: "C"
// Due to its populariy, this function is available in several variants.
// B = 0.0, C = 0.0: "base" bcspline, AKA Hermite spline (blocky)
// B = 0.0, C = 0.5: Catmull-Rom filter (sharp)
// B = 1/3, C = 1/3: Mitchell-Netravali filter (soft, doesn't ring)
// B ≈ 0.37, C ≈ 0.31: Robidoux filter (used by ImageMagick)
// B ≈ 0.26, C ≈ 0.37: RobidouxSharp filter. (sharper variant of Robidoux)
extern const struct pl_filter_function pl_filter_function_bcspline;
extern const struct pl_filter_function pl_filter_function_catmull_rom;
extern const struct pl_filter_function pl_filter_function_mitchell;
extern const struct pl_filter_function pl_filter_function_robidoux;
extern const struct pl_filter_function pl_filter_function_robidouxsharp;
// Bicubic function: Very smooth and free of ringing, but very blurry. Does not
// need to be windowed.
extern const struct pl_filter_function pl_filter_function_bicubic;
// Piecewise approximations of the Lanczos filter function (sinc-windowed
// sinc). Referred to as "spline16", "spline36" and "spline64" mainly for
// historical reasons, based on their fixed radii of 2, 3 and 4 (respectively).
// These do not need to be windowed.
extern const struct pl_filter_function pl_filter_function_spline16;
extern const struct pl_filter_function pl_filter_function_spline36;
extern const struct pl_filter_function pl_filter_function_spline64;
struct pl_named_filter_function {
const char *name;
const struct pl_filter_function *function;
};
// As a convenience, this contains a list of all supported filter function,
// terminated by a single {0} entry.
extern const struct pl_named_filter_function pl_named_filter_functions[];
// Returns a filter function with a given name, or NULL on failure. Safe to
// call on name = NULL.
const struct pl_named_filter_function *pl_find_named_filter_function(const char *name);
// Represents a particular configuration/combination of filter functions to
// form a filter.
struct pl_filter_config {
const struct pl_filter_function *kernel; // The kernel function
const struct pl_filter_function *window; // The windowing function. Optional
// Represents a clamping coefficient for negative weights. A value of 0.0
// (the default) represents no clamping. A value of 1.0 represents full
// clamping, i.e. all negative weights will be clamped to 0. Values in
// between will be linearly scaled.
float clamp;
// Additional blur coefficient. This effectively stretches the kernel,
// without changing the effective radius of the filter radius. Setting this
// to a value of 0.0 is equivalent to disabling it. Values significantly
// below 1.0 may seriously degrade the visual output, and should be used
// with care.
float blur;
// Additional taper coefficient. This essentially flattens the function's
// center. The values within [-taper, taper] will return 1.0, with the
// actual function being squished into the remainder of [taper, radius].
// Defaults to 0.0.
float taper;
// If true, this filter is intended to be used as a polar/2D filter (EWA)
// instead of a separable/1D filter. Does not affect the actual sampling,
// but provides information about how the results are to be interpreted.
bool polar;
};
// Samples a given filter configuration at a given x coordinate, while
// respecting all parameters of the configuration.
double pl_filter_sample(const struct pl_filter_config *c, double x);
// A list of built-in filter configurations. Since they are just combinations
// of the above filter functions, they are not described in much further
// detail.
extern const struct pl_filter_config pl_filter_spline16; // 2 taps
extern const struct pl_filter_config pl_filter_spline36; // 3 taps
extern const struct pl_filter_config pl_filter_spline64; // 4 taps
extern const struct pl_filter_config pl_filter_box; // AKA nearest
extern const struct pl_filter_config pl_filter_triangle; // AKA bilinear
extern const struct pl_filter_config pl_filter_gaussian;
// Sinc family (all configured to 3 taps):
extern const struct pl_filter_config pl_filter_sinc; // unwindowed,
extern const struct pl_filter_config pl_filter_lanczos; // sinc-sinc
extern const struct pl_filter_config pl_filter_ginseng; // sinc-jinc
extern const struct pl_filter_config pl_filter_ewa_jinc; // unwindowed
extern const struct pl_filter_config pl_filter_ewa_lanczos; // jinc-jinc
extern const struct pl_filter_config pl_filter_ewa_ginseng; // jinc-sinc
extern const struct pl_filter_config pl_filter_ewa_hann; // jinc-hann
extern const struct pl_filter_config pl_filter_haasnsoft; // blurred ewa_hann
// Spline family
extern const struct pl_filter_config pl_filter_bicubic;
extern const struct pl_filter_config pl_filter_catmull_rom;
extern const struct pl_filter_config pl_filter_mitchell;
extern const struct pl_filter_config pl_filter_robidoux;
extern const struct pl_filter_config pl_filter_robidouxsharp;
extern const struct pl_filter_config pl_filter_ewa_robidoux;
extern const struct pl_filter_config pl_filter_ewa_robidouxsharp;
struct pl_named_filter_config {
const char *name;
const struct pl_filter_config *filter;
};
// As a convenience, this contains a list of built-in filter configurations,
// terminated by a single {0} entry.
extern const struct pl_named_filter_config pl_named_filters[];
// Returns a filter config with a given name, or NULL on failure. Safe to call
// on name = NULL.
const struct pl_named_filter_config *pl_find_named_filter(const char *name);
// Parameters for filter generation.
struct pl_filter_params {
// The particular filter configuration to be sampled. config.kernel must
// be set to a valid pl_filter_function.
struct pl_filter_config config;
// The precision of the resulting LUT. A value of 64 should be fine for
// most practical purposes, but higher or lower values may be justified
// depending on the use case. This value must be set to something > 0.
int lut_entries;
// When set to values above 1.0, the filter will be computed at a size
// larger than the radius would otherwise require, in order to prevent
// aliasing when downscaling. In practice, this should be set to the
// inverse of the scaling ratio, i.e. src_size / dst_size.
float filter_scale;
// --- polar filers only (config.polar)
// As a micro-optimization, all samples below this cutoff value will be
// ignored when updating the cutoff radius. Setting it to a value of 0.0
// disables this optimization.
float cutoff;
// --- separable filters only (!config.polar)
// Indicates the maximum row size that is supported by the calling code, or
// 0 for no limit.
int max_row_size;
// Indicates the row stride alignment. For some use cases (e.g. uploading
// the weights as a texture), there are certain alignment requirements for
// each row. The chosen row_size will always be a multiple of this value.
// Specifying 0 indicates no alignment requirements.
int row_stride_align;
};
// Represents an initialized instance of a particular filter, with a
// precomputed LUT. The interpretation of the LUT depends on the type of the
// filter (polar or separable).
struct pl_filter {
// Deep copy of the parameters, for convenience.
struct pl_filter_params params;
// Contains the true radius of the computed filter. This may be
// larger than `config.radius` depending on the `scale` passed to
// pl_filter_generate. This is only relevant for polar filters, where it
// affects the value range of *weights.
float radius;
// The computed look-up table (LUT). For polar filters, this is interpreted
// as a 1D array with dimensions [lut_entries] containing the raw filter
// samples on the scale [0, radius]. For separable (non-polar) filters,
// this is interpreted as a 2D array with dimensions
// [lut_entries][row_stride]. The inner rows contain the `row_size` samples
// to convolve with the corresponding input pixels. The outer coordinate is
// used to very the fractional offset (phase). So for example, if the
// sample position to reconstruct is directly aligned with the source
// texels, you would use the values from weights[0]. If the sample position
// to reconstruct is exactly half-way between two source texels (180° out
// of phase), you would use the values from weights[lut_entries/2].
const float *weights;
// --- polar filters only (params.config.polar)
// Contains the effective cut-off radius for this filter. Samples outside
// of this cutoff radius may be discarded. Computed based on the `cutoff`
// value specified at filter generation. Only relevant for polar filters
// since skipping samples outside of the radius can be a significant
// performance gain for EWA sampling.
float radius_cutoff;
// --- separable filters only (!params.config.polar)
// The number of source texels to convolve over for each row. This value
// will never exceed the given `max_row_size`. If the filter ends up
// cut off because of this, the bool `insufficient` will be set to true.
int row_size;
bool insufficient;
// The separation (in *weights) between each row of the filter. Always
// a multiple of params.row_stride_align.
int row_stride;
};
// Generate (compute) a filter instance based on a given filter configuration.
// The resulting pl_filter must be freed with `pl_filter_free` when no longer
// needed. Returns NULL if filter generation fails due to invalid parameters
// (i.e. missing a required parameter).
// The resulting pl_filter is implicitly destroyed when the pl_context is
// destroyed.
const struct pl_filter *pl_filter_generate(struct pl_context *ctx,
const struct pl_filter_params *params);
void pl_filter_free(const struct pl_filter **filter);
#endif // LIBPLACEBO_FILTER_KERNELS_H_
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment