Initial commit of Singe 2!

This commit is contained in:
Scott Duensing 2019-11-18 20:30:00 -06:00
commit d8d75821ef
84 changed files with 60112 additions and 0 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
*~
*.user
*.ISO
*.iso
*.m4v
*.index
*.avi
*.vob

18
ffms2/.gitattributes vendored Normal file
View file

@ -0,0 +1,18 @@
# Auto detect text files and perform LF normalization
* text=auto
# But don't mess up Unix scripts in the process
*.sh eol=lf
*.in eol=lf
*.am eol=lf
*.ac eol=lf
*.m4 eol=lf
# Scripts that don't have extensions...
/install-sh eol=lf
/compile eol=lf
/configure eol=lf
/config.guess eol=lf
/config.sub eol=lf
/depcomp eol=lf
/install-sh eol=lf
/missing eol=lf

4
ffms2/.gitmodules vendored Normal file
View file

@ -0,0 +1,4 @@
[submodule "test/googletest"]
path = test/googletest
url = https://github.com/google/googletest
branch = master

44
ffms2/.travis.yml Normal file
View file

@ -0,0 +1,44 @@
language: cpp
dist: trusty
sudo: required
matrix:
include:
- compiler: gcc
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-6
- g++-6
- yasm
before_install:
- sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-6
- compiler: clang
addons:
apt:
sources:
- llvm-toolchain-trusty-4.0
packages:
- clang-4.0
- yasm
before_install:
- sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-4.0 60 --slave /usr/bin/clang++ clang++ /usr/bin/clang++-4.0
install:
- git clone git://git.videolan.org/ffmpeg.git --depth=1 ffmpeg
- cd ffmpeg
- ./configure --disable-avfilter --disable-devices --disable-doc --disable-encoders --disable-filters --disable-hwaccels --disable-muxers --disable-network
- make -j2
- sudo make install
- cd ..
script:
- ./autogen.sh --enable-static --disable-shared || cat config.log
- make V=1 CXXFLAGS='-Werror -Wno-error=deprecated-declarations' -j2 -k
- make test-sync
- make test -j2 -k
notifications:
email:
- on_success: change
- on_failure: change

31
ffms2/COPYING Normal file
View file

@ -0,0 +1,31 @@
The FFMS2 source is licensed under the MIT license, but its binaries
are licensed under the GPL because GPL components of FFmpeg are
used. FFmpeg can be built as either LGPL, GPLv2, GPLv3, or even be
nonredistributable. Refer to FFmpeg's sources for licensing information.
Text of MIT license:
-----------------------------------------------------------
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------

365
ffms2/INSTALL Normal file
View file

@ -0,0 +1,365 @@
Installation Instructions
*************************
Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005,
2006, 2007, 2008, 2009 Free Software Foundation, Inc.
Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved. This file is offered as-is,
without warranty of any kind.
Basic Installation
==================
Briefly, the shell commands `./configure; make; make install' should
configure, build, and install this package. The following
more-detailed instructions are generic; see the `README' file for
instructions specific to this package. Some packages provide this
`INSTALL' file but do not implement all of the features documented
below. The lack of an optional feature in a given package is not
necessarily a bug. More recommendations for GNU packages can be found
in *note Makefile Conventions: (standards)Makefile Conventions.
The `configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a `Makefile' in each directory of the package.
It may also create one or more `.h' files containing system-dependent
definitions. Finally, it creates a shell script `config.status' that
you can run in the future to recreate the current configuration, and a
file `config.log' containing compiler output (useful mainly for
debugging `configure').
It can also use an optional file (typically called `config.cache'
and enabled with `--cache-file=config.cache' or simply `-C') that saves
the results of its tests to speed up reconfiguring. Caching is
disabled by default to prevent problems with accidental use of stale
cache files.
If you need to do unusual things to compile the package, please try
to figure out how `configure' could check whether to do them, and mail
diffs or instructions to the address given in the `README' so they can
be considered for the next release. If you are using the cache, and at
some point `config.cache' contains results you don't want to keep, you
may remove or edit it.
The file `configure.ac' (or `configure.in') is used to create
`configure' by a program called `autoconf'. You need `configure.ac' if
you want to change it or regenerate `configure' using a newer version
of `autoconf'.
The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code and type
`./configure' to configure the package for your system.
Running `configure' might take a while. While running, it prints
some messages telling which features it is checking for.
2. Type `make' to compile the package.
3. Optionally, type `make check' to run any self-tests that come with
the package, generally using the just-built uninstalled binaries.
4. Type `make install' to install the programs and any data files and
documentation. When installing into a prefix owned by root, it is
recommended that the package be configured and built as a regular
user, and only the `make install' phase executed with root
privileges.
5. Optionally, type `make installcheck' to repeat any self-tests, but
this time using the binaries in their final installed location.
This target does not install anything. Running this target as a
regular user, particularly if the prior `make install' required
root privileges, verifies that the installation completed
correctly.
6. You can remove the program binaries and object files from the
source code directory by typing `make clean'. To also remove the
files that `configure' created (so you can compile the package for
a different kind of computer), type `make distclean'. There is
also a `make maintainer-clean' target, but that is intended mainly
for the package's developers. If you use it, you may have to get
all sorts of other programs in order to regenerate files that came
with the distribution.
7. Often, you can also type `make uninstall' to remove the installed
files again. In practice, not all packages have tested that
uninstallation works correctly, even though it is required by the
GNU Coding Standards.
8. Some packages, particularly those that use Automake, provide `make
distcheck', which can by used by developers to test that all other
targets like `make install' and `make uninstall' work correctly.
This target is generally not run by end users.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the `configure' script does not know about. Run `./configure --help'
for details on some of the pertinent environment variables.
You can give `configure' initial values for configuration parameters
by setting variables in the command line or in the environment. Here
is an example:
./configure CC=c99 CFLAGS=-g LIBS=-lposix
*Note Defining Variables::, for more details.
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you can use GNU `make'. `cd' to the
directory where you want the object files and executables to go and run
the `configure' script. `configure' automatically checks for the
source code in the directory that `configure' is in and in `..'. This
is known as a "VPATH" build.
With a non-GNU `make', it is safer to compile the package for one
architecture at a time in the source code directory. After you have
installed the package for one architecture, use `make distclean' before
reconfiguring for another architecture.
On MacOS X 10.5 and later systems, you can create libraries and
executables that work on multiple system types--known as "fat" or
"universal" binaries--by specifying multiple `-arch' options to the
compiler but only a single `-arch' option to the preprocessor. Like
this:
./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \
CPP="gcc -E" CXXCPP="g++ -E"
This is not guaranteed to produce working output in all cases, you
may have to build one architecture at a time and combine the results
using the `lipo' tool if you have problems.
Installation Names
==================
By default, `make install' installs the package's commands under
`/usr/local/bin', include files under `/usr/local/include', etc. You
can specify an installation prefix other than `/usr/local' by giving
`configure' the option `--prefix=PREFIX', where PREFIX must be an
absolute file name.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
pass the option `--exec-prefix=PREFIX' to `configure', the package uses
PREFIX as the prefix for installing programs and libraries.
Documentation and other data files still use the regular prefix.
In addition, if you use an unusual directory layout you can give
options like `--bindir=DIR' to specify different values for particular
kinds of files. Run `configure --help' for a list of the directories
you can set and what kinds of files go in them. In general, the
default for these options is expressed in terms of `${prefix}', so that
specifying just `--prefix' will affect all of the other directory
specifications that were not explicitly provided.
The most portable way to affect installation locations is to pass the
correct locations to `configure'; however, many packages provide one or
both of the following shortcuts of passing variable assignments to the
`make install' command line to change installation locations without
having to reconfigure or recompile.
The first method involves providing an override variable for each
affected directory. For example, `make install
prefix=/alternate/directory' will choose an alternate location for all
directory configuration variables that were expressed in terms of
`${prefix}'. Any directories that were specified during `configure',
but not in terms of `${prefix}', must each be overridden at install
time for the entire installation to be relocated. The approach of
makefile variable overrides for each directory variable is required by
the GNU Coding Standards, and ideally causes no recompilation.
However, some platforms have known limitations with the semantics of
shared libraries that end up requiring recompilation when using this
method, particularly noticeable in packages that use GNU Libtool.
The second method involves providing the `DESTDIR' variable. For
example, `make install DESTDIR=/alternate/directory' will prepend
`/alternate/directory' before all installation names. The approach of
`DESTDIR' overrides is not required by the GNU Coding Standards, and
does not work on platforms that have drive letters. On the other hand,
it does better at avoiding recompilation issues, and works well even
when some directory options were not specified in terms of `${prefix}'
at `configure' time.
Optional Features
=================
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving `configure' the
option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
Some packages pay attention to `--enable-FEATURE' options to
`configure', where FEATURE indicates an optional part of the package.
They may also pay attention to `--with-PACKAGE' options, where PACKAGE
is something like `gnu-as' or `x' (for the X Window System). The
`README' should mention any `--enable-' and `--with-' options that the
package recognizes.
For packages that use the X Window System, `configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the `configure' options `--x-includes=DIR' and
`--x-libraries=DIR' to specify their locations.
Some packages offer the ability to configure how verbose the
execution of `make' will be. For these packages, running `./configure
--enable-silent-rules' sets the default to minimal output, which can be
overridden with `make V=1'; while running `./configure
--disable-silent-rules' sets the default to verbose, which can be
overridden with `make V=0'.
Particular systems
==================
On HP-UX, the default C compiler is not ANSI C compatible. If GNU
CC is not installed, it is recommended to use the following options in
order to use an ANSI C compiler:
./configure CC="cc -Ae -D_XOPEN_SOURCE=500"
and if that doesn't work, install pre-built binaries of GCC for HP-UX.
On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot
parse its `<wchar.h>' header file. The option `-nodtk' can be used as
a workaround. If GNU CC is not installed, it is therefore recommended
to try
./configure CC="cc"
and if that doesn't work, try
./configure CC="cc -nodtk"
On Solaris, don't put `/usr/ucb' early in your `PATH'. This
directory contains several dysfunctional programs; working variants of
these programs are available in `/usr/bin'. So, if you need `/usr/ucb'
in your `PATH', put it _after_ `/usr/bin'.
On Haiku, software installed for all users goes in `/boot/common',
not `/usr/local'. It is recommended to use the following options:
./configure --prefix=/boot/common
Specifying the System Type
==========================
There may be some features `configure' cannot figure out
automatically, but needs to determine by the type of machine the package
will run on. Usually, assuming the package is built to be run on the
_same_ architectures, `configure' can figure that out, but if it prints
a message saying it cannot guess the machine type, give it the
`--build=TYPE' option. TYPE can either be a short name for the system
type, such as `sun4', or a canonical name which has the form:
CPU-COMPANY-SYSTEM
where SYSTEM can have one of these forms:
OS
KERNEL-OS
See the file `config.sub' for the possible values of each field. If
`config.sub' isn't included in this package, then this package doesn't
need to know the machine type.
If you are _building_ compiler tools for cross-compiling, you should
use the option `--target=TYPE' to select the type of system they will
produce code for.
If you want to _use_ a cross compiler, that generates code for a
platform different from the build platform, you should specify the
"host" platform (i.e., that on which the generated programs will
eventually be run) with `--host=TYPE'.
Sharing Defaults
================
If you want to set default values for `configure' scripts to share,
you can create a site shell script called `config.site' that gives
default values for variables like `CC', `cache_file', and `prefix'.
`configure' looks for `PREFIX/share/config.site' if it exists, then
`PREFIX/etc/config.site' if it exists. Or, you can set the
`CONFIG_SITE' environment variable to the location of the site script.
A warning: not all `configure' scripts look for a site script.
Defining Variables
==================
Variables not defined in a site shell script can be set in the
environment passed to `configure'. However, some packages may run
configure again during the build, and the customized values of these
variables may be lost. In order to avoid this problem, you should set
them in the `configure' command line, using `VAR=value'. For example:
./configure CC=/usr/local2/bin/gcc
causes the specified `gcc' to be used as the C compiler (unless it is
overridden in the site shell script).
Unfortunately, this technique does not work for `CONFIG_SHELL' due to
an Autoconf bug. Until the bug is fixed you can use this workaround:
CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash
`configure' Invocation
======================
`configure' recognizes the following options to control how it
operates.
`--help'
`-h'
Print a summary of all of the options to `configure', and exit.
`--help=short'
`--help=recursive'
Print a summary of the options unique to this package's
`configure', and exit. The `short' variant lists options used
only in the top level, while the `recursive' variant lists options
also present in any nested packages.
`--version'
`-V'
Print the version of Autoconf used to generate the `configure'
script, and exit.
`--cache-file=FILE'
Enable the cache: use and save the results of the tests in FILE,
traditionally `config.cache'. FILE defaults to `/dev/null' to
disable caching.
`--config-cache'
`-C'
Alias for `--cache-file=config.cache'.
`--quiet'
`--silent'
`-q'
Do not print messages saying which checks are being made. To
suppress all normal output, redirect it to `/dev/null' (any error
messages will still be shown).
`--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
`configure' can determine that directory automatically.
`--prefix=DIR'
Use DIR as the installation prefix. *note Installation Names::
for more details, including other options available for fine-tuning
the installation locations.
`--no-create'
`-n'
Run the configure checks, but stop before creating any output
files.
`configure' also accepts some other, not widely useful, options. Run
`configure --help' for more details.

81
ffms2/Makefile.am Normal file
View file

@ -0,0 +1,81 @@
ACLOCAL_AMFLAGS = -I m4
AUTOMAKE_OPTIONS = foreign
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = ffms2.pc
dist_doc_DATA = doc/ffms2-api.md doc/ffms2-changelog.md
AM_CPPFLAGS = \
-I. \
-I$(top_srcdir)/include \
-I$(top_srcdir)/src/config \
-D_FILE_OFFSET_BITS=64 \
-DFFMS_EXPORTS \
-D__STDC_CONSTANT_MACROS \
@FFMPEG_CFLAGS@ \
@ZLIB_CPPFLAGS@ \
-include config.h
AM_CXXFLAGS = -std=c++11 -fvisibility=hidden
lib_LTLIBRARIES = src/core/libffms2.la
src_core_libffms2_la_LDFLAGS = @src_core_libffms2_la_LDFLAGS@
src_core_libffms2_la_LIBADD = @FFMPEG_LIBS@ @ZLIB_LDFLAGS@ -lz @LTUNDEF@
src_core_libffms2_la_SOURCES = \
src/core/audiosource.cpp \
src/core/audiosource.h \
src/core/ffms.cpp \
src/core/filehandle.cpp \
src/core/filehandle.h \
src/core/indexing.cpp \
src/core/indexing.h \
src/core/track.cpp \
src/core/track.h \
src/core/utils.cpp \
src/core/utils.h \
src/core/videosource.cpp \
src/core/videosource.h \
src/core/videoutils.cpp \
src/core/videoutils.h \
src/core/zipfile.cpp \
src/core/zipfile.h \
src/vapoursynth/VapourSynth.h \
src/vapoursynth/vapoursource.cpp \
src/vapoursynth/vapoursource.h \
src/vapoursynth/vapoursynth.cpp
include_HEADERS = $(top_srcdir)/include/ffms.h $(top_srcdir)/include/ffmscompat.h
bin_PROGRAMS = src/index/ffmsindex
src_index_ffmsindex_SOURCES = src/index/ffmsindex.cpp
src_index_ffmsindex_LDADD = src/core/libffms2.la
.PHONY: test test-build test-clean test-sync test-run
clean-local: test-clean
SAMPLES_DIR = $(abs_top_builddir)/test/samples
SAMPLES_URL = https://storage.googleapis.com/ffms2tests
test: test-setup test-build test-run
test-setup:
@$(MKDIR_P) $(abs_top_builddir)/test
@$(MKDIR_P) $(SAMPLES_DIR)
@if [ ! -e "$(abs_top_builddir)/test/Makefile" ]; then \
$(LN_S) $(abs_top_srcdir)/test/Makefile $(abs_top_builddir)/test/Makefile; \
fi
test-build: test-setup src/core/libffms2.la
@if [ ! -d "$(abs_top_srcdir)/test/googletest" ]; then \
echo "googletest submodule not initalized."; \
fi
@$(MAKE) -C test USER_DIR=$(abs_top_srcdir) SAMPLES_DIR=$(SAMPLES_DIR) CXX=$(CXX) AR=$(AR)
test-sync: test-setup
@$(MAKE) -C test sync USER_DIR=$(abs_top_srcdir) SAMPLES_DIR=$(SAMPLES_DIR) SAMPLES_URL=$(SAMPLES_URL) CXX=$(CXX) AR=$(AR)
test-run: test-build
@$(MAKE) -C test run USER_DIR=$(abs_top_srcdir) SAMPLES_DIR=$(SAMPLES_DIR) CXX=$(CXX) AR=$(AR) -k
test-clean:
@$(MAKE) -C test clean USER_DIR=$(abs_top_srcdir) CXX=$(CXX) AR=$(AR)

1157
ffms2/Makefile.in Normal file

File diff suppressed because it is too large Load diff

32
ffms2/README.md Normal file
View file

@ -0,0 +1,32 @@
[![Build Status](https://api.travis-ci.org/FFMS/ffms2.svg?branch=master)](https://travis-ci.org/FFMS/ffms2)
**FFmpegSource** (usually known as **FFMS** or **FFMS2**) is a cross-platform wrapper library around [FFmpeg](http://ffmpeg.org). It gives you an easy, convenient way to say "open and decompress this media file for me, I don't care how you do it" and get frame- and sample-accurate access (usually), without having to bother with the sometimes less than straightforward and less than perfectly documented FFmpeg API.
The library is written in C++, but the public API is pure C, so if you can link to a C library, you can use FFMS2. The source is available under the MIT license, but the license of the binaries depends on how FFmpeg was compiled. There are optional components that require a GPL FFmpeg, and if those are compiled in FFMS2 itself becomes covered by the GPL as well. The official Windows builds are GPLv3 for this reason.
For more information on using the library, see the [API documentation](doc/ffms2-api.md) and the [changelog](doc/ffms2-changelog.md).
### Avisynth and VapourSynth plugin
For the end user, the most visible use of FFMS is the implementation of both an [Avisynth](http://avisynth.nl) and a [VapourSynth](http://www.vapoursynth.com) source plugin that uses the FFMS library to open media files. This plugin is a part of the FFMS2 project and is available for download here; for documentation see the [Avisynth user guide](doc/ffms2-avisynth.md).
### Features
In addition to being able to open almost any common audio or video format, the Avisynth plugin has a number of more or less unique properties that other Avisynth source filters lack:
* It is the only source filter that has support for Unicode filenames that are not representable in the system codepage.
* It is the only source filter that has proper variable framerate (VFR) support.
* It is the only general-purpose (i.e. not restricted to one or a few formats) source filter that will work reliably when running Avisynth under Wine.
* It is the only general-purpose source filter that does not rely on external decoders.
* It is (probably) the only source filter that supports mid-stream video resolution switches.
### Versions and variants
If you're confused by all the different variants, here's a small explanation:
* Vanilla (no suffix): standard 32-bit version. If you don't know what you want, you want this.
* -x64: 64-bit version; mostly for use with 64-bit Avisynth.
* -avs-cplugin: Variant of the Avisynth plugin written in C. Primary purpose is to get access to the new colorspaces available in Avisynth 2.6.
* SDK: software developer's kit, for people who want to develop Windows applications that use FFMS2, using Microsoft Visual Studio 2008 or later.
Packages marked rNUMBER are testing builds made in-between releases. Download them if you need some bleeding-edge feature or just want to test out the upcoming version. Do note that they may be less stable than the official release versions.
### Why is it called FFmpegSource, that makes no sense at all!?!
FFMS originated as an Avisynth file reader plugin, and those are traditionally called FooSource, where Foo usually is the method used to open the file. For historical reasons the entire project is still called FFmpegSource, although these days the name is pretty misleading and makes people think it has something to do with FFmpeg's source code or somesuch. To avoid confusion, it's probably better to refer to the library as FFMS (2, since version 1 was only an Avisynth plugin...) and keep the FFmpegSource name for the Avisynth plugin.

1470
ffms2/aclocal.m4 vendored Normal file

File diff suppressed because it is too large Load diff

6
ffms2/autogen.sh Executable file
View file

@ -0,0 +1,6 @@
#! /bin/sh
mkdir -p src/config
echo Running autoreconf...
autoreconf -ivf
echo Running configure...
./configure "$@"

View file

@ -0,0 +1,7 @@
BUILD INSTRUCTIONS
The included projects require Visual Studio 2017.
Libraries needed: recent FFmpeg, zlib, Avisynth+ (MT branch) headers.
All include and library paths are set to be relative to the ffms2 directory by default.

View file

@ -0,0 +1,41 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.9
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ffms2", "ffms2.vcxproj", "{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ffmsindex", "ffmsindex.vcxproj", "{8665C229-CA77-4B41-ADC5-F3998F0C85A6}"
ProjectSection(ProjectDependencies) = postProject
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA} = {2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Debug|x64.ActiveCfg = Debug|x64
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Debug|x64.Build.0 = Debug|x64
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Debug|x86.ActiveCfg = Debug|Win32
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Debug|x86.Build.0 = Debug|Win32
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Release|x64.ActiveCfg = Release|x64
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Release|x64.Build.0 = Release|x64
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Release|x86.ActiveCfg = Release|Win32
{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}.Release|x86.Build.0 = Release|Win32
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Debug|x64.ActiveCfg = Debug|x64
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Debug|x64.Build.0 = Debug|x64
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Debug|x86.ActiveCfg = Debug|Win32
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Debug|x86.Build.0 = Debug|Win32
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Release|x64.ActiveCfg = Release|x64
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Release|x64.Build.0 = Release|x64
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Release|x86.ActiveCfg = Release|Win32
{8665C229-CA77-4B41-ADC5-F3998F0C85A6}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,199 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{2CF8C7D2-55E5-4861-A58A-A79B84D0D9EA}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>ffms2</RootNamespace>
<WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;../../AviSynthPlus/avs_core/include;../../ffmpeg32/include;../../zlib32;$(IncludePath)</IncludePath>
<LibraryPath>../../ffmpeg32/lib;../../zlib32;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;../../AviSynthPlus/avs_core/include;../../ffmpeg64/include;../../zlib64;$(IncludePath)</IncludePath>
<LibraryPath>../../ffmpeg64/lib;../../zlib64;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;../../AviSynthPlus/avs_core/include;../../ffmpeg32/include;../../zlib32;$(IncludePath)</IncludePath>
<LibraryPath>../../ffmpeg32/lib;../../zlib32;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;../../AviSynthPlus/avs_core/include;../../ffmpeg64/include;../../zlib64;$(IncludePath)</IncludePath>
<LibraryPath>../../ffmpeg64/lib;../../zlib64;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>FFMS_EXPORTS;_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;FFMS_WIN_DEBUG;WIN32;_DEBUG;_WINDOWS;_USRDLL;FFMS2_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<AdditionalDependencies>libavutil.a;libavcodec.a;libavformat.a;libswscale.a;libswresample.a;zlib.lib;ws2_32.lib;secur32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>FFMS_EXPORTS;_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;FFMS_WIN_DEBUG;_DEBUG;_WINDOWS;_USRDLL;FFMS2_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<AdditionalDependencies>libavutil.a;libavcodec.a;libavformat.a;libswscale.a;libswresample.a;zlib.lib;ws2_32.lib;secur32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>FFMS_EXPORTS;_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;WIN32;NDEBUG;_WINDOWS;_USRDLL;FFMS2_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>libavutil.a;libavcodec.a;libavformat.a;libswscale.a;libswresample.a;zlib.lib;ws2_32.lib;secur32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>FFMS_EXPORTS;_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;NDEBUG;_WINDOWS;_USRDLL;FFMS2_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<AdditionalDependencies>libavutil.a;libavcodec.a;libavformat.a;libswscale.a;libswresample.a;zlib.lib;ws2_32.lib;secur32.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\src\avisynth\avisynth.cpp" />
<ClCompile Include="..\src\avisynth\avssources.cpp" />
<ClCompile Include="..\src\core\audiosource.cpp" />
<ClCompile Include="..\src\core\ffms.cpp" />
<ClCompile Include="..\src\core\filehandle.cpp" />
<ClCompile Include="..\src\core\indexing.cpp" />
<ClCompile Include="..\src\core\track.cpp" />
<ClCompile Include="..\src\core\utils.cpp" />
<ClCompile Include="..\src\core\videosource.cpp" />
<ClCompile Include="..\src\core\videoutils.cpp" />
<ClCompile Include="..\src\core\zipfile.cpp" />
<ClCompile Include="..\src\vapoursynth\vapoursource.cpp" />
<ClCompile Include="..\src\vapoursynth\vapoursynth.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\ffms.h" />
<ClInclude Include="..\include\ffmscompat.h" />
<ClInclude Include="..\src\avisynth\avssources.h" />
<ClInclude Include="..\src\core\audiosource.h" />
<ClInclude Include="..\src\core\filehandle.h" />
<ClInclude Include="..\src\core\indexing.h" />
<ClInclude Include="..\src\core\track.h" />
<ClInclude Include="..\src\core\utils.h" />
<ClInclude Include="..\src\core\videosource.h" />
<ClInclude Include="..\src\core\videoutils.h" />
<ClInclude Include="..\src\core\zipfile.h" />
<ClInclude Include="..\src\vapoursynth\vapoursource.h" />
<ClInclude Include="..\src\vapoursynth\VapourSynth.h" />
<ClInclude Include="..\src\vapoursynth\VSHelper.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View file

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="API">
<UniqueIdentifier>{5e4ea0a8-9b1a-49ee-8b02-e498d4d5cc80}</UniqueIdentifier>
</Filter>
<Filter Include="Audio">
<UniqueIdentifier>{94e424bf-1254-46b5-9282-7c6b99280638}</UniqueIdentifier>
</Filter>
<Filter Include="Utils">
<UniqueIdentifier>{e25264ca-e3fd-4fd6-a1d1-839ae9b2ade2}</UniqueIdentifier>
</Filter>
<Filter Include="Indexing">
<UniqueIdentifier>{731b163b-dd24-4aba-8bef-86c3b364157e}</UniqueIdentifier>
</Filter>
<Filter Include="Video">
<UniqueIdentifier>{a2513788-a12f-43c1-99aa-b9f20cd6a099}</UniqueIdentifier>
</Filter>
<Filter Include="Vapoursynth">
<UniqueIdentifier>{8cc15f2a-6612-4e85-96b3-d3abfe15ddab}</UniqueIdentifier>
</Filter>
<Filter Include="Avisynth">
<UniqueIdentifier>{95efeead-393a-4518-b1f2-9b8b6bb8c3d6}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\core\ffms.cpp">
<Filter>API</Filter>
</ClCompile>
<ClCompile Include="..\src\core\filehandle.cpp">
<Filter>Utils</Filter>
</ClCompile>
<ClCompile Include="..\src\core\utils.cpp">
<Filter>Utils</Filter>
</ClCompile>
<ClCompile Include="..\src\core\zipfile.cpp">
<Filter>Utils</Filter>
</ClCompile>
<ClCompile Include="..\src\core\videosource.cpp">
<Filter>Video</Filter>
</ClCompile>
<ClCompile Include="..\src\core\videoutils.cpp">
<Filter>Video</Filter>
</ClCompile>
<ClCompile Include="..\src\vapoursynth\vapoursource.cpp">
<Filter>Vapoursynth</Filter>
</ClCompile>
<ClCompile Include="..\src\vapoursynth\vapoursynth.cpp">
<Filter>Vapoursynth</Filter>
</ClCompile>
<ClCompile Include="..\src\core\indexing.cpp">
<Filter>Indexing</Filter>
</ClCompile>
<ClCompile Include="..\src\core\track.cpp">
<Filter>Indexing</Filter>
</ClCompile>
<ClCompile Include="..\src\core\audiosource.cpp">
<Filter>Audio</Filter>
</ClCompile>
<ClCompile Include="..\src\avisynth\avisynth.cpp">
<Filter>Avisynth</Filter>
</ClCompile>
<ClCompile Include="..\src\avisynth\avssources.cpp">
<Filter>Avisynth</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\ffms.h">
<Filter>API</Filter>
</ClInclude>
<ClInclude Include="..\src\core\filehandle.h">
<Filter>Utils</Filter>
</ClInclude>
<ClInclude Include="..\src\core\utils.h">
<Filter>Utils</Filter>
</ClInclude>
<ClInclude Include="..\src\core\zipfile.h">
<Filter>Utils</Filter>
</ClInclude>
<ClInclude Include="..\include\ffmscompat.h">
<Filter>Utils</Filter>
</ClInclude>
<ClInclude Include="..\src\core\videosource.h">
<Filter>Video</Filter>
</ClInclude>
<ClInclude Include="..\src\core\videoutils.h">
<Filter>Video</Filter>
</ClInclude>
<ClInclude Include="..\src\vapoursynth\vapoursource.h">
<Filter>Vapoursynth</Filter>
</ClInclude>
<ClInclude Include="..\src\vapoursynth\VapourSynth.h">
<Filter>Vapoursynth</Filter>
</ClInclude>
<ClInclude Include="..\src\vapoursynth\VSHelper.h">
<Filter>Vapoursynth</Filter>
</ClInclude>
<ClInclude Include="..\src\core\indexing.h">
<Filter>Indexing</Filter>
</ClInclude>
<ClInclude Include="..\src\core\track.h">
<Filter>Indexing</Filter>
</ClInclude>
<ClInclude Include="..\src\core\audiosource.h">
<Filter>Audio</Filter>
</ClInclude>
<ClInclude Include="..\src\avisynth\avssources.h">
<Filter>Avisynth</Filter>
</ClInclude>
</ItemGroup>
</Project>

View file

@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{8665C229-CA77-4B41-ADC5-F3998F0C85A6}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>ffmsindex</RootNamespace>
<WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)ffmsindex\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)ffmsindex\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)ffmsindex\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)ffmsindex\$(Platform)\$(Configuration)\</IntDir>
<IncludePath>../include;$(IncludePath)</IncludePath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;__STDC_CONSTANT_MACROS;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\src\index\ffmsindex.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\ffms.h" />
<ClInclude Include="..\src\index\vsutf16.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="ffms2.vcxproj">
<Project>{2cf8c7d2-55e5-4861-a58a-a79b84d0d9ea}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View file

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\index\ffmsindex.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\ffms.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\src\index\vsutf16.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

347
ffms2/compile Executable file
View file

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

1480
ffms2/config.guess vendored Executable file

File diff suppressed because it is too large Load diff

1801
ffms2/config.sub vendored Executable file

File diff suppressed because it is too large Load diff

19020
ffms2/configure vendored Executable file

File diff suppressed because it is too large Load diff

151
ffms2/configure.ac Normal file
View file

@ -0,0 +1,151 @@
AC_PREREQ([2.58])
AC_INIT([ffms2],[esyscmd([sh version.sh])])
AC_CONFIG_SRCDIR([src/core/ffms.cpp])
AC_CONFIG_MACRO_DIR([m4])
AM_INIT_AUTOMAKE([1.11 subdir-objects])
AM_SILENT_RULES([yes])
AM_MAINTAINER_MODE([disable])
VERSION_INFO="4:0:0"
AC_MSG_CHECKING([if debug build is enabled])
AC_ARG_ENABLE([debug],
[AC_HELP_STRING([--enable-debug],
[Enable debug build. [default=no]])],
[enable_debug=yes],
[enable_debug=no]
)
AC_MSG_RESULT([$enable_debug])
if test "$enable_debug" = yes; then
OPT_FLAGS="-O0 -g"
else
OPT_FLAGS="-O3"
fi
if test -z "$CFLAGS"; then
CFLAGS="$OPT_FLAGS -Wall -Wextra"
fi
if test -z "$CXXFLAGS"; then
CXXFLAGS="$OPT_FLAGS -Wall -Wextra"
fi
AC_CONFIG_HEADERS([src/config/config.h])
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LN_S
AC_PROG_MKDIR_P
AC_CANONICAL_HOST
AS_CASE([$host],
[*mingw* | *cygwin*], [
AC_ENABLE_STATIC
AC_DISABLE_SHARED
], [
AC_ENABLE_SHARED
AC_DISABLE_STATIC])
AC_PROG_LIBTOOL
if echo "$host" | $GREP "cygwin" >/dev/null 2>&1 && test "$enable_shared" = "yes"; then
AC_MSG_ERROR([Shared build is broken on cygwin.
Please remove --enable-shared from your configure options or build with another --host.])
fi
dnl Workaround for a bug in libtool
dnl The windows libtool uses a file magic checking method that only accepts
dnl dynamic libraries. Change it for libtool's alternative checking method.
if test "$lt_cv_file_magic_cmd" = "func_win32_libid" ; then
deplibs_check_method='file_magic file format pei*-(i386|x86-64)|(.*architecture: i386)?'
file_magic_cmd='$OBJDUMP -f'
fi
FFMS_VERSION="$(sh $(dirname -- "$0")/version.sh)"
AC_SUBST([FFMS_VERSION])
CHECK_ZLIB
dnl Save CFLAGS and LIBS for later, as anything else we add will be from pkg-config
dnl and thus should be separate in our .pc file.
_CFLAGS="$CFLAGS"
_CPPFLAGS="$CPPFLAGS"
_LIBS="$LIBS"
PKG_PROG_PKG_CONFIG([0.22])
pkgconfigdir="\$(libdir)/pkgconfig"
AC_SUBST(pkgconfigdir)
PKG_CHECK_MODULES(FFMPEG, [libavformat >= 53.20.0 libavcodec >= 53.24.0 libswscale >= 0.7.0 libavutil >= 51.21.0 libswresample >= 1.0.0])
dnl As of 0eec06ed8747923faa6a98e474f224d922dc487d ffmpeg only adds -lrt to lavc's
dnl LIBS, but lavu needs it, so move it to the end if it's present
FFMPEG_LIBS=$(echo $FFMPEG_LIBS | sed 's/\(.*\)-lrt \(.*\)/\1\2 -lrt/')
AC_SUBST([FFMPEG_CFLAGS])
AC_SUBST([FFMPEG_LIBS])
CPPFLAGS="$CPPFLAGS -D__STDC_CONSTANT_MACROS"
CFLAGS="$_CFLAGS $FFMPEG_CFLAGS"
AC_DEFUN([TEST_FFMPEG],
[AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
]],[[
avcodec_register_all();
swscale_version();
]])], [eval $1=yes], [eval $1=no])
])
AC_MSG_CHECKING([whether FFmpeg works])
LIBS="$_LIBS $FFMPEG_LIBS"
TEST_FFMPEG([FFMPEG_WORKS])
AC_MSG_RESULT([$FFMPEG_WORKS])
if test "$FFMPEG_WORKS" = no; then
AC_MSG_FAILURE([cannot link with FFmpeg])
fi
src_core_libffms2_la_LDFLAGS=""
AC_MSG_CHECKING([whether -Wl,-Bsymbolic is needed])
if test "$enable_shared" = yes; then
_LDFLAGS="$LDFLAGS"
LDFLAGS="$LDFLAGS -shared $lt_prog_compiler_pic"
TEST_FFMPEG([no_bsymbolic])
if test "$no_bsymbolic" = "no"; then
LDFLAGS="$LDFLAGS -Wl,-Bsymbolic"
TEST_FFMPEG([bsymbolic])
if test "$bsymbolic" = "yes"; then
src_core_libffms2_la_LDFLAGS="$src_core_libffms2_la_LDFLAGS -Wl-Bsymbolic"
else
AC_MSG_RESULT($bsymbolic)
AC_MSG_FAILURE([cannot build ffms2 as a shared library])
fi
else
bsymbolic=no
fi
LDFLAGS="$_LDFLAGS"
src_core_libffms2_la_LDFLAGS="$src_core_libffms2_la_LDFLAGS -version-info $VERSION_INFO"
else
bsymbolic=no
fi
AC_SUBST([src_core_libffms2_la_LDFLAGS])
CFLAGS="$_CFLAGS"
CPPFLAGS="$_CPPFLAGS"
LIBS="$_LIBS"
AC_MSG_RESULT($bsymbolic)
if echo "$host" | $GREP "mingw" >/dev/null 2>&1; then
LTUNDEF="-no-undefined"
fi
AC_SUBST([LTUNDEF])
AC_CONFIG_FILES([
Makefile
ffms2.pc
])
AC_OUTPUT

791
ffms2/depcomp Executable file
View file

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

1421
ffms2/doc/ffms2-api.md Normal file

File diff suppressed because it is too large Load diff

390
ffms2/doc/ffms2-avisynth.md Normal file
View file

@ -0,0 +1,390 @@
# FFmpegSource2 Avisynth User Manual
Opens files using FFmpeg and nothing else.
May be frame accurate on good days.
The source is MIT licensed and can be obtained from https://github.com/FFMS/ffms2/.
The precompiled binary is GPL3 licensed.
If you are religious you may consider this the second coming.
## Donate
Donate if you like this software.
Collecting weird clips from the internet and making them play takes more time than you'd think.
[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=fredrik%2emellbin%40gmail%2ecom&lc=US&item_name=IVTC%2eORG&no_note=0&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHostedGuest)
## Limitations
- Because of LAVF's demuxer, most raw streams (such as elementary h264 and other mpeg video streams) will fail to work properly.
- FFAudioSource() will have to remake any index implicitly created by FFVideoSource() and therefore code like
```
AudioDub(FFVideoSource(X), FFAudioSource(X))
```
will require two indexing passes. Apart from the time consumed this is harmless.
To work around it open the audio first:
```
A = FFAudioSource(X)
V = FFVideoSource(X)
AudioDub(V, A)
```
or use FFIndex(), like so:
```
FFIndex(X)
AudioDub(FFVideoSource(X), FFAudioSource(X))
```
- Interlaced H.264 mostly works these days, but seeking may occasionally result in corruption.
- Transport Streams will not decode reliably without seekmode -1.
- Open-GOP H.264 will sometimes produces corruption when seeking.
## Compatibility
### Video
- AVI, MKV, MP4, FLV: Frame accurate
- WMV: Frame accurate(?) but avformat seems to pick keyframes relatively far away
- OGM: Frame accurate(?)
- VOB, MPG: Seeking seems to be off by one or two frames now and then
- M2TS, TS: Seeking seems to be off a few frames here and there
- Image files: Most formats can be opened if seekmode=-1 is set, no animation support
### Audio
Seeking should be sample-accurate with most codecs in AVI, MKV, MP4 and FLV.
Decoding linearly will almost always give correct results, and forward-seeks from trimming should result in at most a few hundred samples of corruption.
## Indexing and You
Before FFMS2 can open a file, it must be indexed first so that keyframe/sample positions are known and seeking is easily accomplished.
This is done automatically when using `FFVideoSource()` or `FFAudioSource()`,
but if you want to you can invoke the indexing yourself by calling `FFIndex()`, or by running `ffmsindex.exe`.
By default the index is written to a file so it can be reused the next time you open the same file, but this behavior can be turned off if desired.
If you wonder why FFMS2 takes so long opening files, the indexing is the answer.
If you want a progress report on the indexing, you can use the supplied `ffmsindex.exe` commandline program.
## Function reference
### FFIndex
```
FFIndex(string source, string cachefile = source + ".ffindex", int indexmask = -1,
int errorhandling = 3, bool overwrite = false)
```
Indexes a number of tracks in a given source file and writes the index file to disk, where it can be picked up and used by `FFVideoSource` or `FFAudioSource`.
Normally you do not need to call this function manually; it's invoked automatically if necessary by `FFVideoSource`/`FFAudioSource`.
It does, however, give you more control over how indexing is done.
Note that this function returns an integer, not a clip (since it doesn't open video, nor audio).
The return value isn't particularly interesting, but for the record it's 0 if the index file already exists (and is valid) and overwrite was not enabled, 1 if the index file was created and no previous index existed, and 2 if the index file was created by overwriting an existing, valid index file.
#### Arguments
##### string source
The source file to index.
##### string cachefile = source + ".ffindex"
The filename of the index file (where the indexing data is saved).
Defaults to `sourcefilename.ffindex`.
##### int indexmask = -1
A binary mask representing what audio tracks should be indexed (all video tracks are always indexed; you have no choice in the matter).
The mask is constructed by bitshifting 1 left by the track number; if multiple tracks are desired, bitwise OR each value so created together to get the full mask.
In other words, the mask is a bit field where each bit is a track number (the least significant bit is track number 0).
Since Avisynth doesn't have any bitwise operators at all, constructing a mask for more than one track inside an Avisynth script is a rather annoying task; for a single track the mask is, naturally, 2 to the power of the track number minus 1 (i.e. if you want to index track 3, the mask is `2^(3-1) = 4`).
Since the mask works like it does, and FFMS2 is designed to run on a machine that uses two's complement integers, -1 (the default) means index all tracks and 0 means index none.
Note that FFMS2's idea about what track has what number may be completely different from what any other application might think, and that track numbering starts from 1.
##### int errorhandling = 3
Controls what happens if an audio decoding error is encountered during indexing.
Possible values are:
- **0**: Raise an error and abort indexing. No index file is written.
- **1**: Clear the affected track (effectively making it silent) and continue.
- **2**: Stop indexing the track but keep all the index entries so far, effectively ending the track where the error occured.
- **3**: Pretend it's raining and continue anyway. This is the default; if you encounter odd noises in the audio, try mode 0 instead and see if it's FFMS2's fault.
##### bool overwrite = false
If set to true, `FFIndex()` will reindex the source file and overwrite the index file even if the index file already exists and is valid.
Mostly useful for trackmask changes and testing.
### FFVideoSource
```
FFVideoSource(string source, int track = -1, bool cache = true,
string cachefile = source + ".ffindex", int fpsnum = -1, int fpsden = 1,
int threads = -1, string timecodes = "", int seekmode = 1, int rffmode = 0,
int width = -1, int height = -1, string resizer = "BICUBIC",
string colorspace = "", string varprefix = "")
```
Opens video. Will invoke indexing of all video tracks (but no audio tracks) if no valid index file is found.
#### Arguments
##### string source
The source file to open.
##### int track = -1
The video track number to open, as seen by the relevant demuxer.
Track numbers start from zero, and are guaranteed to be continous (i.e. there must be a track 1 if there is a track 0 and a track 2). -1 means open the first video track.
Note that FFMS2's idea about what track has what number may (or may not) be completely different from what some other application might think.
Trying to open an audio track with `FFVideoSource` will naturally fail.
##### bool cache = true
If set to true (the default), `FFVideoSource` will first check if the `cachefile` contains a valid index, and if it does, that index will be used.
If no index is found, all video tracks will be indexed, and the indexing data will be written to `cachefile` afterwards.
If set to false, `FFVideoSource` will not look for an existing index file; instead all video tracks will be indexed when the script is opened, and the indexing data will be discarded after the script is closed; you will have to index again next time you open the script.
##### string cachefile = source + ".ffindex"
The filename of the index file (where the indexing data is saved).
Defaults to `sourcefilename.ffindex`.
Note that if you didn't change this parameter from its default value and `FFVideoSource` encounters an index file that doesn't seem to match the file it's trying to open, it will automatically reindex and then overwrite the old index file.
On the other hand, if you *do* change it, `FFVideoSource` will assume you have your reasons and throw an error instead if the index doesn't match the file.
##### int fpsnum = -1, int fpsden = 1
Controls the framerate of the output; used for VFR to CFR conversions.
If `fpsnum` is less than or equal to zero (the default), the output will contain the same frames that the input did, and the frame rate reported to Avisynth will be set based on the input clip's average frame duration.
If `fpsnum` is greater than zero, `FFVideoSource` will force a constant frame rate, expressed as a rational number where `fpsnum` is the numerator and `fpsden` is the denominator.
This may naturally cause `FFVideoSource` to drop or duplicate frames to achieve the desired frame rate, and the output is not guaranteed to have the same number of frames that the input did.
##### int threads = -1
The number of decoding threads to request from libavcodec.
Setting it to less than or equal to zero means it defaults to the number of logical CPU's reported by Windows.
Note that this setting might be completely ignored by libavcodec under a number of conditions; most commonly because a lot of decoders actually do not support multithreading.
##### string timecodes = ""
Filename to write Matroska v2 timecodes for the opened video track to.
If the file exists, it will be truncated and overwritten.
Set to the empty string to disable timecodes writing (this is the default).
##### int seekmode = 1
Controls how seeking is done.
Mostly useful for getting uncooperative files to work.
Valid modes are:
- **-1**: Linear access without rewind; i.e. will throw an error if each successive requested frame number isn't bigger than the last one.
Only intended for opening images but might work on well with some obscure video format.
- **0**: Linear access (i.e. if you request frame `n` without having requested all frames from 0 to `n-1` in order first, all frames from 0 to `n` will have to be decoded before `n` can be delivered).
The definition of slow, but should make some formats "usable".
- **1**: Safe normal. Bases seeking decisions on the keyframe positions reported by libavformat.
- **2**: Unsafe normal. Same as mode 1, but no error will be thrown if the exact seek destination has to be guessed.
- **3**: Aggressive. Seeks in the forward direction even if no closer keyframe is known to exist. Only useful for testing and containers where libavformat doesn't report keyframes properly.
##### int rffmode = 0
Controls how RFF flags in the video stream are treated; in other words it's equivalent to the "field operation" mode switch in DVD2AVI/DGIndex.
Valid modes are:
- **0**: Ignore all flags (the default mode).
- **1**: Honor all pulldown flags.
- **2**: Equivalent to DVD2AVI's "force film" mode.
Note that using modes 1 or 2 will make `FFVideoSource` throw an error if the video stream has no RFF flags at all.
When using either of those modes, it will also make the output be assumed as CFR, disallow vertical scaling and disallow setting the output colorspace.
`FFPICT_TYPE` will also not be set as the output is a combination of several frames.
Other subtle behavior changes may also exist.
Also note that "force film" is mostly useless and only here for completeness' sake, since if your source really is safe to force film on, using mode 0 will have the exact same effect while being considerably more efficient.
##### int width = -1, int height = -1
Sets the resolution of the output video, in pixels.
Setting either dimension to less than or equal to zero means the resolution of the first decoded video frame is used for that dimension.
These parameters are mostly useful because FFMS2 supports video streams that change resolution mid-stream; since Avisynth does not, these parameters are used to set single resolution for the output.
##### string resizer = "BICUBIC"
The resizing algorithm to use if rescaling the image is necessary.
If the video uses subsampled chroma but your chosen output colorspace does not, the chosen resizer will be used to upscale the chroma planes, even if you did not request an image rescaling.
The available choices are `FAST_BILINEAR`, `BILINEAR`, `BICUBIC` (default), `X`, `POINT`, `AREA`, `BICUBLIN`, `GAUSS`, `SINC`, `LANCZOS` and `SPLINE`.
Note that `SPLINE` is completely different from Avisynth's builtin Spline resizers.
##### string colorspace = ""
Convert the output from whatever it was to the given colorspace, which can be one of `YV12`, `YV16`, `YV24`, `Y8`, `YUY2`, `YV411`, `YUV9`, `RGB24` or `RGB32`.
They can also be referred to with the more systematic names of `YUVsssPx`, `YUVAsssPx`, `Yx`, `RGBPx` or `RGBAPx` where `x` is the desired bitdepth and `sss` represents the subsampling. Formats with an `A` also have an alpha channel.
Examples: `YUV420P8`, `RGBAP16`, `Y16`
Setting this to an empty string (the default) means keeping the same colorspace as the input or in case it's not supported it'll be converted to the closest existing match.
##### string varprefix = ""
A string that is added as a prefix to all exported Avisynth variables.
This makes it possible to differentiate between variables from different clips.
For convenience the last used FFMS function in a script sets the global variable `FFVAR_PREFIX` to its own variable prefix so that `FFInfo()` can default to it.
### FFAudioSource
```
FFAudioSource(string source, int track = -1, bool cache = true,
string cachefile = source + ".ffindex", int adjustdelay = -1,
string varprefix = "")
```
Opens audio.
Invokes indexing of all tracks if no valid index file is found, or if the requested track isn't present in the index.
#### Arguments
Are exactly the same as to `FFVideoSource`, with one exception:
##### int adjustdelay = -1
Controls how audio delay is handled, i.e. what happens if the first audio sample in the file doesn't have a timestamp of zero.
The following arguments are valid:
- **-3**: No adjustment is made; the first decodable audio sample becomes the first sample in the output.
- **-2**: Samples are created (with silence) or discarded so that sample 0 in the decoded audio starts at time zero.
- **-1**: Samples are created (with silence) or discarded so that sample 0 in the decoded audio starts at the same time as frame 0 of the first video track. This is the default, and probably what most people want.
- **Any integer >= 0**: Same as -1, but adjust relative to the video track with the given track number instead.
If the provided track number isn't a video track, an error is raised.
-2 obviously does the same thing as -1 if the first video frame of the first video track starts at time zero.
In some containers this will always be the case, in others (most notably 188-byte MPEG TS) it will almost never happen.
### FFmpegSource2/FFMS2
```
FFmpegSource2/FFMS2(string source, int vtrack = -1, int atrack = -2, bool cache = true,
string cachefile = source + ".ffindex", int fpsnum = -1, int fpsden = 1,
int threads = -1, string timecodes = "", int seekmode = 1,
bool overwrite = false, int width = -1, int height = -1,
string resizer = "BICUBIC", string colorspace = "", int rffmode = 0,
int adjustdelay = -1, string varprefix = "")
```
A convenience function that combines the functionality of `FFVideoSource` and `FFAudioSource`.
The arguments do the same thing as in `FFVideoSource` and `FFAudioSource`; see those functions for details.
`vtrack` and `atrack` are the video and audio track to open, respectively; setting `atrack` <= -2 means audio is disabled.
**Note:** the shorter FFMS2 alias was added in 2.22
### FFImageSource
```
FFImageSource(string source, int width = -1, int height = -1,
string resizer = "BICUBIC", string colorspace = "")
```
A convenience alias for `FFVideoSource`, with the options set optimally for using it as an image reader.
Disables caching and seeking for maximum compatiblity.
### FFInfo
```
FFInfo(clip c, bool framenum = true, bool frametype = true, bool cfrtime = true,
bool vfrtime = true, string varprefix = "", bool colorspace = true,
bool colorrange = true, bool cropping = true, bool sar =true, bool version = true,
bool showprefix = false)
```
A helper function similar to Avisynth's internal `Info()` function; shows general information about the current frame.
Note that not all values are exported in all source modes, so some information may not always be shown.
The arguments can be used to disable the drawing of certain information if so desired.
Use the varprefix argument to determine which clip you want information about.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFFormatTime
FFFormatTime(int ms)
A helper function used to format a time given in milliseconds into a h:mm:ss.ttt string.
Used internally by `FFInfo`.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFColorSpace
FFColorSpace(int i)
A helper function used to convert a colorspace number into a human readable string.
Used internally by `FFInfo`.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFColorRange
FFColorRange(int i)
A helper function used to convert a color range number into a human readable string.
Used internally by `FFInfo`.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFCropping
FFCropping(int l, int t, int r, int b)
A helper function used to convert cropping information into a human readable string.
Used internally by `FFInfo`.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFSampAR
FFSampAR(int num,int den)
A helper function used to convert the sample aspect ratio into a human readable string.
Used internally by `FFInfo`.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFPictType
FFPictType(int ch)
A helper function used to convert a picture type character into a human readable string.
Used internally by `FFInfo`.
**Note:** this function is provided by `FFMS2.avsi` and is not available unless that script has been imported or autoloaded.
### FFSetLogLevel
```
FFSetLogLevel(int Level = -8)
```
Sets the FFmpeg logging level, i.e. how much diagnostic spam it prints to STDERR.
Since most applications that open Avisynth scripts do not provide a way to display things printed to STDERR, and since it's rather hard to make any sense of the printed messages unless you're quite familiar with FFmpeg internals, the usefulness of this function is rather limited for end users. It's mostly intended for debugging.
Defaults to quiet (no messages printed); a list of meaningful values can be found in `ffms.h`.
### FFGetLogLevel
```
FFGetLogLevel()
```
Returns the current log level, as an integer.
### FFGetVersion
```
FFGetVersion()
```
Returns the FFMS2 version, as a string.
## Exported Avisynth variables
All variable names are prefixed by the `varprefix` argument to the respective `FFVideoSource` or `FFAudioSource` call that generated them.
##### FFSAR_NUM, FFSAR_DEN, FFSAR
The playback aspect ratio specified by the container.
`FFSAR_NUM` and `FFSAR_DEN` make up the rational number of the ratio; `FFSAR` is only provided for convenience and may not be set in case it cannot be calculated (i.e. if `FFSAR_DEN` is zero).
##### FFCROP_LEFT, FFCROP_RIGHT, FFCROP_TOP, FFCROP_BOTTOM
The on-playback cropping specified by the container.
##### FFCOLOR_SPACE
The colorimetry the input claims to be using. Only meaningful for YUV inputs.
The source for this variable is a metadata flag that can arbitrarily be set or manipulated at will by incompetent users or buggy programs without changing the actual video content, so blindly trusting its correctness is not recommended.
The value is exported as a cryptic numerical constant that matches the values in the MPEG-2 specification.
You can find the gory details in the FFMS2 API documentation, but the important ones are:
- **0**: RGB (usually indicates the stream isn't actually YUV, but RGB flagged as YUV)
- **1**: ITU-R Rec.709
- **2**: Unknown or unspecified
- **5 and 6**: ITU-R Rec.601
##### FFCOLOR_RANGE
The color range the input video claims to be using.
Much like FFCOLOR_SPACE, the source for this variable is a metadata flag that can freely be set to arbitrary values, so trusting it blindly might not be a good idea.
Note that using the width/height/colorspace parameters to FFVideoSource may under some circumstances change the output color range.
- **0**: Unknown/unspecified
- **1**: Limited range (usually 16-235)
- **2**: Full range (0-255)
##### FFPICT_TYPE
The picture type of the most recently requested frame as the ASCII number of the character listed below.
Use `Chr()` to convert it to an actual letter in Avisynth. Use after_frame=true in Avisynth's conditional scripting for proper results.
Only set when rffmode=0.
The FFmpeg source definition of the characters:
```
I: Intra
P: Predicted
B: Bi-dir predicted
S: S(GMC)-VOP MPEG4
i: Switching Intra
p: Switching Predicted
b: FF_BI_TYPE (no good explanation available)
?: Unknown
```
##### FFVFR_TIME
The actual time of the source frame in milliseconds.
Only set when no type of CFR conversion is being done (`rffmode` and `fpsnum` left at their defaults).
##### FFCHANNEL_LAYOUT
The audio channel layout of the audio stream.
This is exported as a very cryptic integer that is constructed in the same way as the `dwChannelMask` property of the Windows `WAVEFORMATEXTENSIBLE` struct.
If you don't know what a `WAVEFORMATEXTENSIBLE` is or what the `dwChannelMask` does, don't worry about it.
##### FFVAR_PREFIX
The variable prefix of the last called FFMS source function.
Note that this is a global variable.

View file

@ -0,0 +1,339 @@
# FFmpegSource2 Changelog
- 2.2000
- Added LastEndTime track property to make it possible to take the last frame's duration into account (Myrsloik)
- Removed several deprecated functions and enums from the API (Myrsloik)
- No longer assumes sub 1 fps framerates are invalid (Myrsloik)
- Added support for floating point format output in VapourSynth and Avisynth+ (Myrsloik)
- Fixed issue with dropped/repeated frames in vc1 with multiple b-frames after seeking (Myrsloik)
- Fixed issue with dropped/repeated frames in h264 when the reorder buffer size is too small (Myrsloik)
- Improved seeking in mpeg and mpegts streams (Myrsloik)
- Added rgb(a)p and several additional formats as output to Avisynth+ (Myrsloik)
- Added VP9 support (Daemon404)
- Fixed incorrectly reporting the output as limited range when it's in fact unknown and likely to be full range (Myrsloik)
- Added mastering display metadata output (Myrsloik)
- VapourSynth source now defaults to not outputting alpha (Myrsloik)
- Removed the now unused demuxer, dumpmask, audiofile and utf8 arguments from the source filters (Myrsloik)
- Removed ability to dump audio tracks (Myrsloik)
- Fixed incorrect colorimetry metadata reported when converting the output to another colorspace (Myrsloik)
- Sources now simply reference the index instead of copying large parts of it (Myrsloik)
- Use new FFmpeg decoding API (Myrsloik)
- Fixed several bugs in output format selection (Myrsloik)
- FFMSIndex will now properly error out with invalid arguments (Myrsloik)
- Add rotation metadata export (Myrsloik)
- Add stereoscopic metadata export (Myrsloik)
- Created new Visual Studio 2017 projects (Myrsloik)
- Removed old mingw version support (Myrsloik)
- Removed support for old FFmpeg versions (Myrsloik)
- Removed libav support (Myrsloik)
- Discontinuous Timestamp Support (Daemon404)
- Add FFMS_Deinit (Daemon404)
- Fix mid-stream parameter changes (Daemon404)
- Fix decoding H.264 PAFF files with one field per packet (Daemon404)
- Fix delay calculations for H.264 PAFF files (Daemon404)
- Fix frame rate calculation for fields with one field per packet (Daemon404)
- 2.23
- Updated FFmpeg APIs used (Daemon404)
- Added new API that can read/write indexes to a memory buffer (Daemon404)
- Added support for high bitdepth output in Avisynth+ (Myrsloik)
- vapoursource: Add nfMakeLinear flag to better performance in most cases (Myrsloik)
- Remove bad colorspace matrix guessing for YUV (Myrsloik)
- Tell libavformat to discard packets we don't want (Daemon404)
- Restore original FFCopyrightInfringement behavior (Myrsloik)
- Make FFMS_Init threadsafe (Daemon404)
- Support latest libav* APIs (Daemon404)
- 2.22
- Fix possible off by 1 frame until first seek issue introduced in 2.21 (Myrsloik)
- avisynth: Make FFMS2 a shorter alias for FFmpegSource2 to save some typing (Myrsloik)
- avisynth: Moved all source functions in ffms2.avsi into the actual plugin (Myrsloik)
- avisynth: Use 2.6 RC API and add output support for all new colorspaces (Myrsloik)
- vapoursource: Fix swapped RGB channels bug introduced in 2.21 (Myrsloik)
- swscale: Drop pointless and slow bitexact flag from resizer settings (kodabb)
- Add support for files with gaps between the audio packets (Plorkyeran)
- 2.21
- Add missing constants for log levels (Myrsloik)
- Fix bad decoder flush that discards the palette of raw video (Myrsloik)
- Remove the SWScale function from Avisynth since SWScale is useless (Myrsloik)
- Fix common framerate correction (Myrsloik)
- vapoursource: The framerate and frame durations are now normalized (Myrsloik)
- vapoursource: Add support for outputting the alpha channel too (Myrsloik)
- vapoursource: Fix resizer selection so bicubic isn't always used (Myrsloik)
- vapoursource: Set chroma location and full colorspace information (Myrsloik)
- Add support for indexing files with more than 32 tracks and the possibility to skip indexing of video tracks (Myrsloik)
- The Avisynth plugin now sets all per frame variables in all modes to avoid ugly and slow FFInfo() errors (Myrsloik)
- vapoursource: Fix crash on single frame files (Myrsloik)
- Remove the Matroska and Haali demuxers (qyot27, Plorkyeran)
- Fix adjustments for positive audio delay (tophf)
- Don't try to index video tracks in unsupported formats (Daemon404)
- Don't use scientific notation in timecode files (Daemon404)
- Fix utf8 support in FFVideoSource (nixxquality)
- Improve handling of files where only some packets have timestamps (Plorkyeran)
- Fix memory leaks in the VapourSynth error handling (Plorkyeran)
- 2.20
- Add support for Opus in MKV when ffmpeg/libav are built with libopus (qyot27)
- vapoursource: Provide _AbsoluteTime metadata (Daemon404)
- Fix a pile of small things found by Coverity (Daemon404)
- Add support for HEVC in MKV (qyot27)
- Fix infinite loop on garbage data at the beginning of AAC files (Plorkyeran)
- Deal with the never-ending bitrot from FFmpeg/Libav API changes (Daemon404, Plorkyeran)
- Make indexes not arch-specific and trivially smaller (Plorkyeran)
- Fix bug where the first b-frame was replaced with the frame before it with open-gop h.264 (Plorkyeran)
- Fix seeking issues with open-gop h.264 (Plorkyeran)
- Fix corruption when seeking in interlaced h.264 (Plorkyeran)
- Add support for multiple frames per audio packet as FFmpeg seems to have started doing that (Plorkyeran)
- Fix seeking in Y4M files (Plorkyeran)
- Fix dumping audio while indexing files
- Add support for Matroska files with extremely large CodecPrivate sections
- Speed up indexing Matroska files a bit
- 2.18
- Fix regression (r483) with rffmode that caused it to error out even if using the default output colorspace. (TheRyuu)
- High(er) quality YUV->RGB conversion. (TheRyuu)
- Fix indexing on files with cover art. (TheRyuu)
- Add support for libav/ffmpeg built with msvc, this is the default on windows when building with msvc. (TheRyuu)
- Remove postproc support. (TheRyuu)
- Deprecate the CPUFeatures argument to FFMS_Init since postproc was the only thing still using it. (Plorkyeran)
- Added VapourSynth support. (Myrsloik)
- ffmsindex can now output keyframe numbers to a file while indexing. (Plorkyeran)
- configure now defaults to building a shared library, except when building MinGW/Cygwin, since you usually want static for those. (Plorkyeran)
- The source color space and color range used when converting with swscale can now be overridden. (Plorkyeran)
- Fix issues with unicode filenames when building with mingw. (Plorkyeran)
- Fix progress reporting when indexing files with non-zero initial timestamp with haali's splitter. (Plorkyeran)
- Add support for formats with packet durations but no packet timestamps. (Plorkyeran)
- Fix corruption when seeking in VC-1 in MKV. (Plorkyeran)
- Fix bug that resulted in files opened with Haali's splitter sometimes always decoding from the beginning on every seek. (Plorkyeran)
- Add support for VP8. (Plorkyeran)
- Fix crash when indexing video formats with no parser. (Plorkyeran)
- Fix compilation errors with recent versions of libav/ffmpeg. (Plorkyeran)
- Fix NVOP handling with frame-based threading (aka zero-size frames with mp4 bug). (Plorkyeran)
- Add support for vc1image. (Plorkyeran)
- Use the container SAR when the codec SAR is unset when opening via lavf. (Plorkyeran)
- Actually set the ColorRange and ColorSpace of frames when nothing has been overridden. (Plorkyeran)
- Add support for files without timestamps to lavf audio. (Plorkyeran)
- Fix handling of audio delay with invalid inital timestamps. (Plorkyeran)
- Sort of partially fix interlaced H.264. (Plorkyeran)
- Fix errors when the client asks for audio past the end of the file. (Plorkyeran)
- Fix rounding error with MKV timestamps that resulted in things getting a FPS like 60001/1001. (TheRyuu)
- Bump required version to libav 0.8/FFmpeg 0.9. (Plorkyeran)
- Switch to avcodec_decode_audio4. (Plorkyeran)
- Add support for planar audio from lavc. (Plorkyeran)
- Add SetOutputFormatA for audio resampling/mixing using libavresample. (Plorkyeran)
- Zero-length index files are now rejected rather than bad things happening.
- 2.17
- Reworked color matrix and color range handling a bit, which fixed a bug that could cause FFMS2 to always output TV range even if the input was full range. (TheFluff)
- The autotools build system can now create debug builds properly. (Daemon404)
- Deprecated parts of the API will now cause compiler warnings when you use them. (TheFluff)
- Added a `FFMS_GetVersion` function to the API (lets library users get the version number at runtime) and exposed it in Avisynth as `FFGetVersion`. (TheRyuu, TheFluff)
- Added a variable prefix option to the Avisynth functions. Its primary purpose is to get subsequent calls to source functions from overwriting variables from earlier calls. (TheFluff)
- Make it possible to open single-frame videos without explicitly setting seekmode to -1 for you weird people who want to open images with ffms (Plorkyeran)
- Fixed bug where indices would sometimes be incorrectly considered valid (TheRyuu)
- Add support for recent versions of Libav/FFmpeg built as shared libraries (Plorkyeran, TheRyuu, Kovensky)
- When possible, non-API symbols are no longer exported (Daemon404, TheFluff)
- Deprecate postprocessing support. Libav and FFmpeg are planning on removing it at some point in the near future and it's really not very useful.
- Fix the pkg-config version on OS X (Plorkyeran).
- Fixed a bug that could cause the `FFmpegSource2()` Avisynth function to not use UTF8 filenames even when told to do so. (pandv2)
- Fixed a few minor memory leaks. (Plorkyeran)
- Adjusting audio delay relative to the first video track should now work properly again (was broken in 2.16). (Plorkyeran)
- General bitrot fixes to deal with changes in Libav/FFmpeg (everyone)
- Corrected handling of codec private data when using a non-libavformat parser. Fixes decoding of FFV1 and UTVideo in MKV, among other things. (TheFluff)
- Bump minimum required version of FFmpeg to 0.6.
- 2.16
- Reimplemented output colorspace selection, this should fix all issues with the Avisynth plugin when opening yuv420p10 or yuv444 material plus several other less common cases. (Myrsloik)
- Added `FFMS_SetOutputFormatV2` to the API. This function allows you to specify PixelFormats >= 64 for use as output. (Myrsloik)
- Fixed a serious bug that could cause crashes and completely useless index files with h264 in Matroska. (Myrsloik)
- Automatically detect number of decoding threads. The Avisynth video source funtion already did this, now moved so the API can use it as well. (TheRyuu)
- Re-add the ability to target x64 with MSVC, since it's a bit more sane now. (TheRyuu)
- Fixed a bug that could cause crashes when reading audio if FFMS2 was compiled with GCC. (Myrsloik)
- ffmsindex will no longer crash if it cannot open the file given to it for indexing. (TheFluff)
- FFMS2 will no longer crash if the video decoder feeds it an empty frame (can sometimes happen when using lots of decoder threads); you'll get a nice error message instead. (TheFluff)
- The C-plugin can now act as both an Avisynth 2.6 plugin (including support for new colorspaces) as well as an Avisynth 2.5 one, in the same binary. (kemuri_-9)
- Fixed an issue that could cause opening Vorbis audio to fail because FFMS2 couldn't find an initial valid PTS. (TheFluff)
- FFMS2 will no longer crash if forced or tricked into using an index file generated by a FFMS2 version compiled for a different architecture. (TheRyuu)
- Fixed a crash when the last frame was requested using the Avisynth plugin's forced CFR mode. (Plorkyeran)
- Fixed various issues with decoding audio from the Ogg container without Haali's splitter. (Myrsloik, TheFluff)
- Fixed the "invalid postprocessing settings", it is caused by a parsing bug in libpostproc and a workaround has been added (Myrsloik)
- Tinkered a bit with the non-MSVS build system. (Daemon404, Kovensky)
- 2.15
- FFVideoSource and FFAudioSource will now automatically reindex and overwrite the index file if it doesn't match the file being opened and the `cachefile` argument is left as the default. (Plorkyeran)
- FFMS2 can now be used to decode Lagarith, but note that libavcodec's decoder is very experimental at the moment. (Plorkyeran)
- SWScale can now use SSE2 optimizations for certain operations if your CPU supports it. (kemuri_-9)
- Fixed a bug that could cause SWScale initialization to fail. (kemuri_-9)
- Fixed a bug that could cause index files to never be considered valid, forcing a reindexing every time a script was loaded. (TheRyuu)
- Trying to use postprocessing on a fullrange YUV clip will no longer cause errors. (TheFluff)
- Fixed a few random decoding bugs related to unaligned memory or buffers that were not initialized properly. (TheFluff)
- It is now possible to force FFMS2 to use a specific demuxer instead of letting it pick one automatically. (TheFluff)
- When converting YUV to RGB, FFMS2 will now try to actually use the correct color coefficients rather than assuming everything is bt470bg. (Plorkyeran)
- Moved support for container-level audio delay from the Avisynth plugin to the core and exposed it in the API (Plorkyeran)
- Audio decoding has been substantially reworked. Linearly decoding audio now almost always works correctly and seeking is now actually sample-accurate for many formats. (Plorkyeran)
- It is now possible to build 64bit versions of the plugin for use with Avisynth (and whatever else) from MSVC by means of black magic (this probably only works when the planets are aligned, also 64bit builds might require msvcr90.dll). (TheRyuu)
- The Avisynth plugin now supports UTF8 filenames; ffmsindex.exe also supports Unicode filenames. FFMS_USE_UTF8_PATHS is now a runtime option instead of a compile-time one. (TheFluff)
- The FFInfo() function (supplied by ffms2.avsi) will now round timestamps to nearest millisecond instead of truncating them. It's also been cleaned up in general and no longer relies on global variables. (Gavino)
- Containers opened with libavformat will now report a framerate based on the average frame duration instead of the duration of the first frame, just like Matroska files and files opened with Haali's splitter does. Should fix CFR framerates being reported incorrectly in dumb containers like FLV. (TheFluff)
- PC/TV luma range (16-235 versus 0-255) detection should now be a bit more reliable. (TheFluff)
- Fixed a crash when opening files with Unicode filename support enabled. (Plorkyeran)
- 2.14
- Reworked filename handling a bit. Index files should no longer get a garbled name when using the Avisynth plugin and an input filename in the local codepage (issue 9), and FFMS_USE_UTF8_PATHS does no longer require patching ffmpeg. (TheFluff, nielsm)
- Fixed a bunch of compiler warnings and added versioning for the shared library when building under Unix. (Kovensky)
- Fixed an invalid memory access bug that could cause random crashes or other errors when opening files. (TheFluff)
- The timebase for video tracks is now corrected if it's invalid. (kemuri_-9)
- Fixed a number of multithreaded decoding issues. (kemuri_-9)
- Use aligned memory for audio decoding buffers; fixes some crashes during audio decoding. (greg)
- Fixed a bug that caused ffmsindex -c to fail. (chdheu)
- Added support for MKV files using header stripping compression. (TheFluff)
- It is now possible to compile FFMS2 using a ffmpeg without libpostproc compiled in (this will obviously cause postprocessing-related functions to fail). Hence it is now possible to build a GPL-free FFMS2, since the rest of ffmpeg can be compiled as LGPL. (TheFluff)
- Audio streams that change channel layout, sample rate or bitdepth mid-stream will no longer cause crashes; an error will be raised during indexing instead. (TheFluff)
- Fix a potential crash when ffmpeg thought it couldn't decode a certain format, but was wrong. Fixes issues with some FLV's. (Plorkyeran)
- Fix heap corruption that could cause crashes and odd issues when opening H.264 in MPEG-TS with Haali's splitter. (Plorkyeran)
- Fix a memleak when decoding H.264 in MPEG-TS using Haali's splitter. (kemuri-_9)
- Updated FFmpeg to rev 25329.
- 2.13
- Fixed a bug where the Avisynth plugin would drop the last frame when converting to CFR (lanwcp)
- The Avisynth plugin will now attempt to detect and use NTSC fractional framerates for CFR files if applicable, instead of reporting something based on the average framerate (astrange, TheFluff)
- The errorhandling parameter to FFIndex() will now actually do what the documentation claims it does (TheFluff)
- Fixed a progress reporting crash when opening images (TheFluff)
- Replaced the CMake build system with an autotools one that hopefully works better (Kovensky)
- Fixed various compilation issues with MinGW (TheFluff)
- Fixed h264 in mkv which was remuxed from bd sources, there are no longer decoding artifacts after seeking
- Use pts instead of dts for seeking with lavf, fixes various timecode problems on mp4 files with certain obscure delay headers
- Now compresses the index files with zlib to save space
- Removed the boost dependency
- Fixed the framerate calculation for AVC video in the RFF modes
- Improved/fixed the NVOP detection in MPEG4 and how timestamps are calculated (lanwcp, Myrsloik)
- Fixed an issue where the first 15 audio frames would never be redecoded if needed again
- Fixed/added support for uncompressed video and audio formats in matroska, fixes Blank.Clip.720p.x264-darkhold.mkv (Emess)
- The indexer and test is now statically linked so no extra runtimes are needed
- FFmpeg is now compiled with runtime cpu detection, allows opterons and old cpus to work properly
- Updated FFmpeg to rev 21782
- 2.12
- Added support for (L)PCM in TS/PS
- Fixed some possible memory corruption on initialization in the indexers
- Improved the API slightly by making resolution and colorspace frame properties only like they actually are
- Fixed adjustdelay=-1 when no video track is present, previously it would crash
- Updated FFmpeg to rev 19824, FFmpeg-mt unchanged at 24/08/2009 - with faad2, opencore-amr nb/wb, and pthreads
- 2.11
- Now 100% less beta
- FFMSIndex can now write timecode files
- Optimized index reading and writing, file opening should be faster especially for big files
- Fixed a crash bug on zlib compressed streams in matroska
- Added an argument to FFAudioSource that makes it automatically adjust the delay relative to the first video track (default), the specified track (any track type possible) or relative to the zero timestamp, no adjustment is done for files with no video track in the default mode
- Now exports the colorimetry info in a format easily usable with ColorMatrix, see FFCOLOR_SPACE and FFCOLOR_RANGE in the manual, the reported information may be unreliable
- Added an FFImageSource() function to ffms2.avsi which invokes FFVideoSource with the optimal settings for use on images
- Now exports the actual frame presentation time in FFVFR_TIME, added the general information function FFInfo() and FFFormatTime() functions to ffms2.avsi in addition to fixing the missing backslash
- The seek/read method has been changed in the matroska video source to only need the information in the index and nothing more, this matches the audio source and should make seeking faster in some cases
- No longer drops the last audio frame
- It is now possible to force indexing of broken tracks when using FFIndex and from the API, this can in many cases help when the last frame of an avi file is corrupted which would otherwise prevent indexing of all working data
- Fixed a bug that would prevent the SWScale and FFPP filters from working because of randomly added flags
- Added support for RFF flags, the three possible modes should be equivalent to the ones found in DGDecode
- Added a workaround for mpeg4 files with NVOPs
- Fixed a bug where the first frame would be corrupted if the colorspace/dimensions were set for the output
- Now VC1 in TS decoding works in many cases
- Added the missing install target to CMake and changed the default output library name (Kovensky)
- Now reverts to using LAVF if Haali's splitter isn't installed (note that LAVF is VERY bad at seeking in these formats)
- Now requires the boost headers (but not libraries) to compile because boost::format is so convenient
- More API changes to return proper error codes and more source cleanups
- Updated FFmpeg to rev 19776, FFmpeg-mt to 24/08/2009 - with faad2, opencore-amr nb/wb, and w32threads (pthreads for FFmpeg-mt)
- 2.00 beta 10
- Possibly fixed h264 in transport stream decoding, now a suitable bitstream filter is added (could theoretically break other h264 in ts files so make sure to report if any such files stop working)
- Now returns the frame type as a character to make presentation easier and to remove the random numbers from the API
- Fixed the identification of certain codecs (like VC1) in some transport streams
- Fixed a bug introduced in SeekMode=1 by the changes in beta 6, prevents an access violation from happening in very rare conditions
- Some (but not all) stream properties are now retrieved from the container and passed to libavcodec, this makes a few more formats work like vc1 in mkv/ts
- It is now possible to specify the desired output colorspace and resolution in FFVideoSource, this is mostly useful for file where the resolution changes to avoid excessive up/downscaling
- Added support for files where the video frames have changing size and colorspace
- The library part can now be compiled to accept UTF8 encoded strings, this allows full unicode support on windows when FFmpeg is compiled with a small patch applied (TheFluff)
- Added proper detection of when the opened file and index is mismatched and throws an error when it happens instead of undefined behavior, should not add a noticable delay to file opening
- Added a proper cmake based build system and vs2008 project files to make developement and use easier (TheFluff, JEEB, Kovensky)
- Added API documentation by TheFluff and revised many argument descriptions to reflect how they currently work
- The output audio filename can now be specified in avisynth (was ignored previously) with variables such as track number and delay possible to use
- Indexing with Haali's splitters should now show progress in most cases
- Fixed a few more memory leaks in indexing
- Now checks for failed seeking when LAVF is used and retries with more aggressive seeking options before failing
- Updated FFmpeg to rev 19479 (now compiled with the opencore amr decoder)
- 2.00 beta 9
- Dumping audio now actually implies indexing too in FFIndex, previously nothing would be done if the index mask wasn't set as well
- FFAudioSource will now first load the index and returns the first indexed audio track with track=-1, if no audio tracks are indexed or the chosen track isn't indexed the equivalent of FFIndex(indexmask = -1, overwrite = cache) is executed first
- Codec lookup for non-lavf opened files now to a large part use the same lookup tables as lavf, this should improve the number of properly recognized codecs
- Now uses the average framerate for files opened with Haali's splitters, before it was always reported as 30 fps
- Implemented audio decoding using Haali's splitters, FFAudioSource now works on ts, ps and ogm
- Can now be compiled with ICL 10.1 (probably other versions too)
- How indexing works has been split internally so the track numbers and types are reported, this makes it possible to create an interactive GUI or ask which audio tracks are to be indexed
- Now has stricter index checking to detect when different FFmpeg versions were used to create an index of the same version
- Fixed memory leaks when audio sources were destroyed and when errors happened during indexing
- Fixed access violations occurring when a track of the wrong type was specified or didn't exist in FFVideoSource and FFAudioSource
- Fixed access violations occurring when unindexed or empty audio tracks in matroska/lavf read files were opened
- Less type conversion/signedness warnings
- When audio track dumping is performed a custom callback can now be supplied to name the tracks
- The audio track delay is now exposed in the API in the same way as video tracks
- A big type and argument name cleanup in the API, many things have been renamed to be clearer and ffms.h should be completely C friendly now
- Removed FFNoLog and replaced it with FFSetLogLevel and FFGetLogLevel, the default logging is now also set to quiet, the magical numbers to supply it can be found in avutil/log.h
- Updated FFmpeg to rev 18972 (now with faad2 again by popular demand, updated to GCC 4.4.0 for compiling all libraries)
- 2.00 beta 8
- Improved the audio decoding quality a lot by adding a simple cache, no more seeking is done when playing a file linearly and pops and other artifacts should be much more uncommon
- Fixed a bug that would most of the time drop frame 0 and sometimes frame 1
- Updated Haali's matroska parser code to the latest version
- Updated FFmpeg to rev 18774
- 2.00 beta 7
- Using ffms2 as a library no longer requires an installed pixfmt.h from libavutil, it is however still required to compile ffms2 and the avisynth plugin part
- Fix a crash bug at the end of files with b-frames in beta 6 caused by uninitialized null packets
- Includes TheFluff's wrapper function for 1.21 style syntax
- Added a simple regression test application to the source
- Removed a few pointless functions from the API
- Fixed the accessing of codecprivate data with Haali's splitters
- Timecode output should be fixed to include decimals AND not be in scientific format
- Fixed a memory leak when using Haali's splitters
- Updated FFmpeg to rev 18717
- 2.00 beta 6
- Haali's splitters have been improved for video and now have audio dumping during indexing implemented
- SeekMode=1 has improved logic which will make it go back and decode more frames if necessary to figure out where it is, in theory SeekMode=0 should now be mostly obsolete
- Haali's splitters are now used to open mpeg ps and ogm in addition to mpeg ts, only ogm is frame accurate at this time
- Negative timecodes and other bugs caused by an integer overflow fixed
- Updated FFmpeg to rev 18442 (once again compilation fixes for the changes)
- 2.00 beta 5
- FFMSIndex should now print the progress properly when another application reads its output
- Added missing variables and explanations to the manual
- Can now directly be compiled as a library for use in *nix
- Fixed the missing decimals in saved timecode files
- 2.00 beta 4
- Added the function FFNoLog which suppresses all messages from ffmpeg
- Experimental new TS parsing using Haali's splitter (with bugs)
- Everything is now compiled with VS2008 and GCC 4.3.2
- Updated FFmpeg to rev 16383 (no libfaad2 this time)
- 2.00 beta 3
- Compiled with libfaad2 again (has anyone seen a single aac file lavc can open right now?)
- More API changes (and even more are likely to come)
- Several access violations and memory leaks on opening and indexing files fixed
- Added a VFR to CFR mode
- Readded FFAudioSource support for other containers (glitches still present now and then but no separate raw cache is required and possibly less buggy)
- Renamed the dll to FFMS2.dll, FFMS2 is now the official short name of the project
- Updated FFmpeg to rev 15522
- 2.00 beta 2
- More API changes (and more are likely to come)
- Includes a simple CLI indexing application
- FFIndex now takes a few more arguments
- Readded FFAudioSource (only matroska supported for now)
- Updated FFmpeg to rev 15396
- 2.00 beta 1
- Can now be used as a stand alone library for making indices and retrieving frames
- Rewrote most things
- Updated FFmpeg to rev 15301

View file

@ -0,0 +1,195 @@
# FFmpegSource2 VapourSynth User Manual
Opens files using FFmpeg and (almost) nothing else.
May be frame accurate on good days.
The source is MIT licensed and can be obtained from https://github.com/FFMS/ffms2/.
The precompiled binary is GPL3 licensed.
If you are religious you may consider this the second coming.
## Donate
Donate if you like this software.
Collecting weird clips from the internet and making them play takes more time than you'd think.
[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=fredrik%2emellbin%40gmail%2ecom&lc=US&item_name=IVTC%2eORG&no_note=0&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHostedGuest)
## Limitations
- No audio support in VapourSynth
- Because of LAVF's demuxer, most raw streams (such as elementary h264 and other mpeg video streams) will fail to work properly.
- Interlaced H.264 mostly works these days, but seeking may occasionally result in corruption.
- Transport Streams will not decode reliably without seekmode -1.
- Open-GOP H.264 will sometimes produces corruption when seeking.
## Compatibility
- AVI, MKV, MP4, FLV: Frame accurate
- WMV: Frame accurate(?) but avformat seems to pick keyframes relatively far away
- OGM: Frame accurate(?)
- VOB, MPG: Seeking seems to be off by one or two frames now and then
- M2TS, TS: Seeking seems to be off a few frames here and there
- Image files: Most formats can be opened if seekmode=-1 is set, no animation support
## Indexing and You
Before FFMS2 can open a file, it must be indexed first so that keyframe/sample positions are known and seeking is easily accomplished.
This is done automatically when using `Source()`,
but if you want to you can invoke the indexing yourself by calling `Index()`, or by running `ffmsindex`.
By default the index is written to a file so it can be reused the next time you open the same file, but this behavior can be turned off if desired.
If you wonder why FFMS2 takes so long opening files, the indexing is the answer.
If you want a progress report on the indexing, you can use the supplied `ffmsindex` commandline program.
## Function reference
### Index
```
ffms2.Index(string source[, string cachefile = source + ".ffindex", int[] indextracks = [],
int errorhandling = 3, bint overwrite = False])
```
Indexes a number of tracks in a given source file and writes the index file to disk, where it can be picked up and used by `Source`.
Normally you do not need to call this function manually; it's invoked automatically if necessary by `Source`.
It does, however, give you more control over how indexing is done.
Note that this function returns an integer, not a clip (since it doesn't open video, nor audio).
The return value isn't particularly interesting, but for the record it's 0 if the index file already exists (and is valid) and overwrite was not enabled, 1 if the index file was created and no previous index existed, and 2 if the index file was created by overwriting an existing, valid index file.
#### Arguments
##### string source
The source file to index.
##### string cachefile = source + ".ffindex"
The filename of the index file (where the indexing data is saved).
Defaults to `sourcefilename.ffindex`.
##### int[] indextracks = []
An array containing a list of which audio tracks should be indexed (all video tracks are always indexed; you have no choice in the matter).
It's possible to use -1 to simply tell it to index all tracks.´without having to list them individually.
Note that FFMS2's idea about what track has what number may be completely different from what any other application might think.
##### int errorhandling = 3
Controls what happens if an audio decoding error is encountered during indexing.
Possible values are:
- **0**: Raise an error and abort indexing. No index file is written.
- **1**: Clear the affected track (effectively making it silent) and continue.
- **2**: Stop indexing the track but keep all the index entries so far, effectively ending the track where the error occured.
- **3**: Pretend it's raining and continue anyway. This is the default; if you encounter odd noises in the audio, try mode 0 instead and see if it's FFMS2's fault.
##### bint overwrite = False
If set to true, `FFIndex()` will reindex the source file and overwrite the index file even if the index file already exists and is valid.
Mostly useful for trackmask changes and testing.
### Source
```
ffms2.Source(string source[, int track = -1, bint cache = True,
string cachefile = source + ".ffindex", int fpsnum = -1, int fpsden = 1,
int threads = -1, string timecodes = "", int seekmode = 1,
int width = -1, int height = -1, string resizer = "BICUBIC",
int format, bint alpha = False])
```
Opens video. Will invoke indexing of all video tracks (but no audio tracks) if no valid index file is found.
#### Arguments
##### string source
The source file to open.
##### int track = -1
The video track number to open, as seen by the relevant demuxer.
Track numbers start from zero, and are guaranteed to be continous (i.e. there must be a track 1 if there is a track 0 and a track 2). -1 means open the first video track.
Note that FFMS2's idea about what track has what number may (or may not) be completely different from what some other application might think.
##### bint cache = True
If set to true (the default), `Source` will first check if the `cachefile` contains a valid index, and if it does, that index will be used.
If no index is found, all video tracks will be indexed, and the indexing data will be written to `cachefile` afterwards.
If set to false, `Source` will not look for an existing index file; instead all video tracks will be indexed when the script is opened, and the indexing data will be discarded after the script is closed; you will have to index again next time you open the script.
##### string cachefile = source + ".ffindex"
The filename of the index file (where the indexing data is saved).
Defaults to `sourcefilename.ffindex`.
Note that if you didn't change this parameter from its default value and `Source` encounters an index file that doesn't seem to match the file it's trying to open, it will automatically reindex and then overwrite the old index file.
On the other hand, if you *do* change it, `Source` will assume you have your reasons and throw an error instead if the index doesn't match the file.
##### int fpsnum = -1, int fpsden = 1
Controls the framerate of the output; used for VFR to CFR conversions.
If `fpsnum` is less than or equal to zero (the default), the output will contain the same frames that the input did, and the frame rate reported to VapourSynth will be set based on the input clip's average frame duration.
If `fpsnum` is greater than zero, `Source` will force a constant frame rate, expressed as a rational number where `fpsnum` is the numerator and `fpsden` is the denominator.
This may naturally cause `Source` to drop or duplicate frames to achieve the desired frame rate, and the output is not guaranteed to have the same number of frames that the input did.
##### int threads = -1
The number of decoding threads to request from libavcodec.
Setting it to less than or equal to zero means it defaults to the number of logical CPU's reported by the OS.
Note that this setting might be completely ignored by libavcodec under a number of conditions; most commonly because a lot of decoders actually do not support multithreading.
##### string timecodes = ""
Filename to write Matroska v2 timecodes for the opened video track to.
If the file exists, it will be truncated and overwritten.
Set to the empty string to disable timecodes writing (this is the default).
##### int seekmode = 1
Controls how seeking is done.
Mostly useful for getting uncooperative files to work.
Valid modes are:
- **-1**: Linear access without rewind; i.e. will throw an error if each successive requested frame number isn't bigger than the last one.
Only intended for opening images but might work on well with some obscure video format.
- **0**: Linear access (i.e. if you request frame `n` without having requested all frames from 0 to `n-1` in order first, all frames from 0 to `n` will have to be decoded before `n` can be delivered).
The definition of slow, but should make some formats "usable".
- **1**: Safe normal. Bases seeking decisions on the keyframe positions reported by libavformat.
- **2**: Unsafe normal. Same as mode 1, but no error will be thrown if the exact seek destination has to be guessed.
- **3**: Aggressive. Seeks in the forward direction even if no closer keyframe is known to exist. Only useful for testing and containers where libavformat doesn't report keyframes properly.
##### int width = -1, int height = -1
Sets the resolution of the output video, in pixels.
Setting either dimension to less than or equal to zero means the resolution of the first decoded video frame is used for that dimension.
These parameters are mostly useful because FFMS2 supports video streams that change resolution mid-stream which would otherwise have to be handled with a more complicated script.
##### string resizer = "BICUBIC"
The resizing algorithm to use if rescaling the image is necessary.
If the video uses subsampled chroma but your chosen output colorspace does not, the chosen resizer will be used to upscale the chroma planes, even if you did not request an image rescaling.
The available choices are `FAST_BILINEAR`, `BILINEAR`, `BICUBIC` (default), `X`, `POINT`, `AREA`, `BICUBLIN`, `GAUSS`, `SINC`, `LANCZOS` and `SPLINE`.
##### int format
Convert the output from whatever it was to the given format. If not specified the best matching output format is used.
##### bint alpha = False
Output the alpha channel as a second clip if it is present in the file. When set to True an array of two clips will be returned with alpha in the second one. If there is alpha information present.
#### Exported VapourSynth frame properties
There are several useful frame properties that are set. See the VapourSynth manual for a detailed explanation of them.
- _DurationNum
- _DurationDen
- _AbsoluteTime
- _SARNum
- _SARDen
- _Matrix
- _Primaries
- _Transfer
- _ChromaLocation
- _ColorRange
- _PictType
- _FieldBased
### SetLogLevel
```
ffms2.SetLogLevel(int Level = -8)
```
Sets the FFmpeg logging level, i.e. how much diagnostic spam it prints to STDERR.
Since many applications that open VapourSynth scripts do not provide a way to display things printed to STDERR, and since it's rather hard to make any sense of the printed messages unless you're quite familiar with FFmpeg internals, the usefulness of this function is rather limited for end users. It's mostly intended for debugging.
Defaults to quiet (no messages printed); a list of meaningful values can be found in `ffms.h`.
### GetLogLevel
```
ffms2.GetLogLevel()
```
Returns the current log level, as an integer.
### GetVersion
```
ffms2.GetVersion()
```
Returns the FFMS2 version, as a string.

674
ffms2/etc/COPYING.GPLv3 Normal file
View file

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

75
ffms2/etc/FFMS2.avsi Normal file
View file

@ -0,0 +1,75 @@
# FFmpegSource 2.22 helper functions
# Created by TheFluff
function FFFormatTime(int ms) {
s = ms / 1000
ms = ms % 1000
m = s / 60
s = s % 60
h = m / 60
m = m % 60
return ms < 0 ? "<Unknown>" : string(h) + ":" + string(m,"%02.0f") + ":" + string(s,"%02.0f") + "." + string(ms,"%03.0f")
}
function FFColorSpace(int i) {
i=(i<0||i>10) ? 2 : i
return Select(i,"RGB","BT709 (ITU-R Rec.709)","Unspecified","Unspecified","FCC","BT470BG (ITU-R Rec.601)","SMPTE 170M (ITU-R Rec.601)","SMPTE 240M","YCoCg","BT2020 NCL","BT2020 NC")
}
function FFColorRange(int i) {
i=(i<0||i>2) ? 0 : i
return Select(i,"Unknown/Unspecified","Limited range","Full range")
}
function FFCropping(int l, int t, int r, int b) {
return "Left="+String(l)+" Top="+String(t)+" Right="+String(r)+" Bottom="+String(b)
}
function FFSampAR(int num, int den) {
return num > 0 ? String(num)+":"+String(den)+((num<=0 || den<=0)?"":string(Float(num)/den," (%.3f)")) : "Unknown/Unspecified"
}
function FFPictType(int ch) {
s=chr(ch)
s = s + (
\ ch==73?" (Intra)":ch==80?" (Predicted)":ch==66?" (Bi-dir predicted)":ch==83?" (S(GMC)-VOP MPEG4)"
\ : ch==105?" (Switching Intra)":ch==112?" (Switching Predicted)":ch==98?" (FF_BI_TYPE)"
\ : " (Unknown)")
return s
}
function FFInfo(clip c, bool "framenum", bool "frametype", bool "cfrtime", bool "vfrtime", string "varprefix",
\ bool "colorspace",bool "colorrange",bool "cropping",bool "sar",bool "version",bool "showprefix") {
framenum = default(framenum,true)
frametype = default(frametype,true)
cfrtime = default(cfrtime,true)
vfrtime = default(vfrtime,true)
varprefix = default(varprefix, FFVAR_PREFIX)
colorSpace = default(colorspace,true)
colorrange = default(colorrange,true)
cropping = default(cropping,true)
sar = default(sar,true)
version = default(version,true)
showprefix = default(showprefix,false)
c.frameevaluate("""
fftempstring = ""
varprefix = """" + varprefix + """"
""")
version ? frameevaluate("""fftempstring = fftempstring + "Version: " + FFGetVersion + "\n" """, after_frame=true) : nop()
framenum ? frameevaluate("""fftempstring = fftempstring + "Frame Number: " + string(current_frame) + " of " + string(framecount()) + "\n" """, after_frame=true) : nop()
frametype ? frameevaluate("""fftempstring = fftempstring + "Picture Type: " + FFPictType(eval(varprefix + "FFPICT_TYPE")) + "\n" """, after_frame=true) : nop()
cfrtime ? frameevaluate("""fftempstring = fftempstring + "CFR Time: " + FFFormatTime(round((current_frame * 1000) / framerate())) + "\n" """, after_frame=true) : nop()
vfrtime ? frameevaluate("""fftempstring = fftempstring + "VFR Time: " + FFFormatTime(eval(varprefix + "FFVFR_TIME")) + "\n" """, after_frame=true) : nop()
colorspace ? frameevaluate("""fftempstring = fftempstring + "ColorSpace: " + FFColorSpace(eval(varprefix + "FFCOLOR_SPACE")) + "\n" """, after_frame=true) : nop()
colorrange ? frameevaluate("""fftempstring = fftempstring + "Color Range: " + FFColorRange(eval(varprefix + "FFCOLOR_RANGE")) + "\n" """, after_frame=true) : nop()
cropping ? frameevaluate("""fftempstring = fftempstring + "Cropping: " + FFCropping(eval(varprefix + "FFCROP_LEFT"),eval(varprefix + "FFCROP_TOP"),eval(varprefix + "FFCROP_RIGHT"),eval(varprefix + "FFCROP_BOTTOM")) + "\n" """, after_frame=true) : nop()
sar ? frameevaluate("""fftempstring = fftempstring + "SAR: " + FFSampAR(eval(varprefix + "FFSAR_NUM"),eval(varprefix + "FFSAR_DEN")) + "\n" """, after_frame=true) : nop()
showprefix ? frameevaluate("""fftempstring = fftempstring + "Prefix: '" + varprefix + "'\n" """, after_frame=true) : nop()
return scriptclip("subtitle(fftempstring, lsp = 1)", after_frame=true)
}

14
ffms2/ffms2.pc.in Normal file
View file

@ -0,0 +1,14 @@
# @configure_input@
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
Name: ffms2
Description: The Fabulous FM Library 2
Requires.private: libavformat libavcodec libswscale libavutil libswresample
Version: @FFMS_VERSION@
Libs.private: @ZLIB_LDFLAGS@ -lz
Libs: -L${libdir} -lffms2
Cflags: -I${includedir}

455
ffms2/include/ffms.h Normal file
View file

@ -0,0 +1,455 @@
// Copyright (c) 2007-2018 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFMS_H
#define FFMS_H
// Version format: major - minor - micro - bump
#define FFMS_VERSION ((2 << 24) | (31 << 16) | (0 << 8) | 0)
#include <stdint.h>
#include <stddef.h>
/********
* The following preprocessor voodoo ensures that all API symbols are exported
* as intended on all supported platforms, that non-API symbols are hidden (where possible),
* and that the correct calling convention and extern declarations are used.
* The end result should be that linking to FFMS2 Just Works.
********/
// Convenience for C++ users.
#if defined(__cplusplus)
# define FFMS_EXTERN_C extern "C"
#else
# define FFMS_EXTERN_C
#endif
// On win32, we need to ensure we use stdcall with all compilers.
#if defined(_WIN32) && !defined(_WIN64)
# define FFMS_CC __stdcall
#else
# define FFMS_CC
#endif
// compiler-specific deprecation attributes
#ifndef FFMS_EXPORTS
# if defined(__GNUC__) && (__GNUC__ >= 4)
# define FFMS_DEPRECATED __attribute__((deprecated))
# elif defined(_MSC_VER)
# define FFMS_DEPRECATED __declspec(deprecated)
# endif
#endif
#ifndef FFMS_DEPRECATED
// Define as empty if the compiler doesn't support deprecation attributes or
// if we're building FFMS2 itself
# define FFMS_DEPRECATED
#endif
// And now for some symbol hide-and-seek...
#if defined(_WIN32) && !defined(FFMS_STATIC) // MSVC
# if defined(FFMS_EXPORTS) // building the FFMS2 library itself, with visible API symbols
# define FFMS_API(ret) FFMS_EXTERN_C __declspec(dllexport) ret FFMS_CC
# define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED __declspec(dllexport) ret FFMS_CC
# else // building something that depends on FFMS2
# define FFMS_API(ret) FFMS_EXTERN_C __declspec(dllimport) ret FFMS_CC
# define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED __declspec(dllimport) ret FFMS_CC
# endif // defined(FFMS_EXPORTS)
// GCC 4 or later: export API symbols only. Some GCC 3.x versions support the visibility attribute too,
// but we don't really care enough about that to add compatibility defines for it.
#elif defined(__GNUC__) && __GNUC__ >= 4
# define FFMS_API(ret) FFMS_EXTERN_C __attribute__((visibility("default"))) ret FFMS_CC
# define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED __attribute__((visibility("default"))) ret FFMS_CC
#else // fallback for everything else
# define FFMS_API(ret) FFMS_EXTERN_C ret FFMS_CC
# define FFMS_DEPRECATED_API(ret) FFMS_EXTERN_C FFMS_DEPRECATED ret FFMS_CC
#endif // defined(_MSC_VER)
// we now return you to your regularly scheduled programming.
typedef struct FFMS_ErrorInfo {
int ErrorType;
int SubType;
int BufferSize;
char *Buffer;
} FFMS_ErrorInfo;
typedef struct FFMS_VideoSource FFMS_VideoSource;
typedef struct FFMS_AudioSource FFMS_AudioSource;
typedef struct FFMS_Indexer FFMS_Indexer;
typedef struct FFMS_Index FFMS_Index;
typedef struct FFMS_Track FFMS_Track;
typedef enum FFMS_Errors {
// No error
FFMS_ERROR_SUCCESS = 0,
// Main types - where the error occurred
FFMS_ERROR_INDEX = 1, // index file handling
FFMS_ERROR_INDEXING, // indexing
FFMS_ERROR_POSTPROCESSING, // video postprocessing (libpostproc)
FFMS_ERROR_SCALING, // image scaling (libswscale)
FFMS_ERROR_DECODING, // audio/video decoding
FFMS_ERROR_SEEKING, // seeking
FFMS_ERROR_PARSER, // file parsing
FFMS_ERROR_TRACK, // track handling
FFMS_ERROR_WAVE_WRITER, // WAVE64 file writer
FFMS_ERROR_CANCELLED, // operation aborted
FFMS_ERROR_RESAMPLING, // audio resampling (libavresample)
// Subtypes - what caused the error
FFMS_ERROR_UNKNOWN = 20, // unknown error
FFMS_ERROR_UNSUPPORTED, // format or operation is not supported with this binary
FFMS_ERROR_FILE_READ, // cannot read from file
FFMS_ERROR_FILE_WRITE, // cannot write to file
FFMS_ERROR_NO_FILE, // no such file or directory
FFMS_ERROR_VERSION, // wrong version
FFMS_ERROR_ALLOCATION_FAILED, // out of memory
FFMS_ERROR_INVALID_ARGUMENT, // invalid or nonsensical argument
FFMS_ERROR_CODEC, // decoder error
FFMS_ERROR_NOT_AVAILABLE, // requested mode or operation unavailable in this binary
FFMS_ERROR_FILE_MISMATCH, // provided index does not match the file
FFMS_ERROR_USER // problem exists between keyboard and chair
} FFMS_Errors;
typedef enum FFMS_SeekMode {
FFMS_SEEK_LINEAR_NO_RW = -1,
FFMS_SEEK_LINEAR = 0,
FFMS_SEEK_NORMAL = 1,
FFMS_SEEK_UNSAFE = 2,
FFMS_SEEK_AGGRESSIVE = 3
} FFMS_SeekMode;
typedef enum FFMS_IndexErrorHandling {
FFMS_IEH_ABORT = 0,
FFMS_IEH_CLEAR_TRACK = 1,
FFMS_IEH_STOP_TRACK = 2,
FFMS_IEH_IGNORE = 3
} FFMS_IndexErrorHandling;
typedef enum FFMS_TrackType {
FFMS_TYPE_UNKNOWN = -1,
FFMS_TYPE_VIDEO,
FFMS_TYPE_AUDIO,
FFMS_TYPE_DATA,
FFMS_TYPE_SUBTITLE,
FFMS_TYPE_ATTACHMENT
} FFMS_TrackType;
typedef enum FFMS_SampleFormat {
FFMS_FMT_U8 = 0,
FFMS_FMT_S16,
FFMS_FMT_S32,
FFMS_FMT_FLT,
FFMS_FMT_DBL
} FFMS_SampleFormat;
typedef enum FFMS_AudioChannel {
FFMS_CH_FRONT_LEFT = 0x00000001,
FFMS_CH_FRONT_RIGHT = 0x00000002,
FFMS_CH_FRONT_CENTER = 0x00000004,
FFMS_CH_LOW_FREQUENCY = 0x00000008,
FFMS_CH_BACK_LEFT = 0x00000010,
FFMS_CH_BACK_RIGHT = 0x00000020,
FFMS_CH_FRONT_LEFT_OF_CENTER = 0x00000040,
FFMS_CH_FRONT_RIGHT_OF_CENTER = 0x00000080,
FFMS_CH_BACK_CENTER = 0x00000100,
FFMS_CH_SIDE_LEFT = 0x00000200,
FFMS_CH_SIDE_RIGHT = 0x00000400,
FFMS_CH_TOP_CENTER = 0x00000800,
FFMS_CH_TOP_FRONT_LEFT = 0x00001000,
FFMS_CH_TOP_FRONT_CENTER = 0x00002000,
FFMS_CH_TOP_FRONT_RIGHT = 0x00004000,
FFMS_CH_TOP_BACK_LEFT = 0x00008000,
FFMS_CH_TOP_BACK_CENTER = 0x00010000,
FFMS_CH_TOP_BACK_RIGHT = 0x00020000,
FFMS_CH_STEREO_LEFT = 0x20000000,
FFMS_CH_STEREO_RIGHT = 0x40000000
} FFMS_AudioChannel;
typedef enum FFMS_Resizers {
FFMS_RESIZER_FAST_BILINEAR = 0x0001,
FFMS_RESIZER_BILINEAR = 0x0002,
FFMS_RESIZER_BICUBIC = 0x0004,
FFMS_RESIZER_X = 0x0008,
FFMS_RESIZER_POINT = 0x0010,
FFMS_RESIZER_AREA = 0x0020,
FFMS_RESIZER_BICUBLIN = 0x0040,
FFMS_RESIZER_GAUSS = 0x0080,
FFMS_RESIZER_SINC = 0x0100,
FFMS_RESIZER_LANCZOS = 0x0200,
FFMS_RESIZER_SPLINE = 0x0400
} FFMS_Resizers;
typedef enum FFMS_AudioDelayModes {
FFMS_DELAY_NO_SHIFT = -3,
FFMS_DELAY_TIME_ZERO = -2,
FFMS_DELAY_FIRST_VIDEO_TRACK = -1
} FFMS_AudioDelayModes;
typedef enum FFMS_ChromaLocations {
FFMS_LOC_UNSPECIFIED = 0,
FFMS_LOC_LEFT = 1,
FFMS_LOC_CENTER = 2,
FFMS_LOC_TOPLEFT = 3,
FFMS_LOC_TOP = 4,
FFMS_LOC_BOTTOMLEFT = 5,
FFMS_LOC_BOTTOM = 6
} FFMS_ChromaLocations;
typedef enum FFMS_ColorRanges {
FFMS_CR_UNSPECIFIED = 0,
FFMS_CR_MPEG = 1, // 219*2^(n-8), i.e. 16-235 with 8-bit samples
FFMS_CR_JPEG = 2 // 2^n-1, or "fullrange"
} FFMS_ColorRanges;
typedef enum FFMS_Stereo3DType {
FFMS_S3D_TYPE_2D = 0,
FFMS_S3D_TYPE_SIDEBYSIDE,
FFMS_S3D_TYPE_TOPBOTTOM,
FFMS_S3D_TYPE_FRAMESEQUENCE,
FFMS_S3D_TYPE_CHECKERBOARD,
FFMS_S3D_TYPE_SIDEBYSIDE_QUINCUNX,
FFMS_S3D_TYPE_LINES,
FFMS_S3D_TYPE_COLUMNS
} FFMS_Stereo3DType;
typedef enum FFMS_Stereo3DFlags {
FFMS_S3D_FLAGS_INVERT = 1
} FFMS_Stereo3DFlags;
typedef enum FFMS_MixingCoefficientType {
FFMS_MIXING_COEFFICIENT_Q8 = 0,
FFMS_MIXING_COEFFICIENT_Q15 = 1,
FFMS_MIXING_COEFFICIENT_FLT = 2
} FFMS_MixingCoefficientType;
typedef enum FFMS_MatrixEncoding {
FFMS_MATRIX_ENCODING_NONE = 0,
FFMS_MATRIX_ENCODING_DOBLY = 1,
FFMS_MATRIX_ENCODING_PRO_LOGIC_II = 2,
FFMS_MATRIX_ENCODING_PRO_LOGIC_IIX = 3,
FFMS_MATRIX_ENCODING_PRO_LOGIC_IIZ = 4,
FFMS_MATRIX_ENCODING_DOLBY_EX = 5,
FFMS_MATRIX_ENCODING_DOLBY_HEADPHONE = 6
} FFMS_MatrixEncoding;
typedef enum FFMS_ResampleFilterType {
FFMS_RESAMPLE_FILTER_CUBIC = 0,
FFMS_RESAMPLE_FILTER_SINC = 1, /* misnamed as multiple windowsed sinc filters exist, actually called BLACKMAN_NUTTALL */
FFMS_RESAMPLE_FILTER_KAISER = 2
} FFMS_ResampleFilterType;
typedef enum FFMS_AudioDitherMethod {
FFMS_RESAMPLE_DITHER_NONE = 0,
FFMS_RESAMPLE_DITHER_RECTANGULAR = 1,
FFMS_RESAMPLE_DITHER_TRIANGULAR = 2,
FFMS_RESAMPLE_DITHER_TRIANGULAR_HIGHPASS = 3,
FFMS_RESAMPLE_DITHER_TRIANGULAR_NOISESHAPING = 4
} FFMS_AudioDitherMethod;
typedef enum FFMS_LogLevels {
FFMS_LOG_QUIET = -8,
FFMS_LOG_PANIC = 0,
FFMS_LOG_FATAL = 8,
FFMS_LOG_ERROR = 16,
FFMS_LOG_WARNING = 24,
FFMS_LOG_INFO = 32,
FFMS_LOG_VERBOSE = 40,
FFMS_LOG_DEBUG = 48,
FFMS_LOG_TRACE = 56
} FFMS_LogLevels;
typedef struct FFMS_ResampleOptions {
int64_t ChannelLayout;
FFMS_SampleFormat SampleFormat;
int SampleRate;
FFMS_MixingCoefficientType MixingCoefficientType;
double CenterMixLevel;
double SurroundMixLevel;
double LFEMixLevel;
int Normalize;
int ForceResample;
int ResampleFilterSize;
int ResamplePhaseShift;
int LinearInterpolation;
double CutoffFrequencyRatio;
FFMS_MatrixEncoding MatrixedStereoEncoding;
FFMS_ResampleFilterType FilterType;
int KaiserBeta;
FFMS_AudioDitherMethod DitherMethod;
} FFMS_ResampleOptions;
typedef struct FFMS_Frame {
const uint8_t *Data[4];
int Linesize[4];
int EncodedWidth;
int EncodedHeight;
int EncodedPixelFormat;
int ScaledWidth;
int ScaledHeight;
int ConvertedPixelFormat;
int KeyFrame;
int RepeatPict;
int InterlacedFrame;
int TopFieldFirst;
char PictType;
int ColorSpace;
int ColorRange;
/* Introduced in FFMS_VERSION ((2 << 24) | (21 << 16) | (0 << 8) | 0) */
int ColorPrimaries;
int TransferCharateristics;
int ChromaLocation;
/* Introduced in FFMS_VERSION ((2 << 24) | (27 << 16) | (0 << 8) | 0) */
int HasMasteringDisplayPrimaries; /* Non-zero if the 4 fields below are valid */
double MasteringDisplayPrimariesX[3];
double MasteringDisplayPrimariesY[3];
double MasteringDisplayWhitePointX;
double MasteringDisplayWhitePointY;
int HasMasteringDisplayLuminance; /* Non-zero if the 2 fields below are valid */
double MasteringDisplayMinLuminance;
double MasteringDisplayMaxLuminance;
int HasContentLightLevel; /* Non-zero if the 2 fields below are valid */
unsigned int ContentLightLevelMax;
unsigned int ContentLightLevelAverage;
} FFMS_Frame;
typedef struct FFMS_TrackTimeBase {
int64_t Num;
int64_t Den;
} FFMS_TrackTimeBase;
typedef struct FFMS_FrameInfo {
int64_t PTS;
int RepeatPict;
int KeyFrame;
int64_t OriginalPTS;
} FFMS_FrameInfo;
typedef struct FFMS_VideoProperties {
int FPSDenominator;
int FPSNumerator;
int RFFDenominator;
int RFFNumerator;
int NumFrames;
int SARNum;
int SARDen;
int CropTop;
int CropBottom;
int CropLeft;
int CropRight;
int TopFieldFirst;
FFMS_DEPRECATED int ColorSpace; /* Provided in FFMS_Frame */
FFMS_DEPRECATED int ColorRange; /* Provided in FFMS_Frame */
double FirstTime;
double LastTime;
/* Introduced in FFMS_VERSION ((2 << 24) | (24 << 16) | (0 << 8) | 0) */
int Rotation;
int Stereo3DType;
int Stereo3DFlags;
/* Introduced in FFMS_VERSION ((2 << 24) | (30 << 16) | (0 << 8) | 0) */
double LastEndTime;
int HasMasteringDisplayPrimaries; /* Non-zero if the 4 fields below are valid */
double MasteringDisplayPrimariesX[3];
double MasteringDisplayPrimariesY[3];
double MasteringDisplayWhitePointX;
double MasteringDisplayWhitePointY;
int HasMasteringDisplayLuminance; /* Non-zero if the 2 fields below are valid */
double MasteringDisplayMinLuminance;
double MasteringDisplayMaxLuminance;
int HasContentLightLevel; /* Non-zero if the 2 fields below are valid */
unsigned int ContentLightLevelMax;
unsigned int ContentLightLevelAverage;
/* Introduced in FFMS_VERSION ((2 << 24) | (31 << 16) | (0 << 8) | 0) */
int Flip;
} FFMS_VideoProperties;
typedef struct FFMS_AudioProperties {
int SampleFormat;
int SampleRate;
int BitsPerSample;
int Channels;
int64_t ChannelLayout; // should probably be a plain int, none of the constants are >32 bits long
int64_t NumSamples;
double FirstTime;
double LastTime;
/* Introduced in FFMS_VERSION ((2 << 24) | (30 << 16) | (0 << 8) | 0) */
double LastEndTime;
} FFMS_AudioProperties;
typedef int (FFMS_CC *TIndexCallback)(int64_t Current, int64_t Total, void *ICPrivate);
/* Most functions return 0 on success */
/* Functions without error message output can be assumed to never fail in a graceful way */
FFMS_API(void) FFMS_Init(int, int); /* Pass 0 to both arguments, kept to partially preserve abi */
FFMS_API(void) FFMS_Deinit();
FFMS_API(int) FFMS_GetVersion();
FFMS_API(int) FFMS_GetLogLevel();
FFMS_API(void) FFMS_SetLogLevel(int Level);
FFMS_API(FFMS_VideoSource *) FFMS_CreateVideoSource(const char *SourceFile, int Track, FFMS_Index *Index, int Threads, int SeekMode, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(FFMS_AudioSource *) FFMS_CreateAudioSource(const char *SourceFile, int Track, FFMS_Index *Index, int DelayMode, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(void) FFMS_DestroyVideoSource(FFMS_VideoSource *V);
FFMS_API(void) FFMS_DestroyAudioSource(FFMS_AudioSource *A);
FFMS_API(const FFMS_VideoProperties *) FFMS_GetVideoProperties(FFMS_VideoSource *V);
FFMS_API(const FFMS_AudioProperties *) FFMS_GetAudioProperties(FFMS_AudioSource *A);
FFMS_API(const FFMS_Frame *) FFMS_GetFrame(FFMS_VideoSource *V, int n, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(const FFMS_Frame *) FFMS_GetFrameByTime(FFMS_VideoSource *V, double Time, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_GetAudio(FFMS_AudioSource *A, void *Buf, int64_t Start, int64_t Count, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_SetOutputFormatV2(FFMS_VideoSource *V, const int *TargetFormats, int Width, int Height, int Resizer, FFMS_ErrorInfo *ErrorInfo); /* Introduced in FFMS_VERSION ((2 << 24) | (15 << 16) | (3 << 8) | 0) */
FFMS_API(void) FFMS_ResetOutputFormatV(FFMS_VideoSource *V);
FFMS_API(int) FFMS_SetInputFormatV(FFMS_VideoSource *V, int ColorSpace, int ColorRange, int Format, FFMS_ErrorInfo *ErrorInfo); /* Introduced in FFMS_VERSION ((2 << 24) | (17 << 16) | (1 << 8) | 0) */
FFMS_API(void) FFMS_ResetInputFormatV(FFMS_VideoSource *V);
FFMS_API(FFMS_ResampleOptions *) FFMS_CreateResampleOptions(FFMS_AudioSource *A); /* Introduced in FFMS_VERSION ((2 << 24) | (15 << 16) | (4 << 8) | 0) */
FFMS_API(int) FFMS_SetOutputFormatA(FFMS_AudioSource *A, const FFMS_ResampleOptions*options, FFMS_ErrorInfo *ErrorInfo); /* Introduced in FFMS_VERSION ((2 << 24) | (15 << 16) | (4 << 8) | 0) */
FFMS_API(void) FFMS_DestroyResampleOptions(FFMS_ResampleOptions *options); /* Introduced in FFMS_VERSION ((2 << 24) | (15 << 16) | (4 << 8) | 0) */
FFMS_API(void) FFMS_DestroyIndex(FFMS_Index *Index);
FFMS_API(int) FFMS_GetFirstTrackOfType(FFMS_Index *Index, int TrackType, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_GetFirstIndexedTrackOfType(FFMS_Index *Index, int TrackType, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_GetNumTracks(FFMS_Index *Index);
FFMS_API(int) FFMS_GetNumTracksI(FFMS_Indexer *Indexer);
FFMS_API(int) FFMS_GetTrackType(FFMS_Track *T);
FFMS_API(int) FFMS_GetTrackTypeI(FFMS_Indexer *Indexer, int Track);
FFMS_API(FFMS_IndexErrorHandling) FFMS_GetErrorHandling(FFMS_Index *Index);
FFMS_API(const char *) FFMS_GetCodecNameI(FFMS_Indexer *Indexer, int Track);
FFMS_API(const char *) FFMS_GetFormatNameI(FFMS_Indexer *Indexer);
FFMS_API(int) FFMS_GetNumFrames(FFMS_Track *T);
FFMS_API(const FFMS_FrameInfo *) FFMS_GetFrameInfo(FFMS_Track *T, int Frame);
FFMS_API(FFMS_Track *) FFMS_GetTrackFromIndex(FFMS_Index *Index, int Track);
FFMS_API(FFMS_Track *) FFMS_GetTrackFromVideo(FFMS_VideoSource *V);
FFMS_API(FFMS_Track *) FFMS_GetTrackFromAudio(FFMS_AudioSource *A);
FFMS_API(const FFMS_TrackTimeBase *) FFMS_GetTimeBase(FFMS_Track *T);
FFMS_API(int) FFMS_WriteTimecodes(FFMS_Track *T, const char *TimecodeFile, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(FFMS_Indexer *) FFMS_CreateIndexer(const char *SourceFile, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(void) FFMS_TrackIndexSettings(FFMS_Indexer *Indexer, int Track, int Index, int); /* Pass 0 to last argument, kapt to preserve abi. Introduced in FFMS_VERSION ((2 << 24) | (21 << 16) | (0 << 8) | 0) */
FFMS_API(void) FFMS_TrackTypeIndexSettings(FFMS_Indexer *Indexer, int TrackType, int Index, int); /* Pass 0 to last argument, kapt to preserve abi. Introduced in FFMS_VERSION ((2 << 24) | (21 << 16) | (0 << 8) | 0) */
FFMS_API(void) FFMS_SetProgressCallback(FFMS_Indexer *Indexer, TIndexCallback IC, void *ICPrivate); /* Introduced in FFMS_VERSION ((2 << 24) | (21 << 16) | (0 << 8) | 0) */
FFMS_API(FFMS_Index *) FFMS_DoIndexing2(FFMS_Indexer *Indexer, int ErrorHandling, FFMS_ErrorInfo *ErrorInfo); /* Introduced in FFMS_VERSION ((2 << 24) | (21 << 16) | (0 << 8) | 0) */
FFMS_API(void) FFMS_CancelIndexing(FFMS_Indexer *Indexer);
FFMS_API(FFMS_Index *) FFMS_ReadIndex(const char *IndexFile, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(FFMS_Index *) FFMS_ReadIndexFromBuffer(const uint8_t *Buffer, size_t Size, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_IndexBelongsToFile(FFMS_Index *Index, const char *SourceFile, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_WriteIndex(const char *IndexFile, FFMS_Index *Index, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(int) FFMS_WriteIndexToBuffer(uint8_t **BufferPtr, size_t *Size, FFMS_Index *Index, FFMS_ErrorInfo *ErrorInfo);
FFMS_API(void) FFMS_FreeIndexBuffer(uint8_t **BufferPtr);
FFMS_API(int) FFMS_GetPixFmt(const char *Name);
#endif

View file

@ -0,0 +1,38 @@
// Copyright (c) 2007-2011 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFMSCOMPAT_H
#define FFMSCOMPAT_H
#ifdef __GNUC__
# define ffms_used __attribute__((used))
#else
# define ffms_used
#endif
#define VERSION_CHECK(LIB, cmp, major, minor, micro) ((LIB) cmp (AV_VERSION_INT(major, minor, micro)))
#if VERSION_CHECK(LIBAVFORMAT_VERSION_INT, <, 58, 9, 100)
# define FFMS_REGISTER() av_register_all();
#else
# define FFMS_REGISTER()
#endif
#endif // FFMSCOMPAT_H

508
ffms2/install-sh Executable file
View file

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

11156
ffms2/ltmain.sh Normal file

File diff suppressed because it is too large Load diff

28
ffms2/m4/check_zlib.m4 Normal file
View file

@ -0,0 +1,28 @@
AC_DEFUN([CHECK_ZLIB],[
AC_ARG_WITH(zlib,AS_HELP_STRING([--with-zlib=DIR],[specify zlib's root installation folder]),
[ZLIB_HOME="$with_zlib"])
if test -n "${ZLIB_HOME}" -a "${ZLIB_HOME}" != "yes" -a "${ZLIB_HOME}" != "no" ; then
ZLIB_CPPFLAGS="-I${ZLIB_HOME}/include"
ZLIB_LDFLAGS="-L${ZLIB_HOME}/lib"
fi
ZLIB_OLD_LDFLAGS=$LDFLAGS
ZLIB_OLD_CPPFLAGS=$CPPFLAGS
LDFLAGS="$LDFLAGS $ZLIB_LDFLAGS"
CPPFLAGS="$CPPFLAGS $ZLIB_CPPFLAGS"
AC_LANG_PUSH(C)
AC_CHECK_HEADER(zlib.h, [zlib_cv_zlib_h=yes], [zlib_cv_zlib_h=no])
AC_CHECK_LIB(z, inflateEnd, [zlib_cv_libz=yes], [zlib_cv_libz=no])
AC_LANG_POP(C)
LDFLAGS=$ZLIB_OLD_LDFLAGS
CPPFLAGS=$ZLIB_OLD_CPPFLAGS
if test "$zlib_cv_libz" = "yes" -a "$zlib_cv_zlib_h" = "yes"
then
HAVE_ZLIB=yes
AC_SUBST([ZLIB_CPPFLAGS])
AC_SUBST([ZLIB_LDFLAGS])
else
AC_MSG_FAILURE([cannot locate zlib.h and -lz, specify a valid zlib installation using --with-zlib=DIR])
fi
])

8387
ffms2/m4/libtool.m4 vendored Normal file

File diff suppressed because it is too large Load diff

437
ffms2/m4/ltoptions.m4 vendored Normal file
View file

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

124
ffms2/m4/ltsugar.m4 vendored Normal file
View file

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

23
ffms2/m4/ltversion.m4 vendored Normal file
View file

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

99
ffms2/m4/lt~obsolete.m4 vendored Normal file
View file

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

215
ffms2/missing Executable file
View file

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

View file

@ -0,0 +1,357 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <string>
#include "ffms.h"
#include "avssources.h"
#include "../core/utils.h"
static AVSValue __cdecl CreateFFIndex(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
if (!Args[0].Defined())
Env->ThrowError("FFIndex: No source specified");
FFMS_Init(0, 0);
const char *Source = Args[0].AsString();
const char *CacheFile = Args[1].AsString("");
int IndexMask = Args[2].AsInt(-1);
int ErrorHandling = Args[3].AsInt(FFMS_IEH_IGNORE);
bool OverWrite = Args[4].AsBool(false);
std::string DefaultCache(Source);
DefaultCache.append(".ffindex");
if (!strcmp(CacheFile, ""))
CacheFile = DefaultCache.c_str();
ErrorInfo E;
FFMS_Index *Index = FFMS_ReadIndex(CacheFile, &E);
if (OverWrite || !Index || (Index && FFMS_IndexBelongsToFile(Index, Source, 0) != FFMS_ERROR_SUCCESS)) {
FFMS_Indexer *Indexer = FFMS_CreateIndexer(Source, &E);
if (!Indexer)
Env->ThrowError("FFIndex: %s", E.Buffer);
// Treat -1 as meaning track numbers above sizeof(int) too
if (IndexMask == -1)
FFMS_TrackTypeIndexSettings(Indexer, FFMS_TYPE_AUDIO, 1, 0);
// Apply attributes to remaining tracks (will set the attributes again on some tracks)
for (int i = 0; i < sizeof(IndexMask) * 8; i++) {
if ((IndexMask >> i) & 1)
FFMS_TrackIndexSettings(Indexer, i, 1, 0);
}
Index = FFMS_DoIndexing2(Indexer, ErrorHandling, &E);
if (!Index)
Env->ThrowError("FFIndex: %s", E.Buffer);
if (FFMS_WriteIndex(CacheFile, Index, &E)) {
FFMS_DestroyIndex(Index);
Env->ThrowError("FFIndex: %s", E.Buffer);
}
FFMS_DestroyIndex(Index);
if (!OverWrite)
return AVSValue(1);
else
return AVSValue(2);
} else {
FFMS_DestroyIndex(Index);
return AVSValue(0);
}
}
static AVSValue __cdecl CreateFFVideoSource(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
FFMS_Init(0, 0);
if (!Args[0].Defined())
Env->ThrowError("FFVideoSource: No source specified");
const char *Source = Args[0].AsString();
int Track = Args[1].AsInt(-1);
bool Cache = Args[2].AsBool(true);
const char *CacheFile = Args[3].AsString("");
int FPSNum = Args[4].AsInt(-1);
int FPSDen = Args[5].AsInt(1);
int Threads = Args[6].AsInt(-1);
const char *Timecodes = Args[7].AsString("");
int SeekMode = Args[8].AsInt(1);
int RFFMode = Args[9].AsInt(0);
int Width = Args[10].AsInt(0);
int Height = Args[11].AsInt(0);
const char *Resizer = Args[12].AsString("BICUBIC");
const char *ColorSpace = Args[13].AsString("");
const char *VarPrefix = Args[14].AsString("");
if (FPSDen < 1)
Env->ThrowError("FFVideoSource: FPS denominator needs to be 1 or higher");
if (Track <= -2)
Env->ThrowError("FFVideoSource: No video track selected");
if (SeekMode < -1 || SeekMode > 3)
Env->ThrowError("FFVideoSource: Invalid seekmode selected");
if (RFFMode < 0 || RFFMode > 2)
Env->ThrowError("FFVideoSource: Invalid RFF mode selected");
if (RFFMode > 0 && FPSNum > 0)
Env->ThrowError("FFVideoSource: RFF modes may not be combined with CFR conversion");
if (IsSamePath(Source, Timecodes))
Env->ThrowError("FFVideoSource: Timecodes will overwrite the source");
ErrorInfo E;
FFMS_Index *Index = nullptr;
std::string DefaultCache;
if (Cache) {
if (*CacheFile) {
if (IsSamePath(Source, CacheFile))
Env->ThrowError("FFVideoSource: Cache will overwrite the source");
Index = FFMS_ReadIndex(CacheFile, &E);
} else {
DefaultCache = Source;
DefaultCache += ".ffindex";
CacheFile = DefaultCache.c_str();
Index = FFMS_ReadIndex(CacheFile, &E);
// Reindex if the index doesn't match the file and its name wasn't
// explicitly given
if (Index && FFMS_IndexBelongsToFile(Index, Source, 0) != FFMS_ERROR_SUCCESS) {
FFMS_DestroyIndex(Index);
Index = 0;
}
}
}
if (!Index) {
FFMS_Indexer *Indexer = FFMS_CreateIndexer(Source, &E);
if (!Indexer)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
Index = FFMS_DoIndexing2(Indexer, FFMS_IEH_CLEAR_TRACK, &E);
if (!Index)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
if (Cache)
if (FFMS_WriteIndex(CacheFile, Index, &E)) {
FFMS_DestroyIndex(Index);
Env->ThrowError("FFVideoSource: %s", E.Buffer);
}
}
if (Track == -1)
Track = FFMS_GetFirstIndexedTrackOfType(Index, FFMS_TYPE_VIDEO, &E);
if (Track < 0)
Env->ThrowError("FFVideoSource: No video track found");
if (strcmp(Timecodes, "")) {
if (FFMS_WriteTimecodes(FFMS_GetTrackFromIndex(Index, Track), Timecodes, &E)) {
FFMS_DestroyIndex(Index);
Env->ThrowError("FFVideoSource: %s", E.Buffer);
}
}
AvisynthVideoSource *Filter;
try {
Filter = new AvisynthVideoSource(Source, Track, Index, FPSNum, FPSDen, Threads, SeekMode, RFFMode, Width, Height, Resizer, ColorSpace, VarPrefix, Env);
} catch (...) {
FFMS_DestroyIndex(Index);
throw;
}
FFMS_DestroyIndex(Index);
return Filter;
}
static AVSValue __cdecl CreateFFAudioSource(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
FFMS_Init(0, 0);
if (!Args[0].Defined())
Env->ThrowError("FFAudioSource: No source specified");
const char *Source = Args[0].AsString();
int Track = Args[1].AsInt(-1);
bool Cache = Args[2].AsBool(true);
const char *CacheFile = Args[3].AsString("");
int AdjustDelay = Args[4].AsInt(-1);
const char *VarPrefix = Args[5].AsString("");
if (Track <= -2)
Env->ThrowError("FFAudioSource: No audio track selected");
ErrorInfo E;
FFMS_Index *Index = nullptr;
std::string DefaultCache;
if (Cache) {
if (*CacheFile) {
if (IsSamePath(Source, CacheFile))
Env->ThrowError("FFAudioSource: Cache will overwrite the source");
Index = FFMS_ReadIndex(CacheFile, &E);
} else {
DefaultCache = Source;
DefaultCache += ".ffindex";
CacheFile = DefaultCache.c_str();
Index = FFMS_ReadIndex(CacheFile, &E);
// Reindex if the index doesn't match the file and its name wasn't
// explicitly given
if (Index && FFMS_IndexBelongsToFile(Index, Source, 0) != FFMS_ERROR_SUCCESS) {
FFMS_DestroyIndex(Index);
Index = 0;
}
}
}
// Index needs to be remade if it is an unindexed audio track
if (Index && Track >= 0 && Track < FFMS_GetNumTracks(Index)
&& FFMS_GetTrackType(FFMS_GetTrackFromIndex(Index, Track)) == FFMS_TYPE_AUDIO
&& FFMS_GetNumFrames(FFMS_GetTrackFromIndex(Index, Track)) == 0) {
FFMS_DestroyIndex(Index);
Index = nullptr;
}
// More complicated for finding a default track, reindex the file if at least one audio track exists
if (Index && FFMS_GetFirstTrackOfType(Index, FFMS_TYPE_AUDIO, &E) >= 0
&& FFMS_GetFirstIndexedTrackOfType(Index, FFMS_TYPE_AUDIO, &E) < 0) {
for (int i = 0; i < FFMS_GetNumTracks(Index); i++) {
if (FFMS_GetTrackType(FFMS_GetTrackFromIndex(Index, i)) == FFMS_TYPE_AUDIO) {
FFMS_DestroyIndex(Index);
Index = nullptr;
break;
}
}
}
if (!Index) {
FFMS_Indexer *Indexer = FFMS_CreateIndexer(Source, &E);
if (!Indexer)
Env->ThrowError("FFAudioSource: %s", E.Buffer);
FFMS_TrackTypeIndexSettings(Indexer, FFMS_TYPE_AUDIO, 1, 0);
Index = FFMS_DoIndexing2(Indexer, FFMS_IEH_CLEAR_TRACK, &E);
if (!Index)
Env->ThrowError("FFAudioSource: %s", E.Buffer);
if (Cache)
if (FFMS_WriteIndex(CacheFile, Index, &E)) {
FFMS_DestroyIndex(Index);
Env->ThrowError("FFAudioSource: %s", E.Buffer);
}
}
if (Track == -1)
Track = FFMS_GetFirstIndexedTrackOfType(Index, FFMS_TYPE_AUDIO, &E);
if (Track < 0)
Env->ThrowError("FFAudioSource: No audio track found");
if (AdjustDelay < -3)
Env->ThrowError("FFAudioSource: Invalid delay adjustment specified");
if (AdjustDelay >= FFMS_GetNumTracks(Index))
Env->ThrowError("FFAudioSource: Invalid track to calculate delay from specified");
AvisynthAudioSource *Filter;
try {
Filter = new AvisynthAudioSource(Source, Track, Index, AdjustDelay, VarPrefix, Env);
} catch (...) {
FFMS_DestroyIndex(Index);
throw;
}
FFMS_DestroyIndex(Index);
return Filter;
}
static AVSValue __cdecl CreateFFmpegSource2(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
const char *FFIArgNames[] = { "source", "cachefile", "indexmask", "overwrite" };
const char *FFVArgNames[] = { "source", "track", "cache", "cachefile", "fpsnum", "fpsden", "threads", "timecodes", "seekmode", "rffmode", "width", "height", "resizer", "colorspace", "varprefix" };
const char *FFAArgNames[] = { "source", "track", "cache", "cachefile", "adjustdelay", "varprefix" };
bool Cache = Args[3].AsBool(true);
bool WithAudio = Args[2].AsInt(-2) > -2;
if (Cache) {
AVSValue FFIArgs[] = { Args[0], Args[4], WithAudio ? -1 : 0, Args[10] };
static_assert((sizeof(FFIArgs) / sizeof(FFIArgs[0])) == (sizeof(FFIArgNames) / sizeof(FFIArgNames[0])), "Arg error");
Env->Invoke("FFIndex", AVSValue(FFIArgs, sizeof(FFIArgs) / sizeof(FFIArgs[0])), FFIArgNames);
}
AVSValue FFVArgs[] = { Args[0], Args[1], Args[3], Args[4], Args[5], Args[6], Args[7], Args[8], Args[9], Args[15], Args[11], Args[12], Args[13], Args[14], Args[17] };
static_assert((sizeof(FFVArgs) / sizeof(FFVArgs[0])) == (sizeof(FFVArgNames) / sizeof(FFVArgNames[0])), "Arg error");
AVSValue Video = Env->Invoke("FFVideoSource", AVSValue(FFVArgs, sizeof(FFVArgs) / sizeof(FFVArgs[0])), FFVArgNames);
AVSValue Audio;
if (WithAudio) {
AVSValue FFAArgs[] = { Args[0], Args[2], Args[3], Args[4], Args[16], Args[17] };
static_assert((sizeof(FFAArgs) / sizeof(FFAArgs[0])) == (sizeof(FFAArgNames) / sizeof(FFAArgNames[0])), "Arg error");
Audio = Env->Invoke("FFAudioSource", AVSValue(FFAArgs, sizeof(FFAArgs) / sizeof(FFAArgs[0])), FFAArgNames);
AVSValue ADArgs[] = { Video, Audio };
return Env->Invoke("AudioDubEx", AVSValue(ADArgs, sizeof(ADArgs) / sizeof(ADArgs[0])));
} else {
return Video;
}
}
static AVSValue __cdecl CreateFFImageSource(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
const char *FFISArgNames[] = { "source", "width", "height", "resizer", "colorspace", "varprefix", "cache", "seekmode" };
AVSValue FFISArgs[] = { Args[0], Args[1], Args[2], Args[3], Args[4], Args[5], false, -1 };
static_assert((sizeof(FFISArgs) / sizeof(FFISArgs[0])) == (sizeof(FFISArgNames) / sizeof(FFISArgNames[0])), "Arg error");
return Env->Invoke("FFVideoSource", AVSValue(FFISArgs, sizeof(FFISArgs) / sizeof(FFISArgs[0])), FFISArgNames);
}
static AVSValue __cdecl CreateFFCopyrightInfringement(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
const char *ArgNames[] = { "source" };
Env->Invoke("FFIndex", Args, ArgNames);
AVSValue ExArgs[2] = { Env->Invoke("FFVideoSource", Args, ArgNames), Env->Invoke("FFAudioSource", Args, ArgNames) };
return Env->Invoke("AudioDubEx", AVSValue(ExArgs, sizeof(ExArgs) / sizeof(ExArgs[0])));
}
static AVSValue __cdecl FFGetLogLevel(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
return FFMS_GetLogLevel();
}
static AVSValue __cdecl FFSetLogLevel(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
FFMS_SetLogLevel(Args[0].AsInt());
return FFMS_GetLogLevel();
}
static AVSValue __cdecl FFGetVersion(AVSValue Args, void* UserData, IScriptEnvironment* Env) {
int Version = FFMS_GetVersion();
return Env->Sprintf("%d.%d.%d.%d", Version >> 24, (Version & 0xFF0000) >> 16, (Version & 0xFF00) >> 8, Version & 0xFF);
}
const AVS_Linkage *AVS_linkage = nullptr;
extern "C" __declspec(dllexport) const char* __stdcall AvisynthPluginInit3(IScriptEnvironment* Env, const AVS_Linkage* const vectors) {
AVS_linkage = vectors;
Env->AddFunction("FFIndex", "[source]s[cachefile]s[indexmask]i[errorhandling]i[overwrite]b", CreateFFIndex, nullptr);
Env->AddFunction("FFVideoSource", "[source]s[track]i[cache]b[cachefile]s[fpsnum]i[fpsden]i[threads]i[timecodes]s[seekmode]i[rffmode]i[width]i[height]i[resizer]s[colorspace]s[varprefix]s", CreateFFVideoSource, nullptr);
Env->AddFunction("FFAudioSource", "[source]s[track]i[cache]b[cachefile]s[adjustdelay]i[varprefix]s", CreateFFAudioSource, nullptr);
Env->AddFunction("FFmpegSource2", "[source]s[vtrack]i[atrack]i[cache]b[cachefile]s[fpsnum]i[fpsden]i[threads]i[timecodes]s[seekmode]i[overwrite]b[width]i[height]i[resizer]s[colorspace]s[rffmode]i[adjustdelay]i[varprefix]s", CreateFFmpegSource2, nullptr);
Env->AddFunction("FFMS2", "[source]s[vtrack]i[atrack]i[cache]b[cachefile]s[fpsnum]i[fpsden]i[threads]i[timecodes]s[seekmode]i[overwrite]b[width]i[height]i[resizer]s[colorspace]s[rffmode]i[adjustdelay]i[varprefix]s", CreateFFmpegSource2, nullptr);
Env->AddFunction("FFImageSource", "[source]s[width]i[height]i[resizer]s[colorspace]s[varprefix]s", CreateFFImageSource, nullptr);
Env->AddFunction("FFCopyrightInfringement", "[source]s", CreateFFCopyrightInfringement, nullptr);
Env->AddFunction("FFGetLogLevel", "", FFGetLogLevel, nullptr);
Env->AddFunction("FFSetLogLevel", "i", FFSetLogLevel, nullptr);
Env->AddFunction("FFGetVersion", "", FFGetVersion, nullptr);
return "FFmpegSource - The Second Coming V2.0 Final";
}

View file

@ -0,0 +1,610 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#define NOMINMAX
#include "avssources.h"
#include "../core/utils.h"
#include <algorithm>
#include <cassert>
static AVPixelFormat CSNameToPIXFMT(const char *CSName, AVPixelFormat Default, bool HighBitDepth) {
if (!CSName)
return AV_PIX_FMT_NONE;
std::string s = CSName;
std::transform(s.begin(), s.end(), s.begin(), toupper);
if (s == "")
return Default;
if (s == "YUV9" || s == "YUV410P8")
return AV_PIX_FMT_YUV410P;
if (s == "YV411" || s == "YUV411P8")
return AV_PIX_FMT_YUV411P;
if (s == "YV12" || s == "YUV420P8")
return AV_PIX_FMT_YUV420P;
if (s == "YV16" || s == "YUV422P8")
return AV_PIX_FMT_YUV422P;
if (s == "YV24" || s == "YUV444P8")
return AV_PIX_FMT_YUV444P;
if (s == "Y8" || s == "GRAY8")
return AV_PIX_FMT_GRAY8;
if (s == "YUY2")
return AV_PIX_FMT_YUYV422;
if (s == "RGB24")
return AV_PIX_FMT_BGR24;
if (s == "RGB32")
return AV_PIX_FMT_RGB32;
if (HighBitDepth) {
if (s == "YUVA420P8")
return AV_PIX_FMT_YUVA420P;
if (s == "YUVA422P8")
return AV_PIX_FMT_YUVA422P;
if (s == "YUVA444P8")
return AV_PIX_FMT_YUVA444P;
if (s == "YUV420P16")
return AV_PIX_FMT_YUV420P16;
if (s == "YUVA420P16")
return AV_PIX_FMT_YUVA420P16;
if (s == "YUV422P16")
return AV_PIX_FMT_YUV422P16;
if (s == "YUVA422P16")
return AV_PIX_FMT_YUVA422P16;
if (s == "YUV444P16")
return AV_PIX_FMT_YUV444P16;
if (s == "YUVA444P16")
return AV_PIX_FMT_YUVA444P16;
if (s == "YUV420P10")
return AV_PIX_FMT_YUV420P10;
if (s == "YUVA420P10")
return AV_PIX_FMT_YUVA420P10;
if (s == "YUV422P10")
return AV_PIX_FMT_YUV422P10;
if (s == "YUVA422P10")
return AV_PIX_FMT_YUVA422P10;
if (s == "YUV444P10")
return AV_PIX_FMT_YUV444P10;
if (s == "YUVA444P10")
return AV_PIX_FMT_YUVA444P10;
if (s == "RGBP8")
return AV_PIX_FMT_GBRP;
if (s == "RGBP10")
return AV_PIX_FMT_GBRP10;
if (s == "RGBP12")
return AV_PIX_FMT_GBRP12;
if (s == "RGBP16")
return AV_PIX_FMT_GBRP16;
if (s == "RGBPS")
return AV_PIX_FMT_GBRPF32;
if (s == "RGBAP8")
return AV_PIX_FMT_GBRAP;
if (s == "RGBAP10")
return AV_PIX_FMT_GBRAP10;
if (s == "RGBAP12")
return AV_PIX_FMT_GBRAP12;
if (s == "RGBAP16")
return AV_PIX_FMT_GBRAP16;
if (s == "RGBAPS")
return AV_PIX_FMT_GBRAPF32;
if (s == "Y10" || s == "GRAY10")
return AV_PIX_FMT_GRAY10;
if (s == "Y12" || s == "GRAY12")
return AV_PIX_FMT_GRAY12;
if (s == "Y16" || s == "GRAY16")
return AV_PIX_FMT_GRAY16;
}
return AV_PIX_FMT_NONE;
}
AvisynthVideoSource::AvisynthVideoSource(const char *SourceFile, int Track, FFMS_Index *Index,
int FPSNum, int FPSDen, int Threads, int SeekMode, int RFFMode,
int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
const char *ConvertToFormatName, const char *VarPrefix, IScriptEnvironment* Env)
: FPSNum(FPSNum)
, FPSDen(FPSDen)
, RFFMode(RFFMode)
, VarPrefix(VarPrefix) {
VI = {};
// check if the two functions we need for many bits are present
VI.pixel_type = VideoInfo::CS_Y16;
HighBitDepth = (VI.ComponentSize() == 2 && VI.IsY());
VI.pixel_type = VideoInfo::CS_UNKNOWN;
ErrorInfo E;
V = FFMS_CreateVideoSource(SourceFile, Track, Index, Threads, SeekMode, &E);
if (!V)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
try {
InitOutputFormat(ResizeToWidth, ResizeToHeight, ResizerName, ConvertToFormatName, Env);
} catch (AvisynthError &) {
FFMS_DestroyVideoSource(V);
throw;
}
const FFMS_VideoProperties *VP = FFMS_GetVideoProperties(V);
if (RFFMode > 0) {
// This part assumes things, and so should you
FFMS_Track *VTrack = FFMS_GetTrackFromVideo(V);
if (FFMS_GetFrameInfo(VTrack, 0)->RepeatPict < 0) {
FFMS_DestroyVideoSource(V);
Env->ThrowError("FFVideoSource: No RFF flags present");
}
int RepeatMin = FFMS_GetFrameInfo(VTrack, 0)->RepeatPict;;
int NumFields = 0;
for (int i = 0; i < VP->NumFrames; i++) {
int RepeatPict = FFMS_GetFrameInfo(VTrack, i)->RepeatPict;
NumFields += RepeatPict + 1;
RepeatMin = std::min(RepeatMin, RepeatPict);
}
for (int i = 0; i < VP->NumFrames; i++) {
int RepeatPict = FFMS_GetFrameInfo(VTrack, i)->RepeatPict;
if (((RepeatPict + 1) * 2) % (RepeatMin + 1)) {
FFMS_DestroyVideoSource(V);
Env->ThrowError("FFVideoSource: Unsupported RFF flag pattern");
}
}
VI.fps_denominator = VP->RFFDenominator * (RepeatMin + 1);
VI.fps_numerator = VP->RFFNumerator;
VI.num_frames = (NumFields + RepeatMin) / (RepeatMin + 1);
int DestField = 0;
FieldList.resize(VI.num_frames);
for (int i = 0; i < VP->NumFrames; i++) {
int RepeatPict = FFMS_GetFrameInfo(VTrack, i)->RepeatPict;
int RepeatFields = ((RepeatPict + 1) * 2) / (RepeatMin + 1);
for (int j = 0; j < RepeatFields; j++) {
if ((DestField + (VP->TopFieldFirst ? 0 : 1)) & 1)
FieldList[DestField / 2].Top = i;
else
FieldList[DestField / 2].Bottom = i;
DestField++;
}
}
if (RFFMode == 2) {
VI.num_frames = (VI.num_frames * 4) / 5;
VI.fps_denominator *= 5;
VI.fps_numerator *= 4;
int OutputFrames = 0;
for (int i = 0; i < VI.num_frames / 4; i++) {
bool HasDropped = false;
FieldList[OutputFrames].Top = FieldList[i * 5].Top;
FieldList[OutputFrames].Bottom = FieldList[i * 5].Top;
OutputFrames++;
for (int j = 1; j < 5; j++) {
if (!HasDropped && FieldList[i * 5 + j - 1].Top == FieldList[i * 5 + j].Top) {
HasDropped = true;
continue;
}
FieldList[OutputFrames].Top = FieldList[i * 5 + j].Top;
FieldList[OutputFrames].Bottom = FieldList[i * 5 + j].Top;
OutputFrames++;
}
if (!HasDropped)
OutputFrames--;
}
if (OutputFrames > 0)
for (int i = OutputFrames - 1; i < static_cast<int>(FieldList.size()); i++) {
FieldList[i].Top = FieldList[OutputFrames - 1].Top;
FieldList[i].Bottom = FieldList[OutputFrames - 1].Top;
}
FieldList.resize(VI.num_frames);
}
} else {
if (FPSNum > 0 && FPSDen > 0) {
VI.fps_denominator = FPSDen;
VI.fps_numerator = FPSNum;
if (VP->NumFrames > 1) {
VI.num_frames = static_cast<int>((VP->LastTime - VP->FirstTime) * (1 + 1. / (VP->NumFrames - 1)) * FPSNum / FPSDen + 0.5);
if (VI.num_frames < 1) VI.num_frames = 1;
} else {
VI.num_frames = 1;
}
} else {
VI.fps_denominator = VP->FPSDenominator;
VI.fps_numerator = VP->FPSNumerator;
VI.num_frames = VP->NumFrames;
}
}
// Set AR variables
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFSAR_NUM"), VP->SARNum);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFSAR_DEN"), VP->SARDen);
if (VP->SARNum > 0 && VP->SARDen > 0)
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFSAR"), VP->SARNum / (double)VP->SARDen);
// Set crop variables
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_LEFT"), VP->CropLeft);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_RIGHT"), VP->CropRight);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_TOP"), VP->CropTop);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCROP_BOTTOM"), VP->CropBottom);
Env->SetGlobalVar("FFVAR_PREFIX", this->VarPrefix);
}
AvisynthVideoSource::~AvisynthVideoSource() {
FFMS_DestroyVideoSource(V);
}
static int GetSubSamplingH(const VideoInfo &vi) {
if ((vi.IsYUV() || vi.IsYUVA()) && !vi.IsY() && vi.IsPlanar())
return vi.GetPlaneHeightSubsampling(PLANAR_U);
else
return 0;
}
static int GetSubSamplingW(const VideoInfo &vi) {
if ((vi.IsYUV() || vi.IsYUVA()) && !vi.IsY() && vi.IsPlanar())
return vi.GetPlaneWidthSubsampling(PLANAR_U);
else
return 0;
}
void AvisynthVideoSource::InitOutputFormat(
int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
const char *ConvertToFormatName, IScriptEnvironment *Env) {
ErrorInfo E;
const FFMS_VideoProperties *VP = FFMS_GetVideoProperties(V);
const FFMS_Frame *F = FFMS_GetFrame(V, 0, &E);
if (!F)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
std::vector<int> TargetFormats;
if (HighBitDepth) {
TargetFormats.push_back(FFMS_GetPixFmt("yuv420p16"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva420p16"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv422p16"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva422p16"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv444p16"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva444p16"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv420p10"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva420p10"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv422p10"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva422p10"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv444p10"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva444p10"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrpf32"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrapf32"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrp16"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrap16"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrp12"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrap12"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrp10"));
TargetFormats.push_back(FFMS_GetPixFmt("gbrap10"));
TargetFormats.push_back(FFMS_GetPixFmt("gray16"));
TargetFormats.push_back(FFMS_GetPixFmt("gray12"));
TargetFormats.push_back(FFMS_GetPixFmt("gray10"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva420p"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva422p"));
TargetFormats.push_back(FFMS_GetPixFmt("yuva444p"));
}
TargetFormats.push_back(FFMS_GetPixFmt("yuv410p"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv411p"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv420p"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv422p"));
TargetFormats.push_back(FFMS_GetPixFmt("yuv444p"));
TargetFormats.push_back(FFMS_GetPixFmt("gray8"));
TargetFormats.push_back(FFMS_GetPixFmt("yuyv422"));
TargetFormats.push_back(FFMS_GetPixFmt("bgra"));
// Remove unsupported formats from list so they don't appear as an early termination
TargetFormats.erase(std::remove(TargetFormats.begin(), TargetFormats.end(), -1), TargetFormats.end());
TargetFormats.push_back(-1);
// PIX_FMT_NV21 is misused as a return value different to the defined ones in the function
AVPixelFormat TargetPixelFormat = CSNameToPIXFMT(ConvertToFormatName, AV_PIX_FMT_NV21, HighBitDepth);
if (TargetPixelFormat == AV_PIX_FMT_NONE)
Env->ThrowError("FFVideoSource: Invalid colorspace name specified");
if (TargetPixelFormat != AV_PIX_FMT_NV21) {
TargetFormats.clear();
TargetFormats.push_back(TargetPixelFormat);
TargetFormats.push_back(-1);
}
if (ResizeToWidth <= 0)
ResizeToWidth = F->EncodedWidth;
if (ResizeToHeight <= 0)
ResizeToHeight = F->EncodedHeight;
int Resizer = ResizerNameToSWSResizer(ResizerName);
if (Resizer == 0)
Env->ThrowError("FFVideoSource: Invalid resizer name specified");
if (FFMS_SetOutputFormatV2(V, TargetFormats.data(),
ResizeToWidth, ResizeToHeight, Resizer, &E))
Env->ThrowError("FFVideoSource: No suitable output format found");
F = FFMS_GetFrame(V, 0, &E);
TargetFormats.clear();
TargetFormats.push_back(F->ConvertedPixelFormat);
TargetFormats.push_back(-1);
// This trick is required to first get the "best" default format and then set only that format as the output
if (FFMS_SetOutputFormatV2(V, TargetFormats.data(),
ResizeToWidth, ResizeToHeight, Resizer, &E))
Env->ThrowError("FFVideoSource: No suitable output format found");
F = FFMS_GetFrame(V, 0, &E);
if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuvj420p") || F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv420p"))
VI.pixel_type = VideoInfo::CS_I420;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva420p"))
VI.pixel_type = VideoInfo::CS_YUVA420;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuvj422p") || F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv422p"))
VI.pixel_type = VideoInfo::CS_YV16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva422p"))
VI.pixel_type = VideoInfo::CS_YUVA422;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuvj444p") || F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv444p"))
VI.pixel_type = VideoInfo::CS_YV24;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva444p"))
VI.pixel_type = VideoInfo::CS_YUVA444;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv411p"))
VI.pixel_type = VideoInfo::CS_YV411;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv410p"))
VI.pixel_type = VideoInfo::CS_YUV9;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gray8"))
VI.pixel_type = VideoInfo::CS_Y8;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuyv422"))
VI.pixel_type = VideoInfo::CS_YUY2;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("rgb32"))
VI.pixel_type = VideoInfo::CS_BGR32;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("bgr24"))
VI.pixel_type = VideoInfo::CS_BGR24;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv420p16"))
VI.pixel_type = VideoInfo::CS_YUV420P16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva420p16"))
VI.pixel_type = VideoInfo::CS_YUVA420P16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv422p16"))
VI.pixel_type = VideoInfo::CS_YUV422P16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva422p16"))
VI.pixel_type = VideoInfo::CS_YUVA422P16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv444p16"))
VI.pixel_type = VideoInfo::CS_YUV444P16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva444p16"))
VI.pixel_type = VideoInfo::CS_YUVA444P16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv420p10"))
VI.pixel_type = VideoInfo::CS_YUV420P10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva420p10"))
VI.pixel_type = VideoInfo::CS_YUVA420P10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv422p10"))
VI.pixel_type = VideoInfo::CS_YUV422P10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva422p10"))
VI.pixel_type = VideoInfo::CS_YUVA422P10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuv444p10"))
VI.pixel_type = VideoInfo::CS_YUV444P10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("yuva444p10"))
VI.pixel_type = VideoInfo::CS_YUVA444P10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrpf32"))
VI.pixel_type = VideoInfo::CS_RGBPS;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrp16"))
VI.pixel_type = VideoInfo::CS_RGBP16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrp12"))
VI.pixel_type = VideoInfo::CS_RGBP12;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrp10"))
VI.pixel_type = VideoInfo::CS_RGBP10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrapf32"))
VI.pixel_type = VideoInfo::CS_RGBAPS;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrap16"))
VI.pixel_type = VideoInfo::CS_RGBAP16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrap12"))
VI.pixel_type = VideoInfo::CS_RGBAP12;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrap10"))
VI.pixel_type = VideoInfo::CS_RGBAP10;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrp"))
VI.pixel_type = VideoInfo::CS_RGBP;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gbrap"))
VI.pixel_type = VideoInfo::CS_RGBAP;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gray16"))
VI.pixel_type = VideoInfo::CS_Y16;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gray12"))
VI.pixel_type = VideoInfo::CS_Y12;
else if (F->ConvertedPixelFormat == FFMS_GetPixFmt("gray10"))
VI.pixel_type = VideoInfo::CS_Y10;
else
Env->ThrowError("FFVideoSource: No suitable output format found");
if (RFFMode > 0 && ResizeToHeight != F->EncodedHeight)
Env->ThrowError("FFVideoSource: Vertical scaling not allowed in RFF mode");
if (RFFMode > 0 && TargetPixelFormat != AV_PIX_FMT_NV21)
Env->ThrowError("FFVideoSource: Only the default output colorspace can be used in RFF mode");
// set color information variables
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCOLOR_SPACE"), F->ColorSpace);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFCOLOR_RANGE"), F->ColorRange);
if (VP->TopFieldFirst)
VI.image_type = VideoInfo::IT_TFF;
else
VI.image_type = VideoInfo::IT_BFF;
VI.width = F->ScaledWidth;
VI.height = F->ScaledHeight;
// Crop to obey subsampling width/height requirements
VI.width -= VI.width % (1 << GetSubSamplingW(VI));
VI.height -= VI.height % (1 << (GetSubSamplingH(VI) + (RFFMode > 0 ? 1 : 0)));
}
static void BlitPlane(const FFMS_Frame *Frame, PVideoFrame &Dst, IScriptEnvironment *Env, int Plane, int PlaneId) {
Env->BitBlt(Dst->GetWritePtr(PlaneId), Dst->GetPitch(PlaneId),
Frame->Data[Plane], Frame->Linesize[Plane],
Dst->GetRowSize(PlaneId), Dst->GetHeight(PlaneId));
}
void AvisynthVideoSource::OutputFrame(const FFMS_Frame *Frame, PVideoFrame &Dst, IScriptEnvironment *Env) {
if (VI.IsPlanar()) {
BlitPlane(Frame, Dst, Env, 0, VI.IsRGB() ? PLANAR_G : PLANAR_Y);
if (HighBitDepth ? !VI.IsY() : !VI.IsY8()) {
BlitPlane(Frame, Dst, Env, 1, VI.IsRGB() ? PLANAR_B : PLANAR_U);
BlitPlane(Frame, Dst, Env, 2, VI.IsRGB() ? PLANAR_R : PLANAR_V);
}
if (VI.IsYUVA() || VI.IsPlanarRGBA())
BlitPlane(Frame, Dst, Env, 3, PLANAR_A);
} else if (VI.IsYUY2()) {
BlitPlane(Frame, Dst, Env, 0, 0);
} else if (VI.IsRGB24() || VI.IsRGB32()) {
Env->BitBlt(
Dst->GetWritePtr() + Dst->GetPitch() * (Dst->GetHeight() - 1), -Dst->GetPitch(),
Frame->Data[0], Frame->Linesize[0],
Dst->GetRowSize(), Dst->GetHeight());
} else {
assert(false);
}
}
static void BlitField(const FFMS_Frame *Frame, PVideoFrame &Dst, IScriptEnvironment *Env, int Plane, int PlaneId, int Field) {
Env->BitBlt(
Dst->GetWritePtr(PlaneId) + Dst->GetPitch(PlaneId) * Field, Dst->GetPitch(PlaneId) * 2,
Frame->Data[Plane] + Frame->Linesize[Plane] * Field, Frame->Linesize[Plane] * 2,
Dst->GetRowSize(PlaneId), Dst->GetHeight(PlaneId) / 2);
}
void AvisynthVideoSource::OutputField(const FFMS_Frame *Frame, PVideoFrame &Dst, int Field, IScriptEnvironment *Env) {
const FFMS_Frame *SrcPicture = Frame;
if (VI.IsPlanar()) {
BlitField(Frame, Dst, Env, 0, VI.IsRGB() ? PLANAR_G : PLANAR_Y, Field);
if (HighBitDepth ? !VI.IsY() : !VI.IsY8()) {
BlitField(Frame, Dst, Env, 1, VI.IsRGB() ? PLANAR_B : PLANAR_U, Field);
BlitField(Frame, Dst, Env, 2, VI.IsRGB() ? PLANAR_R : PLANAR_V, Field);
}
if (VI.IsYUVA() || VI.IsPlanarRGBA())
BlitField(Frame, Dst, Env, 3, PLANAR_A, Field);
} else if (VI.IsYUY2()) {
BlitField(Frame, Dst, Env, 0, 0, Field);
} else if (VI.IsRGB24() || VI.IsRGB32()) {
Env->BitBlt(
Dst->GetWritePtr() + Dst->GetPitch() * (Dst->GetHeight() - 1 - Field), -Dst->GetPitch() * 2,
SrcPicture->Data[0] + SrcPicture->Linesize[0] * Field, SrcPicture->Linesize[0] * 2,
Dst->GetRowSize(), Dst->GetHeight() / 2);
} else {
assert(false);
}
}
PVideoFrame AvisynthVideoSource::GetFrame(int n, IScriptEnvironment *Env) {
n = std::min(std::max(n, 0), VI.num_frames - 1);
PVideoFrame Dst = Env->NewVideoFrame(VI);
ErrorInfo E;
if (RFFMode > 0) {
const FFMS_Frame *Frame = FFMS_GetFrame(V, std::min(FieldList[n].Top, FieldList[n].Bottom), &E);
if (Frame == nullptr)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
if (FieldList[n].Top == FieldList[n].Bottom) {
OutputFrame(Frame, Dst, Env);
} else {
int FirstField = std::min(FieldList[n].Top, FieldList[n].Bottom) == FieldList[n].Bottom;
OutputField(Frame, Dst, FirstField, Env);
Frame = FFMS_GetFrame(V, std::max(FieldList[n].Top, FieldList[n].Bottom), &E);
if (Frame == nullptr)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
OutputField(Frame, Dst, !FirstField, Env);
}
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFVFR_TIME"), -1);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFPICT_TYPE"), static_cast<int>('U'));
} else {
const FFMS_Frame *Frame;
if (FPSNum > 0 && FPSDen > 0) {
Frame = FFMS_GetFrameByTime(V, FFMS_GetVideoProperties(V)->FirstTime +
(double)(n * (int64_t)FPSDen) / FPSNum, &E);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFVFR_TIME"), -1);
} else {
Frame = FFMS_GetFrame(V, n, &E);
FFMS_Track *T = FFMS_GetTrackFromVideo(V);
const FFMS_TrackTimeBase *TB = FFMS_GetTimeBase(T);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFVFR_TIME"), static_cast<int>(FFMS_GetFrameInfo(T, n)->PTS * static_cast<double>(TB->Num) / TB->Den));
}
if (Frame == nullptr)
Env->ThrowError("FFVideoSource: %s", E.Buffer);
Env->SetVar(Env->Sprintf("%s%s", this->VarPrefix, "FFPICT_TYPE"), static_cast<int>(Frame->PictType));
OutputFrame(Frame, Dst, Env);
}
return Dst;
}
bool AvisynthVideoSource::GetParity(int n) {
return VI.image_type == VideoInfo::IT_TFF;
}
AvisynthAudioSource::AvisynthAudioSource(const char *SourceFile, int Track, FFMS_Index *Index,
int AdjustDelay, const char *VarPrefix, IScriptEnvironment* Env) {
VI = {};
ErrorInfo E;
A = FFMS_CreateAudioSource(SourceFile, Track, Index, AdjustDelay, &E);
if (!A)
Env->ThrowError("FFAudioSource: %s", E.Buffer);
const FFMS_AudioProperties *AP = FFMS_GetAudioProperties(A);
VI.nchannels = AP->Channels;
VI.num_audio_samples = AP->NumSamples;
VI.audio_samples_per_second = AP->SampleRate;
// casting to int should be safe; none of the channel constants are greater than INT_MAX
Env->SetVar(Env->Sprintf("%s%s", VarPrefix, "FFCHANNEL_LAYOUT"), static_cast<int>(AP->ChannelLayout));
Env->SetGlobalVar("FFVAR_PREFIX", VarPrefix);
switch (AP->SampleFormat) {
case FFMS_FMT_U8: VI.sample_type = SAMPLE_INT8; break;
case FFMS_FMT_S16: VI.sample_type = SAMPLE_INT16; break;
case FFMS_FMT_S32: VI.sample_type = SAMPLE_INT32; break;
case FFMS_FMT_FLT: VI.sample_type = SAMPLE_FLOAT; break;
default: Env->ThrowError("FFAudioSource: Bad audio format");
}
}
AvisynthAudioSource::~AvisynthAudioSource() {
FFMS_DestroyAudioSource(A);
}
void AvisynthAudioSource::GetAudio(void* Buf, __int64 Start, __int64 Count, IScriptEnvironment *Env) {
ErrorInfo E;
if (FFMS_GetAudio(A, Buf, Start, Count, &E))
Env->ThrowError("FFAudioSource: %s", E.Buffer);
}

View file

@ -0,0 +1,83 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFAVSSOURCES_H
#define FFAVSSOURCES_H
#include <vector>
#include <windows.h>
#include <avisynth.h>
#include "ffms.h"
struct ErrorInfo : FFMS_ErrorInfo {
char ErrorBuffer[1024];
ErrorInfo() {
Buffer = ErrorBuffer;
BufferSize = sizeof(ErrorBuffer);
}
};
class AvisynthVideoSource : public IClip {
struct FrameFields {
int Top;
int Bottom;
};
VideoInfo VI;
bool HighBitDepth;
FFMS_VideoSource *V;
int FPSNum;
int FPSDen;
int RFFMode;
std::vector<FrameFields> FieldList;
const char *VarPrefix;
void InitOutputFormat(int ResizeToWidth, int ResizeToHeight,
const char *ResizerName, const char *ConvertToFormatName, IScriptEnvironment *Env);
void OutputFrame(const FFMS_Frame *Frame, PVideoFrame &Dst, IScriptEnvironment *Env);
void OutputField(const FFMS_Frame *Frame, PVideoFrame &Dst, int Field, IScriptEnvironment *Env);
public:
AvisynthVideoSource(const char *SourceFile, int Track, FFMS_Index *Index,
int FPSNum, int FPSDen, int Threads, int SeekMode, int RFFMode,
int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
const char *ConvertToFormatName, const char *VarPrefix, IScriptEnvironment* Env);
~AvisynthVideoSource();
bool __stdcall GetParity(int n);
int __stdcall SetCacheHints(int cachehints, int frame_range) { return 0; }
const VideoInfo& __stdcall GetVideoInfo() { return VI; }
void __stdcall GetAudio(void* Buf, __int64 Start, __int64 Count, IScriptEnvironment *Env) {}
PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment *Env);
};
class AvisynthAudioSource : public IClip {
VideoInfo VI;
FFMS_AudioSource *A;
public:
AvisynthAudioSource(const char *SourceFile, int Track, FFMS_Index *Index,
int AdjustDelay, const char *VarPrefix, IScriptEnvironment* Env);
~AvisynthAudioSource();
bool __stdcall GetParity(int n) { return false; }
int __stdcall SetCacheHints(int cachehints, int frame_range) { return 0; }
const VideoInfo& __stdcall GetVideoInfo() { return VI; }
void __stdcall GetAudio(void* Buf, __int64 Start, __int64 Count, IScriptEnvironment *Env);
PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment *Env) { return nullptr; };
};
#endif

View file

@ -0,0 +1,61 @@
/* src/config/config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#undef LT_OBJDIR
/* Name of package */
#undef PACKAGE
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the home page for this package. */
#undef PACKAGE_URL
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Version number of package */
#undef VERSION

View file

@ -0,0 +1,538 @@
// Copyright (c) 2010 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "audiosource.h"
#include "indexing.h"
#include <algorithm>
#include <cassert>
extern "C" {
#include <libavutil/channel_layout.h>
}
namespace {
#define MAPPER(m, n) OptionMapper<FFMS_ResampleOptions>(n, &FFMS_ResampleOptions::m)
OptionMapper<FFMS_ResampleOptions> resample_options[] = {
MAPPER(ChannelLayout, "out_channel_layout"),
MAPPER(SampleFormat, "out_sample_fmt"),
MAPPER(SampleRate, "out_sample_rate"),
MAPPER(MixingCoefficientType, "mix_coeff_type"),
MAPPER(CenterMixLevel, "center_mix_level"),
MAPPER(SurroundMixLevel, "surround_mix_level"),
MAPPER(LFEMixLevel, "lfe_mix_level"),
MAPPER(Normalize, "normalize_mix_level"),
MAPPER(ForceResample, "force_resampling"),
MAPPER(ResampleFilterSize, "filter_size"),
MAPPER(ResamplePhaseShift, "phase_shift"),
MAPPER(LinearInterpolation, "linear_interp"),
MAPPER(CutoffFrequencyRatio, "cutoff"),
MAPPER(MatrixedStereoEncoding, "matrix_encoding"),
MAPPER(FilterType, "filter_type"),
MAPPER(KaiserBeta, "kaiser_beta"),
MAPPER(DitherMethod, "dither_method")
};
#undef MAPPER
}
FFMS_AudioSource::FFMS_AudioSource(const char *SourceFile, FFMS_Index &Index, int Track, int DelayMode)
: LastValidTS(AV_NOPTS_VALUE), SourceFile(SourceFile), ResampleContext{ swr_alloc() }, TrackNumber(Track) {
try {
if (Track < 0 || Track >= static_cast<int>(Index.size()))
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Out of bounds track index selected");
if (Index[Track].TT != FFMS_TYPE_AUDIO)
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Not an audio track");
if (Index[Track].empty())
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Audio track contains no audio frames");
if (!Index.CompareFileSignature(SourceFile))
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_FILE_MISMATCH,
"The index does not match the source file");
Frames = Index[Track];
DecodeFrame = av_frame_alloc();
if (!DecodeFrame)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Couldn't allocate frame");
OpenFile();
if (Frames.back().PTS == Frames.front().PTS)
SeekOffset = -1;
else
SeekOffset = 10;
Init(Index, DelayMode);
} catch (...) {
Free();
throw;
}
}
#define EXCESSIVE_CACHE_SIZE 400
void FFMS_AudioSource::Init(const FFMS_Index &Index, int DelayMode) {
// Decode the first packet to ensure all properties are initialized
// Don't cache it since it might be in the wrong format
for (size_t i = 0; i < Frames.size(); i++) {
if (DecodeNextBlock())
break;
}
// Read properties of the audio which may not be available until the first
// frame has been decoded
FillAP(AP, CodecContext, Frames);
if (AP.SampleRate <= 0 || AP.BitsPerSample <= 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Codec returned zero size audio");
auto opt = CreateResampleOptions();
SetOutputFormat(*opt);
if (DelayMode < FFMS_DELAY_NO_SHIFT)
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Bad audio delay compensation mode");
if (DelayMode == FFMS_DELAY_NO_SHIFT) return;
if (DelayMode > (signed)Index.size())
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Out of bounds track index selected for audio delay compensation");
if (DelayMode >= 0 && Index[DelayMode].TT != FFMS_TYPE_VIDEO)
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Audio delay compensation must be relative to a video track");
if (DelayMode == FFMS_DELAY_FIRST_VIDEO_TRACK) {
for (size_t i = 0; i < Index.size(); ++i) {
if (Index[i].TT == FFMS_TYPE_VIDEO && !Index[i].empty()) {
DelayMode = static_cast<int>(i);
break;
}
}
}
if (DelayMode >= 0) {
const FFMS_Track &VTrack = Index[DelayMode];
Delay = -(VTrack[0].PTS * VTrack.TB.Num * AP.SampleRate / (VTrack.TB.Den * 1000));
}
if (Frames.HasTS) {
int i = 0;
while (Frames[i].PTS == AV_NOPTS_VALUE) ++i;
Delay += Frames[i].PTS * Frames.TB.Num * AP.SampleRate / (Frames.TB.Den * 1000);
for (; i > 0; --i)
Delay -= Frames[i].SampleCount;
}
AP.NumSamples += Delay;
}
void FFMS_AudioSource::CacheBeginning() {
// Nothing to do if the cache is already populated
if (!Cache.empty()) return;
// The first packet after a seek is often decoded incorrectly, which
// makes it impossible to ever correctly seek back to the beginning, so
// store the first block now
// In addition, anything with the same PTS as the first packet can't be
// distinguished from the first packet and so can't be seeked to, so
// store those as well
// Some of LAVF's splitters don't like to seek to the beginning of the
// file (ts and?), so cache a few blocks even if PTSes are unique
// Packet 7 is the last packet I've had be unseekable to, so cache up to
// 10 for a bit of an extra buffer
auto end = Cache.end();
while (PacketNumber < Frames.size() &&
((Frames[0].PTS != AV_NOPTS_VALUE && Frames[PacketNumber].PTS == Frames[0].PTS) ||
Cache.size() < 10)) {
// Vorbis in particular seems to like having 60+ packets at the start
// of the file with a PTS of 0, so we might need to expand the search
// range to account for that.
// Expanding slightly before it's strictly needed to ensure there's a
// bit of space for an actual cache
if (Cache.size() >= MaxCacheBlocks - 5) {
if (MaxCacheBlocks >= EXCESSIVE_CACHE_SIZE)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Exceeded the search range for an initial valid audio PTS");
MaxCacheBlocks *= 2;
}
DecodeNextBlock(&end);
}
// Store the iterator to the last element of the cache which is used for
// correctness rather than speed, so that when looking for one to delete
// we know how much to skip
CacheNoDelete = Cache.end();
--CacheNoDelete;
}
void FFMS_AudioSource::SetOutputFormat(FFMS_ResampleOptions const& opt) {
if (opt.SampleRate != AP.SampleRate)
throw FFMS_Exception(FFMS_ERROR_RESAMPLING, FFMS_ERROR_UNSUPPORTED,
"Sample rate changes are currently unsupported.");
// Cache stores audio in the output format, so clear it and reopen the file
Cache.clear();
PacketNumber = 0;
OpenFile();
avcodec_flush_buffers(CodecContext);
BytesPerSample = av_get_bytes_per_sample(static_cast<AVSampleFormat>(opt.SampleFormat)) * av_get_channel_layout_nb_channels(opt.ChannelLayout);
NeedsResample =
opt.SampleFormat != (int)CodecContext->sample_fmt ||
opt.SampleRate != AP.SampleRate ||
opt.ChannelLayout != AP.ChannelLayout ||
opt.ForceResample;
if (!NeedsResample) return;
FFResampleContext newContext{ swr_alloc() };
SetOptions(opt, newContext.get(), resample_options);
av_opt_set_int(newContext.get(), "in_sample_rate", AP.SampleRate, 0);
av_opt_set_int(newContext.get(), "in_sample_fmt", CodecContext->sample_fmt, 0);
av_opt_set_int(newContext.get(), "in_channel_layout", AP.ChannelLayout, 0);
av_opt_set_int(newContext.get(), "out_sample_rate", opt.SampleRate, 0);
av_opt_set_channel_layout(newContext.get(), "out_channel_layout", opt.ChannelLayout, 0);
av_opt_set_sample_fmt(newContext.get(), "out_sample_fmt", (AVSampleFormat)opt.SampleFormat, 0);
if (swr_init(newContext.get()))
throw FFMS_Exception(FFMS_ERROR_RESAMPLING, FFMS_ERROR_UNKNOWN,
"Could not open avresample context");
newContext.swap(ResampleContext);
}
std::unique_ptr<FFMS_ResampleOptions> FFMS_AudioSource::CreateResampleOptions() const {
auto ret = ReadOptions(ResampleContext.get(), resample_options);
ret->SampleRate = AP.SampleRate;
ret->SampleFormat = static_cast<FFMS_SampleFormat>(AP.SampleFormat);
ret->ChannelLayout = AP.ChannelLayout;
return ret;
}
void FFMS_AudioSource::ResampleAndCache(CacheIterator pos) {
AudioBlock& block = *pos;
size_t size = DecodeFrame->nb_samples * BytesPerSample;
auto dst = block.Grow(size);
uint8_t *OutPlanes[1] = { dst };
swr_convert(ResampleContext.get(), OutPlanes, DecodeFrame->nb_samples, (const uint8_t **)DecodeFrame->extended_data, DecodeFrame->nb_samples);
}
FFMS_AudioSource::AudioBlock *FFMS_AudioSource::CacheBlock(CacheIterator &pos) {
// If the previous block has the same Start sample as this one, then
// we got multiple frames of audio out of a single packet and should
// combine them
auto block = pos;
if (pos == Cache.begin() || (--block)->Start != CurrentSample)
block = Cache.emplace(pos, CurrentSample);
block->Samples += DecodeFrame->nb_samples;
if (NeedsResample)
ResampleAndCache(block);
else {
const uint8_t *data = DecodeFrame->extended_data[0];
auto dst = block->Grow(DecodeFrame->nb_samples * BytesPerSample);
memcpy(dst, data, DecodeFrame->nb_samples * BytesPerSample);
}
if (Cache.size() >= MaxCacheBlocks) {
// Kill the oldest one
auto min = CacheNoDelete;
// Never drop the first one as the first packet decoded after a seek
// is often decoded incorrectly and we can't seek to before the first one
++min;
for (auto it = min; it != Cache.end(); ++it)
if (it->Age < min->Age) min = it;
if (min == pos) ++pos;
Cache.erase(min);
}
return &*block;
}
int FFMS_AudioSource::DecodeNextBlock(CacheIterator *pos) {
CurrentFrame = &Frames[PacketNumber];
AVPacket Packet;
if (!ReadPacket(&Packet))
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_UNKNOWN,
"ReadPacket unexpectedly failed to read a packet");
// ReadPacket may have changed the packet number
CurrentFrame = &Frames[PacketNumber];
CurrentSample = CurrentFrame->SampleStart;
int NumberOfSamples = 0;
AudioBlock *CachedBlock = nullptr;
int Ret = avcodec_send_packet(CodecContext, &Packet);
av_packet_unref(&Packet);
av_frame_unref(DecodeFrame);
Ret = avcodec_receive_frame(CodecContext, DecodeFrame);
if (Ret == 0) {
//FIXME, is DecodeFrame->nb_samples > 0 always true for decoded frames? I can't be bothered to find out
NumberOfSamples += DecodeFrame->nb_samples;
if (DecodeFrame->nb_samples > 0) {
if (pos)
CachedBlock = CacheBlock(*pos);
}
}
// Zero sample packets aren't included in the index
if (!NumberOfSamples)
return NumberOfSamples;
++PacketNumber;
// Add padding after the packet, if needed
if (!CachedBlock || CachedBlock->Samples == CurrentFrame->SampleCount)
return NumberOfSamples;
const int64_t MissingSamples = static_cast<int64_t>(CurrentFrame->SampleCount - CachedBlock->Samples);
// This can apparently happen in some rare circumstances, caused by inaccurate seeking?
if (MissingSamples <= 0)
return NumberOfSamples;
CachedBlock->Samples += MissingSamples;
const int64_t MissingBytes = MissingSamples * BytesPerSample;
if (MissingSamples > 200 || MissingSamples > CachedBlock->Samples - MissingSamples)
memset(CachedBlock->Grow(MissingBytes), 0, MissingBytes);
else {
auto ptr = CachedBlock->Grow(MissingBytes);
memcpy(ptr, ptr - MissingBytes, MissingBytes);
}
return NumberOfSamples;
}
static bool SampleStartComp(const FrameInfo &a, const FrameInfo &b) {
return a.SampleStart < b.SampleStart;
}
void FFMS_AudioSource::GetAudio(void *Buf, int64_t Start, int64_t Count) {
if (Start < 0 || Start + Count > AP.NumSamples || Count < 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_INVALID_ARGUMENT,
"Out of bounds audio samples requested");
CacheBeginning();
uint8_t *Dst = static_cast<uint8_t*>(Buf);
// Apply audio delay (if any) and fill any samples before the start time with zero
Start -= Delay;
if (Start < 0) {
size_t Bytes = static_cast<size_t>(BytesPerSample * FFMIN(-Start, Count));
memset(Dst, 0, Bytes);
Count += Start;
// Entire request was before the start of the audio
if (Count <= 0) return;
Start = 0;
Dst += Bytes;
}
auto it = Cache.begin();
while (Count > 0) {
// Find first useful cache block
while (it != Cache.end() && it->Start + it->Samples <= Start) ++it;
// Cache has the next block we want
if (it != Cache.end() && it->Start <= Start) {
int64_t SrcOffset = FFMAX(0, Start - it->Start);
int64_t DstOffset = FFMAX(0, it->Start - Start);
int64_t CopySamples = FFMIN(it->Samples - SrcOffset, Count - DstOffset);
size_t Bytes = static_cast<size_t>(CopySamples * BytesPerSample);
memcpy(Dst + DstOffset * BytesPerSample, it->Data.get() + SrcOffset * BytesPerSample, Bytes);
Start += CopySamples;
Count -= CopySamples;
Dst += Bytes;
++it;
}
// Decode another block
else {
if (Start < CurrentSample && SeekOffset == -1)
throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_CODEC, "Audio stream is not seekable");
if (SeekOffset >= 0 && (Start < CurrentSample || Start > CurrentSample + DecodeFrame->nb_samples * 5)) {
FrameInfo f;
f.SampleStart = Start;
size_t NewPacketNumber = std::distance(
Frames.begin(),
std::lower_bound(Frames.begin(), Frames.end(), f, SampleStartComp));
NewPacketNumber = NewPacketNumber > static_cast<size_t>(SeekOffset + 15)
? NewPacketNumber - SeekOffset - 15
: 0;
while (NewPacketNumber > 0 && !Frames[NewPacketNumber].KeyFrame) --NewPacketNumber;
// Only seek forward if it'll actually result in moving forward
if (Start < CurrentSample || static_cast<size_t>(NewPacketNumber) > PacketNumber) {
PacketNumber = NewPacketNumber;
CurrentSample = -1;
av_frame_unref(DecodeFrame);
avcodec_flush_buffers(CodecContext);
Seek();
}
}
// Decode until we hit the block we want
if (PacketNumber >= Frames.size())
throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_CODEC, "Seeking is severely broken");
while (CurrentSample + CurrentFrame->SampleCount <= Start && PacketNumber < Frames.size())
DecodeNextBlock(&it);
if (CurrentSample > Start)
throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_CODEC, "Seeking is severely broken");
// The block we want is now in the cache immediately before it
--it;
}
}
}
size_t FFMS_AudioSource::GetSeekablePacketNumber(FFMS_Track const& Frames, size_t PacketNumber) {
// Packets don't always have unique PTSes, so we may not be able to
// uniquely identify the packet we want. This function attempts to find
// a PTS we can seek to which will let us figure out which packet we're
// on before we get to the packet we actually wanted
// MatroskaAudioSource doesn't need this, as it seeks by byte offset
// rather than PTS. LAVF theoretically can seek by byte offset, but we
// don't use it as not all demuxers support it and it's broken in some of
// those that claim to support it
// However much we might wish to, we can't seek to before packet zero
if (PacketNumber == 0) return PacketNumber;
// Desired packet's PTS is unique, so don't do anything
if (Frames[PacketNumber].PTS != Frames[PacketNumber - 1].PTS &&
(PacketNumber + 1 == Frames.size() || Frames[PacketNumber].PTS != Frames[PacketNumber + 1].PTS))
return PacketNumber;
// When decoding, we only reliably know what packet we're at when the
// newly parsed packet has a different PTS from the previous one. As such,
// we walk backwards until we hit a different PTS and then seek to there,
// so that we can then decode until we hit the PTS group we actually wanted
// (and thereby know that we're at the first packet in the group rather
// than whatever the splitter happened to choose)
// This doesn't work if our desired packet has the same PTS as the first
// packet, but this scenario should never come up anyway; we permanently
// cache the decoded results from those packets, so there's no need to ever
// seek to them
int64_t PTS = Frames[PacketNumber].PTS;
while (PacketNumber > 0 && PTS == Frames[PacketNumber].PTS)
--PacketNumber;
return PacketNumber;
}
void FFMS_AudioSource::OpenFile() {
avcodec_free_context(&CodecContext);
avformat_close_input(&FormatContext);
LAVFOpenFile(SourceFile.c_str(), FormatContext, TrackNumber);
AVCodec *Codec = avcodec_find_decoder(FormatContext->streams[TrackNumber]->codecpar->codec_id);
if (Codec == nullptr)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Audio codec not found");
CodecContext = avcodec_alloc_context3(Codec);
if (CodecContext == nullptr)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate audio decoding context");
if (avcodec_parameters_to_context(CodecContext, FormatContext->streams[TrackNumber]->codecpar) < 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Could not copy audio codec parameters");
if (avcodec_open2(CodecContext, Codec, nullptr) < 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Could not open audio codec");
}
void FFMS_AudioSource::Free() {
av_frame_free(&DecodeFrame);
avcodec_free_context(&CodecContext);
avformat_close_input(&FormatContext);
}
FFMS_AudioSource::~FFMS_AudioSource() {
Free();
}
int64_t FFMS_AudioSource::FrameTS(size_t Packet) const {
return Frames.HasTS ? Frames[Packet].PTS : Frames[Packet].FilePos;
}
void FFMS_AudioSource::Seek() {
size_t TargetPacket = GetSeekablePacketNumber(Frames, PacketNumber);
LastValidTS = AV_NOPTS_VALUE;
int Flags = Frames.HasTS ? AVSEEK_FLAG_BACKWARD : AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_BYTE;
if (av_seek_frame(FormatContext, TrackNumber, FrameTS(TargetPacket), Flags) < 0)
av_seek_frame(FormatContext, TrackNumber, FrameTS(TargetPacket), Flags | AVSEEK_FLAG_ANY);
if (TargetPacket != PacketNumber) {
// Decode until the PTS changes so we know where we are
int64_t LastPTS = FrameTS(PacketNumber);
while (LastPTS == FrameTS(PacketNumber)) DecodeNextBlock();
}
}
bool FFMS_AudioSource::ReadPacket(AVPacket *Packet) {
InitNullPacket(*Packet);
while (av_read_frame(FormatContext, Packet) >= 0) {
if (Packet->stream_index == TrackNumber) {
// Required because not all audio packets, especially in ogg, have a pts. Use the previous valid packet's pts instead.
if (Packet->pts == AV_NOPTS_VALUE)
Packet->pts = LastValidTS;
else
LastValidTS = Packet->pts;
// This only happens if a really shitty demuxer seeks to a packet without pts *hrm* ogg *hrm* so read until a valid pts is reached
int64_t PacketTS = Frames.HasTS ? Packet->pts : Packet->pos;
if (PacketTS != AV_NOPTS_VALUE) {
while (PacketNumber > 0 && FrameTS(PacketNumber) > PacketTS) --PacketNumber;
while (FrameTS(PacketNumber) < PacketTS) ++PacketNumber;
return true;
}
}
av_packet_unref(Packet);
}
return false;
}

View file

@ -0,0 +1,148 @@
// Copyright (c) 2007-2011 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFAUDIOSOURCE_H
#define FFAUDIOSOURCE_H
#include "utils.h"
#include "track.h"
#include <list>
#include <vector>
#include <atomic>
struct FFMS_AudioSource {
struct AudioBlock {
struct Free {
void operator()(uint8_t *ptr) const {
free(ptr);
}
};
int64_t Age;
int64_t Start;
int64_t Samples = 0;
size_t DataSize = 0;
std::unique_ptr<uint8_t, Free> Data;
AudioBlock(int64_t Start)
: Start(Start) {
static std::atomic<int64_t> Now{ 0 };
Age = Now++;
}
uint8_t *Grow(size_t size) {
auto ptr = static_cast<uint8_t *>(realloc(Data.get(), DataSize + size));
if (!ptr)
throw std::bad_alloc();
Data.release();
Data.reset(ptr);
ptr += DataSize;
DataSize += size;
return ptr;
}
};
typedef std::list<AudioBlock>::iterator CacheIterator;
AVFormatContext *FormatContext = nullptr;
int64_t LastValidTS;
std::string SourceFile;
// delay in samples to apply to the audio
int64_t Delay = 0;
// cache of decoded audio blocks
std::list<AudioBlock> Cache;
// max size of the cache in blocks
size_t MaxCacheBlocks = 50;
// pointer to last element of the cache which should never be deleted
CacheIterator CacheNoDelete;
// bytes per sample * number of channels, *after* resampling if applicable
size_t BytesPerSample = 0;
bool NeedsResample = false;
struct SwrFreeWrapper {
void operator()(SwrContext *c) const {
swr_free(&c);
}
};
typedef std::unique_ptr<SwrContext, SwrFreeWrapper> FFResampleContext;
FFResampleContext ResampleContext;
// Insert the current audio frame into the cache
AudioBlock *CacheBlock(CacheIterator &pos);
// Interleave the current audio frame and insert it into the cache
void ResampleAndCache(CacheIterator pos);
// Cache the unseekable beginning of the file once the output format is set
void CacheBeginning();
// Called after seeking
void Seek();
// Read the next packet from the file
bool ReadPacket(AVPacket *);
// Close and reopen the source file to seek back to the beginning. Only
// needs to do anything for formats that can't seek to the beginning otherwise.
//
// If the file is not already open, it is merely just opened.
void OpenFile();
// First sample which is stored in the decoding buffer
int64_t CurrentSample = -1;
// Next packet to be read
size_t PacketNumber = 0;
// Current audio frame
const FrameInfo *CurrentFrame = nullptr;
// Track which this corresponds to
int TrackNumber;
// Number of packets which the demuxer requires to know where it is
// If -1, seeking is assumed to be impossible
int SeekOffset = 0;
// Buffer which audio is decoded into
AVFrame *DecodeFrame = nullptr;
FFMS_Track Frames;
AVCodecContext *CodecContext = nullptr;
FFMS_AudioProperties AP = {};
int DecodeNextBlock(CacheIterator *cachePos = 0);
// Initialization which has to be done after the codec is opened
void Init(const FFMS_Index &Index, int DelayMode);
int64_t FrameTS(size_t Packet) const;
void Free();
public:
FFMS_AudioSource(const char *SourceFile, FFMS_Index &Index, int Track, int DelayMode);
~FFMS_AudioSource();
FFMS_Track *GetTrack() { return &Frames; }
const FFMS_AudioProperties& GetAudioProperties() const { return AP; }
void GetAudio(void *Buf, int64_t Start, int64_t Count);
std::unique_ptr<FFMS_ResampleOptions> CreateResampleOptions() const;
void SetOutputFormat(FFMS_ResampleOptions const& opt);
static size_t GetSeekablePacketNumber(FFMS_Track const& Frames, size_t PacketNumber);
};
#endif

431
ffms2/src/core/ffms.cpp Normal file
View file

@ -0,0 +1,431 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "ffms.h"
#include "audiosource.h"
#include "indexing.h"
#include "videosource.h"
#include "videoutils.h"
extern "C" {
#include <libavutil/avutil.h>
#include <libavutil/pixdesc.h>
}
#include <mutex>
#include <sstream>
#include <iomanip>
#ifdef FFMS_WIN_DEBUG
# include <windows.h>
#endif
static std::once_flag FFmpegOnce;
static std::mutex FFmpegNetwork;
static bool FFmpegNetworkInited = false;
#ifdef FFMS_WIN_DEBUG
static void av_log_windebug_callback(void* ptr, int level, const char* fmt, va_list vl) {
if (level > av_log_get_level())
return;
static int print_prefix = 1;
static int count;
static char line[1024] = {}, prev[1024] = {};
auto avc = ptr ? *static_cast<AVClass **>(ptr) : nullptr;
int written = 0;
if (print_prefix && avc) {
written = snprintf(line, sizeof(line), "[%s @ %p]", avc->item_name(ptr), ptr);
}
written += vsnprintf(line + written, sizeof(line) - written, fmt, vl);
print_prefix = line[written - 1] == '\n';
line[sizeof(line) - 1] = 0;
if (print_prefix && !strcmp(line, prev)) {
count++;
return;
}
if (count > 0) {
std::stringstream ss;
ss << " Last message repeated " << count << " times\n";
OutputDebugStringA(ss.str().c_str());
count = 0;
}
OutputDebugStringA(line);
strcpy(prev, line);
}
#endif
FFMS_API(void) FFMS_Init(int, int) {
std::call_once(FFmpegOnce, []() {
FFMS_REGISTER();
#ifdef FFMS_WIN_DEBUG
av_log_set_callback(av_log_windebug_callback);
av_log_set_level(AV_LOG_INFO);
#else
av_log_set_level(AV_LOG_QUIET);
#endif
});
FFmpegNetwork.lock();
if (!FFmpegNetworkInited) {
avformat_network_init();
FFmpegNetworkInited = true;
}
FFmpegNetwork.unlock();
}
FFMS_API(void) FFMS_Deinit() {
FFmpegNetwork.lock();
if (FFmpegNetworkInited) {
avformat_network_deinit();
FFmpegNetworkInited = false;
}
FFmpegNetwork.unlock();
}
FFMS_API(int) FFMS_GetVersion() {
return FFMS_VERSION;
}
FFMS_API(int) FFMS_GetLogLevel() {
return av_log_get_level();
}
FFMS_API(void) FFMS_SetLogLevel(int Level) {
av_log_set_level(Level);
}
FFMS_API(FFMS_VideoSource *) FFMS_CreateVideoSource(const char *SourceFile, int Track, FFMS_Index *Index, int Threads, int SeekMode, FFMS_ErrorInfo *ErrorInfo) {
try {
return new FFMS_VideoSource(SourceFile, *Index, Track, Threads, SeekMode);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(FFMS_AudioSource *) FFMS_CreateAudioSource(const char *SourceFile, int Track, FFMS_Index *Index, int DelayMode, FFMS_ErrorInfo *ErrorInfo) {
try {
return new FFMS_AudioSource(SourceFile, *Index, Track, DelayMode);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(void) FFMS_DestroyVideoSource(FFMS_VideoSource *V) {
delete V;
}
FFMS_API(void) FFMS_DestroyAudioSource(FFMS_AudioSource *A) {
delete A;
}
FFMS_API(const FFMS_VideoProperties *) FFMS_GetVideoProperties(FFMS_VideoSource *V) {
return &V->GetVideoProperties();
}
FFMS_API(const FFMS_AudioProperties *) FFMS_GetAudioProperties(FFMS_AudioSource *A) {
return &A->GetAudioProperties();
}
FFMS_API(const FFMS_Frame *) FFMS_GetFrame(FFMS_VideoSource *V, int n, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
return V->GetFrame(n);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(const FFMS_Frame *) FFMS_GetFrameByTime(FFMS_VideoSource *V, double Time, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
return V->GetFrameByTime(Time);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(int) FFMS_GetAudio(FFMS_AudioSource *A, void *Buf, int64_t Start, int64_t Count, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
A->GetAudio(Buf, Start, Count);
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(int) FFMS_SetOutputFormatV2(FFMS_VideoSource *V, const int *TargetFormats, int Width, int Height, int Resizer, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
V->SetOutputFormat(reinterpret_cast<const AVPixelFormat *>(TargetFormats), Width, Height, Resizer);
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(void) FFMS_ResetOutputFormatV(FFMS_VideoSource *V) {
V->ResetOutputFormat();
}
FFMS_API(int) FFMS_SetInputFormatV(FFMS_VideoSource *V, int ColorSpace, int ColorRange, int Format, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
V->SetInputFormat(ColorSpace, ColorRange, static_cast<AVPixelFormat>(Format));
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(void) FFMS_ResetInputFormatV(FFMS_VideoSource *V) {
V->ResetInputFormat();
}
FFMS_API(FFMS_ResampleOptions *) FFMS_CreateResampleOptions(FFMS_AudioSource *A) {
return A->CreateResampleOptions().release();
}
FFMS_API(void) FFMS_DestroyResampleOptions(FFMS_ResampleOptions *options) {
delete options;
}
FFMS_API(int) FFMS_SetOutputFormatA(FFMS_AudioSource *A, const FFMS_ResampleOptions *options, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
A->SetOutputFormat(*options);
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(void) FFMS_DestroyIndex(FFMS_Index *Index) {
delete Index;
}
FFMS_API(FFMS_IndexErrorHandling) FFMS_GetErrorHandling(FFMS_Index *Index) {
return static_cast<FFMS_IndexErrorHandling>(Index->ErrorHandling);
}
FFMS_API(int) FFMS_GetFirstTrackOfType(FFMS_Index *Index, int TrackType, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
for (int i = 0; i < static_cast<int>(Index->size()); i++)
if ((*Index)[i].TT == TrackType)
return i;
try {
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_NOT_AVAILABLE,
"No suitable, indexed track found");
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return -1;
}
}
FFMS_API(int) FFMS_GetFirstIndexedTrackOfType(FFMS_Index *Index, int TrackType, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
for (int i = 0; i < static_cast<int>(Index->size()); i++)
if ((*Index)[i].TT == TrackType && !(*Index)[i].empty())
return i;
try {
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_NOT_AVAILABLE,
"No suitable, indexed track found");
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return -1;
}
}
FFMS_API(int) FFMS_GetNumTracks(FFMS_Index *Index) {
return static_cast<int>(Index->size());
}
FFMS_API(int) FFMS_GetNumTracksI(FFMS_Indexer *Indexer) {
return Indexer->GetNumberOfTracks();
}
FFMS_API(int) FFMS_GetTrackType(FFMS_Track *T) {
return T->TT;
}
FFMS_API(int) FFMS_GetTrackTypeI(FFMS_Indexer *Indexer, int Track) {
return Indexer->GetTrackType(Track);
}
FFMS_API(const char *) FFMS_GetCodecNameI(FFMS_Indexer *Indexer, int Track) {
return Indexer->GetTrackCodec(Track);
}
FFMS_API(int) FFMS_GetNumFrames(FFMS_Track *T) {
return T->VisibleFrameCount();
}
FFMS_API(const FFMS_FrameInfo *) FFMS_GetFrameInfo(FFMS_Track *T, int Frame) {
return T->GetFrameInfo(static_cast<size_t>(Frame));
}
FFMS_API(FFMS_Track *) FFMS_GetTrackFromIndex(FFMS_Index *Index, int Track) {
return &(*Index)[Track];
}
FFMS_API(FFMS_Track *) FFMS_GetTrackFromVideo(FFMS_VideoSource *V) {
return V->GetTrack();
}
FFMS_API(FFMS_Track *) FFMS_GetTrackFromAudio(FFMS_AudioSource *A) {
return A->GetTrack();
}
FFMS_API(const FFMS_TrackTimeBase *) FFMS_GetTimeBase(FFMS_Track *T) {
return &T->TB;
}
FFMS_API(int) FFMS_WriteTimecodes(FFMS_Track *T, const char *TimecodeFile, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
T->WriteTimecodes(TimecodeFile);
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(FFMS_Indexer *) FFMS_CreateIndexer(const char *SourceFile, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
return new FFMS_Indexer(SourceFile);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(FFMS_Index *) FFMS_DoIndexing2(FFMS_Indexer *Indexer, int ErrorHandling, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
Indexer->SetErrorHandling(ErrorHandling);
FFMS_Index *Index = nullptr;
try {
Index = Indexer->DoIndexing();
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
}
delete Indexer;
return Index;
}
FFMS_API(void) FFMS_TrackIndexSettings(FFMS_Indexer *Indexer, int Track, int Index, int) {
Indexer->SetIndexTrack(Track, !!Index);
}
FFMS_API(void) FFMS_TrackTypeIndexSettings(FFMS_Indexer *Indexer, int TrackType, int Index, int) {
Indexer->SetIndexTrackType(TrackType, !!Index);
}
FFMS_API(void) FFMS_SetProgressCallback(FFMS_Indexer *Indexer, TIndexCallback IC, void *ICPrivate) {
Indexer->SetProgressCallback(IC, ICPrivate);
}
FFMS_API(void) FFMS_CancelIndexing(FFMS_Indexer *Indexer) {
delete Indexer;
}
FFMS_API(FFMS_Index *) FFMS_ReadIndex(const char *IndexFile, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
return new FFMS_Index(IndexFile);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(FFMS_Index *) FFMS_ReadIndexFromBuffer(const uint8_t *Buffer, size_t Size, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
return new FFMS_Index(Buffer, Size);
} catch (FFMS_Exception &e) {
e.CopyOut(ErrorInfo);
return nullptr;
}
}
FFMS_API(int) FFMS_IndexBelongsToFile(FFMS_Index *Index, const char *SourceFile, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
if (!Index->CompareFileSignature(SourceFile))
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_FILE_MISMATCH,
"The index does not belong to the file");
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(int) FFMS_WriteIndex(const char *IndexFile, FFMS_Index *Index, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
try {
Index->WriteIndexFile(IndexFile);
} catch (FFMS_Exception &e) {
return e.CopyOut(ErrorInfo);
}
return FFMS_ERROR_SUCCESS;
}
FFMS_API(int) FFMS_WriteIndexToBuffer(uint8_t **BufferPtr, size_t *Size, FFMS_Index *Index, FFMS_ErrorInfo *ErrorInfo) {
ClearErrorInfo(ErrorInfo);
uint8_t *buf;
try {
buf = Index->WriteIndexBuffer(Size);
} catch (FFMS_Exception &e) {
*Size = 0;
*BufferPtr = nullptr;
return e.CopyOut(ErrorInfo);
}
*BufferPtr = buf;
return FFMS_ERROR_SUCCESS;
}
FFMS_API(void) FFMS_FreeIndexBuffer(uint8_t **BufferPtr) {
av_freep(BufferPtr);
}
FFMS_API(int) FFMS_GetPixFmt(const char *Name) {
return av_get_pix_fmt(Name);
}
FFMS_API(const char *) FFMS_GetFormatNameI(FFMS_Indexer *Indexer) {
return Indexer->GetFormatName();
}

View file

@ -0,0 +1,118 @@
// Copyright (c) 2014 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "filehandle.h"
#include "utils.h"
#include <cstdarg>
extern "C" {
#include <libavformat/avio.h>
}
static AVIOContext *ffms_fopen(const char *filename, const char *mode) {
int flags = 0;
if (strchr(mode, 'r'))
flags |= AVIO_FLAG_READ;
if (strchr(mode, 'w'))
flags |= AVIO_FLAG_WRITE;
AVIOContext *ctx;
int ret = avio_open2(&ctx, filename, flags, nullptr, nullptr);
if (ret < 0)
return nullptr;
return ctx;
}
FileHandle::FileHandle(const char *filename, const char *mode, int error_source, int error_cause)
: avio(ffms_fopen(filename, mode))
, filename(filename)
, error_source(error_source)
, error_cause(error_cause) {
if (!avio)
throw FFMS_Exception(error_source, FFMS_ERROR_NO_FILE,
"Failed to open '" + this->filename + "'");
}
FileHandle::~FileHandle() {
avio_close(avio);
}
void FileHandle::Seek(int64_t offset, int origin) {
int64_t ret = avio_seek(avio, offset, origin);
if (ret < 0)
throw FFMS_Exception(error_source, error_cause,
"Failed to seek in '" + filename + "'");
}
int64_t FileHandle::Tell() {
int64_t ret = avio_tell(avio);
if (ret < 0)
throw FFMS_Exception(error_source, error_cause,
"Failed to read position in '" + filename + "'");
return ret;
}
size_t FileHandle::Read(char *buffer, size_t size) {
int count = avio_read(avio, (unsigned char *)buffer, size);
if (count < 0)
throw FFMS_Exception(error_source, FFMS_ERROR_FILE_READ,
"Failed to read from '" + filename + "'");
return (size_t)count;
}
size_t FileHandle::Write(const char *buffer, size_t size) {
avio_write(avio, (const unsigned char *)buffer, size);
avio_flush(avio);
if (avio->error < 0)
throw FFMS_Exception(error_source, FFMS_ERROR_FILE_WRITE,
"Failed to write to '" + filename + "'");
return size;
}
int64_t FileHandle::Size() {
int64_t size = avio_size(avio);
if (size < 0)
throw FFMS_Exception(error_source, FFMS_ERROR_FILE_READ,
"Failed to get file size for '" + filename + "'");
return size;
}
int FileHandle::Printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
std::vector<char> OutBuffer(100);
int ret = -1;
while (OutBuffer.size() < 1024 * 1024) {
ret = vsnprintf(OutBuffer.data(), OutBuffer.size(), fmt, args);
if (ret > 0 && ret < (int)OutBuffer.size())
break;
OutBuffer.resize(OutBuffer.size() * 2);
}
va_end(args);
avio_write(avio, reinterpret_cast<const unsigned char *>(OutBuffer.data()), ret);
avio_flush(avio);
return avio->error < 0 ? avio->error : ret;
}

View file

@ -0,0 +1,50 @@
// Copyright (c) 2014 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <cstdint>
#include <string>
struct AVIOContext;
class FileHandle {
AVIOContext *avio;
std::string filename;
int error_source;
int error_cause;
public:
FileHandle(const char *filename, const char *mode, int error_source, int error_cause);
FileHandle() : avio(nullptr) {}
~FileHandle();
void Seek(int64_t offset, int origin);
int64_t Tell();
int64_t Size();
size_t Read(char *buffer, size_t size);
size_t Write(const char *buffer, size_t size);
int Printf(const char *fmt, ...)
#ifdef __GNUC__
__attribute__((format(printf, 2, 3)))
#endif
;
};

549
ffms2/src/core/indexing.cpp Normal file
View file

@ -0,0 +1,549 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "indexing.h"
#include "track.h"
#include "videoutils.h"
#include "zipfile.h"
#include <algorithm>
#include <limits>
#include <numeric>
#include <sstream>
extern "C" {
#include <libavutil/avutil.h>
#include <libavutil/sha.h>
}
#define INDEXID 0x53920873
#define INDEX_VERSION 5
SharedAVContext::~SharedAVContext() {
avcodec_free_context(&CodecContext);
if (Parser)
av_parser_close(Parser);
}
void FFMS_Index::CalculateFileSignature(const char *Filename, int64_t *Filesize, uint8_t Digest[20]) {
FileHandle file(Filename, "rb", FFMS_ERROR_INDEX, FFMS_ERROR_FILE_READ);
std::unique_ptr<AVSHA, decltype(&av_free)> ctx{ av_sha_alloc(), av_free };
av_sha_init(ctx.get(), 160);
try {
*Filesize = file.Size();
std::vector<char> FileBuffer(static_cast<size_t>(std::min<int64_t>(1024 * 1024, *Filesize)));
size_t BytesRead = file.Read(FileBuffer.data(), FileBuffer.size());
av_sha_update(ctx.get(), reinterpret_cast<const uint8_t*>(FileBuffer.data()), BytesRead);
if (*Filesize > static_cast<int64_t>(FileBuffer.size())) {
file.Seek(*Filesize - static_cast<int64_t>(FileBuffer.size()), SEEK_SET);
BytesRead = file.Read(FileBuffer.data(), FileBuffer.size());
av_sha_update(ctx.get(), reinterpret_cast<const uint8_t*>(FileBuffer.data()), BytesRead);
}
} catch (...) {
av_sha_final(ctx.get(), Digest);
throw;
}
av_sha_final(ctx.get(), Digest);
}
void FFMS_Index::Finalize(std::vector<SharedAVContext> const& video_contexts, const char *Format) {
for (size_t i = 0, end = size(); i != end; ++i) {
FFMS_Track& track = (*this)[i];
// H.264 PAFF needs to have some frames hidden
//
// Don't send any WMV/ASF files, since they (as far as we know) cannot contain PAFF,
// but may also have valid, split packets, with pos equal to the previous pos.
if (video_contexts[i].CodecContext && video_contexts[i].CodecContext->codec_id == AV_CODEC_ID_H264 && !!strcmp(Format, "asf"))
track.MaybeHideFrames();
track.FinalizeTrack();
if (track.TT != FFMS_TYPE_VIDEO) continue;
if (video_contexts[i].CodecContext && video_contexts[i].CodecContext->has_b_frames) {
track.MaxBFrames = video_contexts[i].CodecContext->has_b_frames;
continue;
}
// Whether or not has_b_frames gets set during indexing seems
// to vary based on version of FFmpeg/Libav, so do an extra
// check for b-frames if it's 0.
for (size_t f = 0; f < track.size(); ++f) {
if (track[f].FrameType == AV_PICTURE_TYPE_B) {
track.MaxBFrames = 1;
break;
}
}
}
}
bool FFMS_Index::CompareFileSignature(const char *Filename) {
int64_t CFilesize;
uint8_t CDigest[20];
CalculateFileSignature(Filename, &CFilesize, CDigest);
return (CFilesize == Filesize && !memcmp(CDigest, Digest, sizeof(Digest)));
}
void FFMS_Index::WriteIndex(ZipFile &zf) {
// Write the index file header
zf.Write<uint32_t>(INDEXID);
zf.Write<uint32_t>(FFMS_VERSION);
zf.Write<uint16_t>(INDEX_VERSION);
zf.Write<uint32_t>(size());
zf.Write<uint32_t>(ErrorHandling);
zf.Write<uint32_t>(avutil_version());
zf.Write<uint32_t>(avformat_version());
zf.Write<uint32_t>(avcodec_version());
zf.Write<uint32_t>(swscale_version());
zf.Write<int64_t>(Filesize);
zf.Write(Digest);
for (size_t i = 0; i < size(); ++i)
at(i).Write(zf);
zf.Finish();
}
void FFMS_Index::WriteIndexFile(const char *IndexFile) {
ZipFile zf(IndexFile, "wb");
WriteIndex(zf);
}
uint8_t *FFMS_Index::WriteIndexBuffer(size_t *Size) {
ZipFile zf;
WriteIndex(zf);
return zf.GetBuffer(Size);
}
void FFMS_Index::ReadIndex(ZipFile &zf, const char *IndexFile) {
// Read the index file header
if (zf.Read<uint32_t>() != INDEXID)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("'") + IndexFile + "' is not a valid index file");
if (zf.Read<uint32_t>() != FFMS_VERSION)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("'") + IndexFile + "' was not created with the expected FFMS2 version");
if (zf.Read<uint16_t>() != INDEX_VERSION)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("'") + IndexFile + "' is not the expected index version");
uint32_t Tracks = zf.Read<uint32_t>();
ErrorHandling = zf.Read<uint32_t>();
if (zf.Read<uint32_t>() != avutil_version() ||
zf.Read<uint32_t>() != avformat_version() ||
zf.Read<uint32_t>() != avcodec_version() ||
zf.Read<uint32_t>() != swscale_version())
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("A different FFmpeg build was used to create '") + IndexFile + "'");
Filesize = zf.Read<int64_t>();
zf.Read(Digest, sizeof(Digest));
reserve(Tracks);
try {
for (size_t i = 0; i < Tracks; ++i)
emplace_back(zf);
} catch (FFMS_Exception const&) {
throw;
} catch (...) {
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("Unknown error while reading index information in '") + IndexFile + "'");
}
}
FFMS_Index::FFMS_Index(const char *IndexFile) {
ZipFile zf(IndexFile, "rb");
ReadIndex(zf, IndexFile);
}
FFMS_Index::FFMS_Index(const uint8_t *Buffer, size_t Size) {
ZipFile zf(Buffer, Size);
ReadIndex(zf, "User supplied buffer");
}
FFMS_Index::FFMS_Index(int64_t Filesize, uint8_t Digest[20], int ErrorHandling)
: ErrorHandling(ErrorHandling)
, Filesize(Filesize) {
memcpy(this->Digest, Digest, sizeof(this->Digest));
}
void FFMS_Indexer::SetIndexTrack(int Track, bool Index) {
if (Track < 0 || Track >= GetNumberOfTracks())
return;
if (Index)
IndexMask.insert(Track);
else
IndexMask.erase(Track);
};
void FFMS_Indexer::SetIndexTrackType(int TrackType, bool Index) {
for (int i = 0; i < GetNumberOfTracks(); i++) {
if (GetTrackType(i) == TrackType) {
if (Index)
IndexMask.insert(i);
else
IndexMask.erase(i);
}
}
}
void FFMS_Indexer::SetErrorHandling(int ErrorHandling_) {
if (ErrorHandling_ != FFMS_IEH_ABORT && ErrorHandling_ != FFMS_IEH_CLEAR_TRACK &&
ErrorHandling_ != FFMS_IEH_STOP_TRACK && ErrorHandling_ != FFMS_IEH_IGNORE)
throw FFMS_Exception(FFMS_ERROR_INDEXING, FFMS_ERROR_INVALID_ARGUMENT,
"Invalid error handling mode specified");
ErrorHandling = ErrorHandling_;
}
void FFMS_Indexer::SetProgressCallback(TIndexCallback IC_, void *ICPrivate_) {
IC = IC_;
ICPrivate = ICPrivate_;
}
FFMS_Indexer *CreateIndexer(const char *Filename) {
return new FFMS_Indexer(Filename);
}
FFMS_Indexer::FFMS_Indexer(const char *Filename)
: SourceFile(Filename) {
try {
if (avformat_open_input(&FormatContext, Filename, nullptr, nullptr) != 0)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("Can't open '") + Filename + "'");
FFMS_Index::CalculateFileSignature(Filename, &Filesize, Digest);
if (avformat_find_stream_info(FormatContext, nullptr) < 0) {
avformat_close_input(&FormatContext);
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
"Couldn't find stream information");
}
for (unsigned int i = 0; i < FormatContext->nb_streams; i++)
if (FormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
IndexMask.insert(i);
DecodeFrame = av_frame_alloc();
if (!DecodeFrame)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Couldn't allocate frame");
} catch (...) {
Free();
throw;
}
}
uint32_t FFMS_Indexer::IndexAudioPacket(int Track, AVPacket *Packet, SharedAVContext &Context, FFMS_Index &TrackIndices) {
AVCodecContext *CodecContext = Context.CodecContext;
int64_t StartSample = Context.CurrentSample;
int Ret = avcodec_send_packet(CodecContext, Packet);
if (Ret != 0) {
if (ErrorHandling == FFMS_IEH_ABORT) {
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, "Audio decoding error");
} else if (ErrorHandling == FFMS_IEH_CLEAR_TRACK) {
TrackIndices[Track].clear();
IndexMask.erase(Track);
} else if (ErrorHandling == FFMS_IEH_STOP_TRACK) {
IndexMask.erase(Track);
}
}
while (true) {
av_frame_unref(DecodeFrame);
Ret = avcodec_receive_frame(CodecContext, DecodeFrame);
if (Ret == 0) {
CheckAudioProperties(Track, CodecContext);
Context.CurrentSample += DecodeFrame->nb_samples;
} else if (Ret == AVERROR_EOF || Ret == AVERROR(EAGAIN)) {
break;
} else {
if (ErrorHandling == FFMS_IEH_ABORT) {
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING, "Audio decoding error");
} else if (ErrorHandling == FFMS_IEH_CLEAR_TRACK) {
TrackIndices[Track].clear();
IndexMask.erase(Track);
} else if (ErrorHandling == FFMS_IEH_STOP_TRACK) {
IndexMask.erase(Track);
}
}
}
return static_cast<uint32_t>(Context.CurrentSample - StartSample);
}
void FFMS_Indexer::CheckAudioProperties(int Track, AVCodecContext *Context) {
auto it = LastAudioProperties.find(Track);
if (it == LastAudioProperties.end()) {
FFMS_AudioProperties &AP = LastAudioProperties[Track];
AP.SampleRate = Context->sample_rate;
AP.SampleFormat = Context->sample_fmt;
AP.Channels = Context->channels;
} else if (it->second.SampleRate != Context->sample_rate ||
it->second.SampleFormat != Context->sample_fmt ||
it->second.Channels != Context->channels) {
std::ostringstream buf;
buf <<
"Audio format change detected. This is currently unsupported."
<< " Channels: " << it->second.Channels << " -> " << Context->channels << ";"
<< " Sample rate: " << it->second.SampleRate << " -> " << Context->sample_rate << ";"
<< " Sample format: " << av_get_sample_fmt_name((AVSampleFormat)it->second.SampleFormat) << " -> "
<< av_get_sample_fmt_name(Context->sample_fmt);
throw FFMS_Exception(FFMS_ERROR_UNSUPPORTED, FFMS_ERROR_DECODING, buf.str());
}
}
void FFMS_Indexer::ParseVideoPacket(SharedAVContext &VideoContext, AVPacket &pkt, int *RepeatPict,
int *FrameType, bool *Invisible, enum AVPictureStructure *LastPicStruct) {
if (VideoContext.Parser) {
uint8_t *OB;
int OBSize;
bool IncompleteFrame = false;
av_parser_parse2(VideoContext.Parser,
VideoContext.CodecContext,
&OB, &OBSize,
pkt.data, pkt.size,
pkt.pts, pkt.dts, pkt.pos);
// H.264 (PAFF) and HEVC may have one field per packet, so we need to track
// when we have a full or half frame available, and mark one of them as
// hidden, so we do not get duplicate frames.
if (VideoContext.CodecContext->codec_id == AV_CODEC_ID_H264 ||
VideoContext.CodecContext->codec_id == AV_CODEC_ID_HEVC) {
if ((VideoContext.Parser->picture_structure == AV_PICTURE_STRUCTURE_TOP_FIELD &&
*LastPicStruct == AV_PICTURE_STRUCTURE_BOTTOM_FIELD) ||
(VideoContext.Parser->picture_structure == AV_PICTURE_STRUCTURE_BOTTOM_FIELD &&
*LastPicStruct == AV_PICTURE_STRUCTURE_TOP_FIELD)) {
IncompleteFrame = true;
*LastPicStruct = AV_PICTURE_STRUCTURE_UNKNOWN;
} else {
*LastPicStruct = VideoContext.Parser->picture_structure;
}
}
*RepeatPict = VideoContext.Parser->repeat_pict;
*FrameType = VideoContext.Parser->pict_type;
*Invisible = (IncompleteFrame || VideoContext.Parser->repeat_pict < 0 || (pkt.flags & AV_PKT_FLAG_DISCARD));
} else {
*Invisible = !!(pkt.flags & AV_PKT_FLAG_DISCARD);
}
if (VideoContext.CodecContext->codec_id == AV_CODEC_ID_VP8)
ParseVP8(pkt.data[0], Invisible, FrameType);
else if (VideoContext.CodecContext->codec_id == AV_CODEC_ID_VP9)
ParseVP9(pkt.data[0], Invisible, FrameType);
}
void FFMS_Indexer::Free() {
av_frame_free(&DecodeFrame);
avformat_close_input(&FormatContext);
}
FFMS_Indexer::~FFMS_Indexer() {
Free();
}
int FFMS_Indexer::GetNumberOfTracks() {
return FormatContext->nb_streams;
}
const char *FFMS_Indexer::GetFormatName() {
return FormatContext->iformat->name;
}
FFMS_TrackType FFMS_Indexer::GetTrackType(int Track) {
return static_cast<FFMS_TrackType>(FormatContext->streams[Track]->codecpar->codec_type);
}
const char *FFMS_Indexer::GetTrackCodec(int Track) {
AVCodec *codec = avcodec_find_decoder(FormatContext->streams[Track]->codecpar->codec_id);
return codec ? codec->name : nullptr;
}
FFMS_Index *FFMS_Indexer::DoIndexing() {
std::vector<SharedAVContext> AVContexts(FormatContext->nb_streams);
auto TrackIndices = make_unique<FFMS_Index>(Filesize, Digest, ErrorHandling);
bool UseDTS = !strcmp(FormatContext->iformat->name, "mpeg") || !strcmp(FormatContext->iformat->name, "mpegts") || !strcmp(FormatContext->iformat->name, "mpegtsraw") || !strcmp(FormatContext->iformat->name, "nuv");
for (unsigned int i = 0; i < FormatContext->nb_streams; i++) {
TrackIndices->emplace_back((int64_t)FormatContext->streams[i]->time_base.num * 1000,
FormatContext->streams[i]->time_base.den,
static_cast<FFMS_TrackType>(FormatContext->streams[i]->codecpar->codec_type),
!!(FormatContext->iformat->flags & AVFMT_TS_DISCONT),
UseDTS);
if (IndexMask.count(i) && FormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
AVCodec *VideoCodec = avcodec_find_decoder(FormatContext->streams[i]->codecpar->codec_id);
if (!VideoCodec) {
FormatContext->streams[i]->discard = AVDISCARD_ALL;
IndexMask.erase(i);
continue;
}
AVContexts[i].CodecContext = avcodec_alloc_context3(VideoCodec);
if (AVContexts[i].CodecContext == nullptr)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate video codec context");
if (avcodec_parameters_to_context(AVContexts[i].CodecContext, FormatContext->streams[i]->codecpar) < 0)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING,
"Could not copy video codec parameters");
if (avcodec_open2(AVContexts[i].CodecContext, VideoCodec, nullptr) < 0)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING,
"Could not open video codec");
AVContexts[i].Parser = av_parser_init(FormatContext->streams[i]->codecpar->codec_id);
if (AVContexts[i].Parser)
AVContexts[i].Parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
if (FormatContext->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC) {
FormatContext->streams[i]->discard = AVDISCARD_ALL;
IndexMask.erase(i);
} else {
IndexMask.insert(i);
}
} else if (IndexMask.count(i) && FormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
AVCodec *AudioCodec = avcodec_find_decoder(FormatContext->streams[i]->codecpar->codec_id);
if (AudioCodec == nullptr)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_UNSUPPORTED,
"Audio codec not found");
AVContexts[i].CodecContext = avcodec_alloc_context3(AudioCodec);
if (AVContexts[i].CodecContext == nullptr)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate audio codec context");
if (avcodec_parameters_to_context(AVContexts[i].CodecContext, FormatContext->streams[i]->codecpar) < 0)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING,
"Could not copy audio codec parameters");
if (avcodec_open2(AVContexts[i].CodecContext, AudioCodec, nullptr) < 0)
throw FFMS_Exception(FFMS_ERROR_CODEC, FFMS_ERROR_DECODING,
"Could not open audio codec");
(*TrackIndices)[i].HasTS = false;
} else {
FormatContext->streams[i]->discard = AVDISCARD_ALL;
IndexMask.erase(i);
}
}
AVPacket Packet;
InitNullPacket(Packet);
std::vector<int64_t> LastValidTS(FormatContext->nb_streams, AV_NOPTS_VALUE);
int64_t filesize = avio_size(FormatContext->pb);
enum AVPictureStructure LastPicStruct = AV_PICTURE_STRUCTURE_UNKNOWN;
while (av_read_frame(FormatContext, &Packet) >= 0) {
// Update progress
// FormatContext->pb can apparently be NULL when opening images.
if (IC && FormatContext->pb) {
if ((*IC)(FormatContext->pb->pos, filesize, ICPrivate))
throw FFMS_Exception(FFMS_ERROR_CANCELLED, FFMS_ERROR_USER,
"Cancelled by user");
}
if (!IndexMask.count(Packet.stream_index)) {
av_packet_unref(&Packet);
continue;
}
int Track = Packet.stream_index;
FFMS_Track &TrackInfo = (*TrackIndices)[Track];
bool KeyFrame = !!(Packet.flags & AV_PKT_FLAG_KEY);
ReadTS(Packet, LastValidTS[Track], (*TrackIndices)[Track].UseDTS);
if (FormatContext->streams[Track]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
int64_t PTS = TrackInfo.UseDTS ? Packet.dts : Packet.pts;
if (PTS == AV_NOPTS_VALUE) {
// VPx alt-refs are output as packets which lack timestmps or durations, since
// they are invisible. Currently, the timestamp mangling code in libavformat
// will sometimes add a bogus timestamp and duration, if the webm in question
// has the block duration set (which is a hack, and not really a frame duration
// at all). In the future, libav* will only output packets without timestamps
// or duration, so we need to handle it here, regardless. This does not handle
// NVOPs. We set the duration based on the last PTS, for these packets, because
// FFMS2 currently sorts packets by PTS, which will break decoding, otherwise.
bool HasAltRefs = (FormatContext->streams[Track]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
FormatContext->streams[Track]->codecpar->codec_id == AV_CODEC_ID_VP9);
if (Packet.duration == 0 && !HasAltRefs)
throw FFMS_Exception(FFMS_ERROR_INDEXING, FFMS_ERROR_PARSER,
"Invalid packet pts, dts, and duration");
if (TrackInfo.empty())
PTS = 0;
else
PTS = TrackInfo.back().PTS + TrackInfo.LastDuration;
TrackInfo.HasTS = false;
}
int RepeatPict = -1;
int FrameType = 0;
bool Invisible = false;
ParseVideoPacket(AVContexts[Track], Packet, &RepeatPict, &FrameType, &Invisible, &LastPicStruct);
TrackInfo.AddVideoFrame(PTS, RepeatPict, KeyFrame,
FrameType, Packet.pos, Invisible);
} else if (FormatContext->streams[Track]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
// For video seeking timestamps are used only if all packets have
// timestamps, while for audio they're used if any have timestamps,
// as it's pretty common for only some packets to have timestamps
if (LastValidTS[Track] != AV_NOPTS_VALUE)
TrackInfo.HasTS = true;
int64_t StartSample = AVContexts[Track].CurrentSample;
uint32_t SampleCount = IndexAudioPacket(Track, &Packet, AVContexts[Track], *TrackIndices);
TrackInfo.SampleRate = AVContexts[Track].CodecContext->sample_rate;
TrackInfo.AddAudioFrame(LastValidTS[Track],
StartSample, SampleCount, KeyFrame, Packet.pos, Packet.flags & AV_PKT_FLAG_DISCARD);
}
if (!(Packet.flags & AV_PKT_FLAG_DISCARD))
TrackInfo.LastDuration = Packet.duration;
av_packet_unref(&Packet);
}
TrackIndices->Finalize(AVContexts, FormatContext->iformat->name);
return TrackIndices.release();
}
void FFMS_Indexer::ReadTS(const AVPacket &Packet, int64_t &TS, bool &UseDTS) {
if (!UseDTS && Packet.pts != AV_NOPTS_VALUE)
TS = Packet.pts;
if (TS == AV_NOPTS_VALUE)
UseDTS = true;
if (UseDTS && Packet.dts != AV_NOPTS_VALUE)
TS = Packet.dts;
}

105
ffms2/src/core/indexing.h Normal file
View file

@ -0,0 +1,105 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef INDEXING_H
#define INDEXING_H
#include "utils.h"
#include <set>
#include <map>
#include <memory>
#include <atomic>
extern "C" {
#include <libavutil/avutil.h>
}
class Wave64Writer;
class ZipFile;
struct SharedAVContext {
AVCodecContext *CodecContext = nullptr;
AVCodecParserContext *Parser = nullptr;
int64_t CurrentSample = 0;
~SharedAVContext();
};
struct FFMS_Index : public std::vector<FFMS_Track> {
FFMS_Index(FFMS_Index const&) = delete;
FFMS_Index& operator=(FFMS_Index const&) = delete;
void ReadIndex(ZipFile &zf, const char* IndexFile);
void WriteIndex(ZipFile &zf);
public:
static void CalculateFileSignature(const char *Filename, int64_t *Filesize, uint8_t Digest[20]);
int ErrorHandling;
int64_t Filesize;
uint8_t Digest[20];
void Finalize(std::vector<SharedAVContext> const& video_contexts, const char *Format);
bool CompareFileSignature(const char *Filename);
void WriteIndexFile(const char *IndexFile);
uint8_t *WriteIndexBuffer(size_t *Size);
FFMS_Index(const char *IndexFile);
FFMS_Index(const uint8_t *Buffer, size_t Size);
FFMS_Index(int64_t Filesize, uint8_t Digest[20], int ErrorHandling);
};
struct FFMS_Indexer {
private:
std::map<int, FFMS_AudioProperties> LastAudioProperties;
FFMS_Indexer(FFMS_Indexer const&) = delete;
FFMS_Indexer& operator=(FFMS_Indexer const&) = delete;
AVFormatContext *FormatContext = nullptr;
std::set<int> IndexMask;
int ErrorHandling = FFMS_IEH_CLEAR_TRACK;
TIndexCallback IC = nullptr;
void *ICPrivate = nullptr;
std::string SourceFile;
AVFrame *DecodeFrame = nullptr;
int64_t Filesize;
uint8_t Digest[20];
void ReadTS(const AVPacket &Packet, int64_t &TS, bool &UseDTS);
void CheckAudioProperties(int Track, AVCodecContext *Context);
uint32_t IndexAudioPacket(int Track, AVPacket *Packet, SharedAVContext &Context, FFMS_Index &TrackIndices);
void ParseVideoPacket(SharedAVContext &VideoContext, AVPacket &pkt, int *RepeatPict, int *FrameType, bool *Invisible, enum AVPictureStructure *LastPicStruct);
void Free();
public:
FFMS_Indexer(const char *Filename);
~FFMS_Indexer();
void SetIndexTrack(int Track, bool Index);
void SetIndexTrackType(int TrackType, bool Index);
void SetErrorHandling(int ErrorHandling_);
void SetProgressCallback(TIndexCallback IC_, void *ICPrivate_);
FFMS_Index *DoIndexing();
int GetNumberOfTracks();
FFMS_TrackType GetTrackType(int Track);
const char *GetTrackCodec(int Track);
const char *GetFormatName();
};
#endif

414
ffms2/src/core/track.cpp Normal file
View file

@ -0,0 +1,414 @@
// Copyright (c) 2014 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "track.h"
#include "utils.h"
#include "zipfile.h"
#include "indexing.h"
#include <algorithm>
#include <cmath>
extern "C" {
#include <libavutil/avutil.h>
#include <libavutil/common.h>
#include <libavutil/mathematics.h>
}
namespace {
FrameInfo ReadFrame(ZipFile &stream, FrameInfo const& prev, const FFMS_TrackType TT) {
FrameInfo f{};
f.PTS = stream.Read<int64_t>() + prev.PTS;
f.OriginalPTS = stream.Read<int64_t>() + prev.OriginalPTS;
f.KeyFrame = !!stream.Read<int8_t>();
f.FilePos = stream.Read<int64_t>() + prev.FilePos;
f.Hidden = !!stream.Read<int8_t>();
if (TT == FFMS_TYPE_AUDIO) {
f.SampleStart = prev.SampleStart + prev.SampleCount;
f.SampleCount = stream.Read<uint32_t>() + prev.SampleCount;
} else if (TT == FFMS_TYPE_VIDEO) {
f.OriginalPos = static_cast<size_t>(stream.Read<uint64_t>() + prev.OriginalPos + 1);
f.RepeatPict = stream.Read<int32_t>();
}
return f;
}
static void WriteFrame(ZipFile &stream, FrameInfo const& f, FrameInfo const& prev, const FFMS_TrackType TT) {
stream.Write(f.PTS - prev.PTS);
stream.Write(f.OriginalPTS - prev.OriginalPTS);
stream.Write<int8_t>(f.KeyFrame);
stream.Write(f.FilePos - prev.FilePos);
stream.Write<uint8_t>(f.Hidden);
if (TT == FFMS_TYPE_AUDIO)
stream.Write(f.SampleCount - prev.SampleCount);
else if (TT == FFMS_TYPE_VIDEO) {
stream.Write(static_cast<uint64_t>(f.OriginalPos) - prev.OriginalPos - 1);
stream.Write<int32_t>(f.RepeatPict);
}
}
}
FFMS_Track::FFMS_Track()
: Data(std::make_shared<TrackData>())
{
}
FFMS_Track::FFMS_Track(int64_t Num, int64_t Den, FFMS_TrackType TT, bool HasDiscontTS, bool UseDTS, bool HasTS)
: Data(std::make_shared<TrackData>())
, TT(TT)
, UseDTS(UseDTS)
, HasTS(HasTS)
, HasDiscontTS(HasDiscontTS) {
TB.Num = Num;
TB.Den = Den;
}
FFMS_Track::FFMS_Track(ZipFile &stream)
: Data(std::make_shared<TrackData>()) {
frame_vec &Frames = Data->Frames;
TT = static_cast<FFMS_TrackType>(stream.Read<uint8_t>());
TB.Num = stream.Read<int64_t>();
TB.Den = stream.Read<int64_t>();
LastDuration = stream.Read<int64_t>();
MaxBFrames = stream.Read<int32_t>();
UseDTS = !!stream.Read<uint8_t>();
HasTS = !!stream.Read<uint8_t>();
size_t FrameCount = static_cast<size_t>(stream.Read<uint64_t>());
if (!FrameCount) return;
FrameInfo temp{};
Frames.reserve(FrameCount);
for (size_t i = 0; i < FrameCount; ++i)
Frames.push_back(ReadFrame(stream, i == 0 ? temp : Frames.back(), TT));
if (TT == FFMS_TYPE_VIDEO)
GeneratePublicInfo();
}
void FFMS_Track::Write(ZipFile &stream) const {
frame_vec &Frames = Data->Frames;
stream.Write<uint8_t>(TT);
stream.Write(TB.Num);
stream.Write(TB.Den);
stream.Write<int64_t>(LastDuration);
stream.Write<int32_t>(MaxBFrames);
stream.Write<uint8_t>(UseDTS);
stream.Write<uint8_t>(HasTS);
stream.Write<uint64_t>(size());
if (empty()) return;
FrameInfo temp{};
for (size_t i = 0; i < size(); ++i)
WriteFrame(stream, Frames[i], i == 0 ? temp : Frames[i - 1], TT);
}
void FFMS_Track::AddVideoFrame(int64_t PTS, int RepeatPict, bool KeyFrame, int FrameType, int64_t FilePos, bool Hidden) {
Data->Frames.push_back({ PTS, 0, FilePos, 0, 0, 0, FrameType, RepeatPict, KeyFrame, Hidden });
}
void FFMS_Track::AddAudioFrame(int64_t PTS, int64_t SampleStart, uint32_t SampleCount, bool KeyFrame, int64_t FilePos, bool Hidden) {
if (SampleCount > 0) {
Data->Frames.push_back({ PTS, 0, FilePos, SampleStart, SampleCount,
0, 0, 0, KeyFrame, Hidden });
}
}
void FFMS_Track::WriteTimecodes(const char *TimecodeFile) const {
frame_vec &Frames = Data->Frames;
FileHandle file(TimecodeFile, "w", FFMS_ERROR_TRACK, FFMS_ERROR_FILE_WRITE);
file.Printf("# timecode format v2\n");
for (size_t i = 0; i < size(); ++i) {
if (!Frames[i].Hidden)
file.Printf("%.02f\n", (Frames[i].PTS * TB.Num) / (double)TB.Den);
}
}
static bool PTSComparison(FrameInfo FI1, FrameInfo FI2) {
return FI1.PTS < FI2.PTS;
}
int FFMS_Track::FrameFromPTS(int64_t PTS) const {
FrameInfo F;
F.PTS = PTS;
auto Pos = std::lower_bound(begin(), end(), F, PTSComparison);
while (Pos != end() && Pos->Hidden && Pos->PTS == PTS)
Pos++;
if (Pos == end() || Pos->PTS != PTS)
return -1;
return std::distance(begin(), Pos);
}
int FFMS_Track::FrameFromPos(int64_t Pos) const {
for (size_t i = 0; i < size(); i++)
if (Data->Frames[i].FilePos == Pos && !Data->Frames[i].Hidden)
return static_cast<int>(i);
return -1;
}
int FFMS_Track::ClosestFrameFromPTS(int64_t PTS) const {
FrameInfo F;
F.PTS = PTS;
auto Pos = std::lower_bound(begin(), end(), F, PTSComparison);
while (Pos != end() && Pos->Hidden && Pos->PTS == PTS)
Pos++;
if (Pos == end())
return static_cast<int>(size() - 1);
size_t Frame = std::distance(begin(), Pos);
if (Pos == begin() || FFABS(Pos->PTS - PTS) <= FFABS((Pos - 1)->PTS - PTS))
return static_cast<int>(Frame);
return static_cast<int>(Frame - 1);
}
int FFMS_Track::FindClosestVideoKeyFrame(int Frame) const {
frame_vec &Frames = Data->Frames;
Frame = std::min(std::max(Frame, 0), static_cast<int>(size()) - 1);
for (; Frame > 0 && !Frames[Frame].KeyFrame; Frame--);
for (; Frame > 0 && !Frames[Frames[Frame].OriginalPos].KeyFrame; Frame--);
return Frame;
}
int FFMS_Track::RealFrameNumber(int Frame) const {
return Data->RealFrameNumbers[Frame];
}
int FFMS_Track::VisibleFrameCount() const {
return TT == FFMS_TYPE_AUDIO ? static_cast<int>(Data->Frames.size()) : static_cast<int>(Data->RealFrameNumbers.size());
}
void FFMS_Track::MaybeReorderFrames() {
frame_vec &Frames = Data->Frames;
// First check if we need to do anything
bool has_b_frames = false;
for (size_t i = 1; i < size(); ++i) {
// If the timestamps are already out of order, then they actually are
// presentation timestamps and we don't need to do anything
if (Frames[i].PTS < Frames[i - 1].PTS)
return;
if (Frames[i].FrameType == AV_PICTURE_TYPE_B) {
has_b_frames = true;
// Reordering files with multiple b-frames is currently not
// supported
if (Frames[i - 1].FrameType == AV_PICTURE_TYPE_B)
return;
}
}
// Don't need to do anything if there are no b-frames as presentation order
// equals decoding order
if (!has_b_frames)
return;
// We have b-frames, but the timestamps are monotonically increasing. This
// means that the timestamps we have are decoding timestamps, and we want
// presentation time stamps. Convert DTS to PTS by swapping the timestamp
// of each b-frame with the frame before it. This only works for the
// specific case of b-frames which reference the frame immediately after
// them temporally, but that happens to cover the only files I've seen
// with b-frames and no presentation timestamps.
for (size_t i = 1; i < size(); ++i) {
if (Frames[i].FrameType == AV_PICTURE_TYPE_B)
std::swap(Frames[i].PTS, Frames[i - 1].PTS);
}
}
void FFMS_Track::MaybeHideFrames() {
frame_vec &Frames = Data->Frames;
// Awful handling for interlaced H.264: each frame is output twice, so hide
// frames with an invalid file position. The PTS will not match sometimes,
// since libavformat makes up timestamps... but only sometimes.
for (size_t i = 1; i < size(); ++i) {
FrameInfo const& prev = Frames[i - 1];
FrameInfo& cur = Frames[i];
if (prev.FilePos >= 0 && (cur.FilePos == -1 || cur.FilePos == prev.FilePos) && !prev.Hidden)
cur.Hidden = true;
}
}
void FFMS_Track::FillAudioGaps() {
frame_vec &Frames = Data->Frames;
// There may not be audio data for the entire duration of the audio track,
// as some formats support gaps between the end time of one packet and the
// PTS of the next audio packet, and we should zero-fill those gaps.
// However, garbage or missing timestamps for audio tracks are very common,
// so we only want to trust them if they're all present, monotonically
// increasing, and result in a total duration meaningfully longer than the
// samples we have would cover.
if (size() < 2 || !HasTS || front().PTS == AV_NOPTS_VALUE || back().PTS == AV_NOPTS_VALUE)
return;
const auto DurationToSamples = [this](int64_t Dur) {
auto Num = TB.Num * SampleRate;
auto Den = TB.Den * 1000;
return av_rescale(Dur, Num, Den);
};
const auto SamplesToDuration = [this](int64_t Samples) {
auto Num = TB.Den * 1000;
auto Den = TB.Num * SampleRate;
return av_rescale(Samples, Num, Den);
};
if (HasDiscontTS) {
int64_t shift = 0;
Frames[0].OriginalPTS = Frames[0].PTS;
for (size_t i = 1; i < size(); i++) {
Frames[i].OriginalPTS = Frames[i].PTS;
if (Frames[i].PTS != AV_NOPTS_VALUE && Frames[i].OriginalPTS <= Frames[i-1].OriginalPTS)
shift = -(Frames[i].PTS) + Frames[i-1].PTS + SamplesToDuration(Frames[i-1].SampleCount);
Frames[i].PTS += shift;
}
}
const auto ActualSamples = back().SampleStart + back().SampleCount;
const auto ExpectedSamples = DurationToSamples(back().PTS - front().PTS) + back().SampleCount;
if (ActualSamples + 5 > ExpectedSamples) // arbitrary threshold to cover rounding/not worth adjusting
return;
// Verify that every frame has a timestamp and that they monotonically
// increase, as otherwise we can't trust them
auto PrevPTS = front().PTS - 1;
for (auto const& frame : *this) {
if (frame.PTS == AV_NOPTS_VALUE || frame.PTS <= PrevPTS)
return;
PrevPTS = frame.PTS;
}
// There are some missing samples and the timestamps appear to all be valid,
// so go ahead and extend the frames to cover the gaps
const auto FirstPTS = front().PTS;
auto PrevFrame = &Frames.front();
int32_t Shift = 0;
for (auto& Frame : Frames) {
if (Shift > 0)
Frame.SampleStart += Shift;
const auto ExpectedStartSample = DurationToSamples(Frame.PTS - FirstPTS);
const auto Gap = static_cast<int32_t>(ExpectedStartSample - Frame.SampleStart);
if (Gap > 0) {
PrevFrame->SampleCount += Gap;
Frame.SampleStart = ExpectedStartSample;
}
Shift += Gap;
PrevFrame = &Frame;
}
}
void FFMS_Track::FinalizeTrack() {
frame_vec &Frames = Data->Frames;
// With some formats (such as Vorbis) a bad final packet results in a
// frame with PTS 0, which we don't want to sort to the beginning
if (size() > 2 && front().PTS >= back().PTS)
Frames.pop_back();
if (TT == FFMS_TYPE_AUDIO) {
FillAudioGaps();
return;
}
if (TT != FFMS_TYPE_VIDEO)
return;
for (size_t i = 0; i < size(); i++) {
Frames[i].OriginalPos = i;
Frames[i].OriginalPTS = Frames[i].PTS;
}
MaybeReorderFrames();
if (size() > 2 && HasDiscontTS) {
std::vector<size_t> secs = { 0 };
auto lastPTS = Frames[0].PTS;
const auto thresh = std::abs(Frames[1].PTS - Frames[0].PTS) * 16; // A bad approximation of 16 frames, the max reorder buffer size.
for (size_t i = 0; i < size(); i++) {
if (Frames[i].PTS < lastPTS && (lastPTS - Frames[i].PTS) > thresh && i + 1 < size()) {
secs.push_back(i);
i++; // Sections must be at least 2 frames long.
}
lastPTS = Frames[i].PTS;
}
// We need to sort each distinct sections by PTS to account for any reordering.
for (size_t i = 0; i < secs.size() - 1; i++)
sort(Frames.begin() + secs[i], Frames.begin() + secs[i + 1], PTSComparison);
sort(Frames.begin() + secs.back(), Frames.end(), PTSComparison);
// Try and make up some sane timestamps based on previous sections, while
// keeping the same frame durations.
for (size_t i = 1; i < secs.size(); i++) {
const auto shift = -(Frames[secs[i]].PTS) + (Frames[secs[i] + 1].PTS - Frames[secs[i]].PTS) + Frames[secs[i] - 1].PTS;
size_t end;
if (i == secs.size() - 1)
end = Frames.size();
else
end = secs[i + 1];
for (size_t j = secs[i]; j < end; j++)
Frames[j].PTS += shift;
}
} else {
sort(Frames.begin(), Frames.end(), PTSComparison);
}
std::vector<size_t> ReorderTemp;
ReorderTemp.reserve(size());
for (size_t i = 0; i < size(); i++)
ReorderTemp.push_back(Frames[i].OriginalPos);
for (size_t i = 0; i < size(); i++)
Frames[ReorderTemp[i]].OriginalPos = i;
GeneratePublicInfo();
}
void FFMS_Track::GeneratePublicInfo() {
frame_vec &Frames = Data->Frames;
std::vector<int> &RealFrameNumbers = Data->RealFrameNumbers;
std::vector<FFMS_FrameInfo> &PublicFrameInfo = Data->PublicFrameInfo;
RealFrameNumbers.reserve(size());
PublicFrameInfo.reserve(size());
for (size_t i = 0; i < size(); ++i) {
if (Frames[i].Hidden)
continue;
RealFrameNumbers.push_back(static_cast<int>(i));
FFMS_FrameInfo info = { Frames[i].PTS, Frames[i].RepeatPict, Frames[i].KeyFrame, Frames[i].OriginalPTS };
PublicFrameInfo.push_back(info);
}
}
const FFMS_FrameInfo *FFMS_Track::GetFrameInfo(size_t N) const {
std::vector<FFMS_FrameInfo> &PublicFrameInfo = Data->PublicFrameInfo;
if (N >= PublicFrameInfo.size()) return nullptr;
return &PublicFrameInfo[N];
}

114
ffms2/src/core/track.h Normal file
View file

@ -0,0 +1,114 @@
// Copyright (c) 2013 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef TRACK_H
#define TRACK_H
#include "ffms.h"
#include <cstddef>
#include <vector>
#include <memory>
class ZipFile;
struct FrameInfo {
int64_t PTS;
int64_t OriginalPTS;
int64_t FilePos;
int64_t SampleStart;
uint32_t SampleCount;
size_t OriginalPos;
int FrameType;
int RepeatPict;
bool KeyFrame;
bool Hidden;
};
struct FFMS_Track {
private:
typedef std::vector<FrameInfo> frame_vec;
struct TrackData {
frame_vec Frames;
std::vector<int> RealFrameNumbers;
std::vector<FFMS_FrameInfo> PublicFrameInfo;
};
std::shared_ptr<TrackData> Data;
void MaybeReorderFrames();
void FillAudioGaps();
void GeneratePublicInfo();
public:
FFMS_TrackType TT = FFMS_TYPE_UNKNOWN;
FFMS_TrackTimeBase TB = FFMS_TrackTimeBase{ 0, 0 };
int MaxBFrames = 0;
bool UseDTS = false;
bool HasTS = false;
bool HasDiscontTS = false;
int64_t LastDuration = 0;
int SampleRate = 0; // not persisted
void AddVideoFrame(int64_t PTS, int RepeatPict, bool KeyFrame, int FrameType, int64_t FilePos = 0, bool Invisible = false);
void AddAudioFrame(int64_t PTS, int64_t SampleStart, uint32_t SampleCount, bool KeyFrame, int64_t FilePos = 0, bool Invisible = false);
void MaybeHideFrames();
void FinalizeTrack();
int FindClosestVideoKeyFrame(int Frame) const;
int FrameFromPTS(int64_t PTS) const;
int FrameFromPos(int64_t Pos) const;
int ClosestFrameFromPTS(int64_t PTS) const;
int RealFrameNumber(int Frame) const;
int VisibleFrameCount() const;
const FFMS_FrameInfo *GetFrameInfo(size_t N) const;
void WriteTimecodes(const char *TimecodeFile) const;
void Write(ZipFile &Stream) const;
typedef frame_vec::allocator_type allocator_type;
typedef frame_vec::size_type size_type;
typedef frame_vec::difference_type difference_type;
typedef frame_vec::const_pointer pointer;
typedef frame_vec::const_reference reference;
typedef frame_vec::value_type value_type;
typedef frame_vec::const_iterator iterator;
typedef frame_vec::const_reverse_iterator reverse_iterator;
void clear() {
Data = std::make_shared<TrackData>();
}
bool empty() const { return Data->Frames.empty(); }
size_type size() const { return Data->Frames.size(); }
reference operator[](size_type pos) const { return Data->Frames[pos]; }
reference front() const { return Data->Frames.front(); }
reference back() const { return Data->Frames.back(); }
iterator begin() const { return Data->Frames.begin(); }
iterator end() const { return Data->Frames.end(); }
FFMS_Track();
FFMS_Track(ZipFile &Stream);
FFMS_Track(int64_t Num, int64_t Den, FFMS_TrackType TT, bool HasDiscontTS, bool UseDTS, bool HasTS = true);
};
#endif

142
ffms2/src/core/utils.cpp Normal file
View file

@ -0,0 +1,142 @@
// Copyright (c) 2007-2015 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
extern "C" {
#include <libavutil/channel_layout.h>
}
#include "utils.h"
#include "indexing.h"
#include "track.h"
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif // _WIN32
#include <algorithm>
#include <sstream>
FFMS_Exception::FFMS_Exception(int ErrorType, int SubType, const char *Message) : _Message(Message), _ErrorType(ErrorType), _SubType(SubType) {}
FFMS_Exception::FFMS_Exception(int ErrorType, int SubType, const std::string &Message) : _Message(Message), _ErrorType(ErrorType), _SubType(SubType) {}
int FFMS_Exception::CopyOut(FFMS_ErrorInfo *ErrorInfo) const {
if (ErrorInfo) {
ErrorInfo->ErrorType = _ErrorType;
ErrorInfo->SubType = _SubType;
if (ErrorInfo->BufferSize > 0) {
memset(ErrorInfo->Buffer, 0, ErrorInfo->BufferSize);
_Message.copy(ErrorInfo->Buffer, ErrorInfo->BufferSize - 1);
}
}
return (_ErrorType << 16) | _SubType;
}
void ClearErrorInfo(FFMS_ErrorInfo *ErrorInfo) {
if (ErrorInfo) {
ErrorInfo->ErrorType = FFMS_ERROR_SUCCESS;
ErrorInfo->SubType = FFMS_ERROR_SUCCESS;
if (ErrorInfo->BufferSize > 0)
ErrorInfo->Buffer[0] = 0;
}
}
void InitNullPacket(AVPacket &pkt) {
av_init_packet(&pkt);
pkt.data = nullptr;
pkt.size = 0;
}
void FillAP(FFMS_AudioProperties &AP, AVCodecContext *CTX, FFMS_Track &Frames) {
AP.SampleFormat = static_cast<FFMS_SampleFormat>(av_get_packed_sample_fmt(CTX->sample_fmt));
AP.BitsPerSample = av_get_bytes_per_sample(CTX->sample_fmt) * 8;
AP.Channels = CTX->channels;
AP.ChannelLayout = CTX->channel_layout;
AP.SampleRate = CTX->sample_rate;
if (!Frames.empty()) {
AP.NumSamples = (Frames.back()).SampleStart + (Frames.back()).SampleCount;
AP.FirstTime = ((Frames.front().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
AP.LastTime = ((Frames.back().PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
AP.LastEndTime = (((Frames.back().PTS + Frames.LastDuration) * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
}
if (AP.ChannelLayout == 0)
AP.ChannelLayout = av_get_default_channel_layout(AP.Channels);
}
void LAVFOpenFile(const char *SourceFile, AVFormatContext *&FormatContext, int Track) {
if (avformat_open_input(&FormatContext, SourceFile, nullptr, nullptr) != 0)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
std::string("Couldn't open '") + SourceFile + "'");
if (avformat_find_stream_info(FormatContext, nullptr) < 0) {
avformat_close_input(&FormatContext);
FormatContext = nullptr;
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ,
"Couldn't find stream information");
}
for (int i = 0; i < (int)FormatContext->nb_streams; i++)
if (i != Track)
FormatContext->streams[i]->discard = AVDISCARD_ALL;
}
int ResizerNameToSWSResizer(const char *ResizerName) {
if (!ResizerName)
return 0;
std::string s = ResizerName;
std::transform(s.begin(), s.end(), s.begin(), toupper);
if (s == "FAST_BILINEAR")
return SWS_FAST_BILINEAR;
if (s == "BILINEAR")
return SWS_BILINEAR;
if (s == "BICUBIC")
return SWS_BICUBIC;
if (s == "X")
return SWS_X;
if (s == "POINT")
return SWS_POINT;
if (s == "AREA")
return SWS_AREA;
if (s == "BICUBLIN")
return SWS_BICUBLIN;
if (s == "GAUSS")
return SWS_GAUSS;
if (s == "SINC")
return SWS_SINC;
if (s == "LANCZOS")
return SWS_LANCZOS;
if (s == "SPLINE")
return SWS_SPLINE;
return 0;
}
bool IsSamePath(const char *p1, const char *p2) {
// assume windows is the only OS with a case insensitive filesystem and ignore all path complications
#ifndef _WIN32
return !strcmp(p1, p2);
#else
return !_stricmp(p1, p2);
#endif
}

138
ffms2/src/core/utils.h Normal file
View file

@ -0,0 +1,138 @@
// Copyright (c) 2007-2011 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef UTILS_H
#define UTILS_H
#include "ffms.h"
extern "C" {
#include <libavutil/mem.h>
#include <libavutil/opt.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
}
// must be included after ffmpeg headers
#include "ffmscompat.h"
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
class FFMS_Exception {
std::string _Message;
int _ErrorType;
int _SubType;
public:
FFMS_Exception(int ErrorType, int SubType, const char *Message = "");
FFMS_Exception(int ErrorType, int SubType, const std::string &Message);
const std::string &GetErrorMessage() const { return _Message; }
int CopyOut(FFMS_ErrorInfo *ErrorInfo) const;
};
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
void ClearErrorInfo(FFMS_ErrorInfo *ErrorInfo);
void InitNullPacket(AVPacket &pkt);
void FillAP(FFMS_AudioProperties &AP, AVCodecContext *CTX, FFMS_Track &Frames);
void LAVFOpenFile(const char *SourceFile, AVFormatContext *&FormatContext, int Track);
namespace optdetail {
template<typename T>
T get_av_opt(void *v, const char *name) {
int64_t value = 0;
av_opt_get_int(v, name, 0, &value);
return static_cast<T>(value);
}
template<>
inline double get_av_opt<double>(void *v, const char *name) {
double value = 0.0;
av_opt_get_double(v, name, 0, &value);
return value;
}
template<typename T>
void set_av_opt(void *v, const char *name, T value) {
av_opt_set_int(v, name, value, 0);
}
template<>
inline void set_av_opt<double>(void *v, const char *name, double value) {
av_opt_set_double(v, name, value, 0);
}
}
template<typename FFMS_Struct>
class OptionMapper {
struct OptionMapperBase {
virtual void ToOpt(FFMS_Struct const& src, void *dst) const = 0;
virtual void FromOpt(FFMS_Struct &dst, void *src) const = 0;
virtual ~OptionMapperBase() = default;
};
template<typename T>
class OptionMapperImpl : public OptionMapperBase {
T(FFMS_Struct::*ptr);
const char *name;
public:
OptionMapperImpl(T(FFMS_Struct::*ptr), const char *name) : ptr(ptr), name(name) {}
void ToOpt(FFMS_Struct const& src, void *dst) const { optdetail::set_av_opt(dst, name, src.*ptr); }
void FromOpt(FFMS_Struct &dst, void *src) const { dst.*ptr = optdetail::get_av_opt<T>(src, name); }
};
std::unique_ptr<OptionMapperBase> impl;
public:
template<typename T>
OptionMapper(const char *opt_name, T(FFMS_Struct::*member)) : impl(new OptionMapperImpl<T>(member, opt_name)) {}
void ToOpt(FFMS_Struct const& src, void *dst) const { impl->ToOpt(src, dst); }
void FromOpt(FFMS_Struct &dst, void *src) const { impl->FromOpt(dst, src); }
};
template<typename T, int N>
std::unique_ptr<T> ReadOptions(void *opt, OptionMapper<T>(&options)[N]) {
auto ret = make_unique<T>();
for (int i = 0; i < N; ++i)
options[i].FromOpt(*ret, opt);
return ret;
}
template<typename T, int N>
void SetOptions(T const& src, void *opt, OptionMapper<T>(&options)[N]) {
for (int i = 0; i < N; ++i)
options[i].ToOpt(src, opt);
}
int ResizerNameToSWSResizer(const char *ResizerName);
bool IsSamePath(const char *p1, const char *p2);
#endif

View file

@ -0,0 +1,801 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "videosource.h"
#include "indexing.h"
#include "videoutils.h"
#include <algorithm>
#include <thread>
void FFMS_VideoSource::SanityCheckFrameForData(AVFrame *Frame) {
for (int i = 0; i < 4; i++) {
if (Frame->data[i] != nullptr && Frame->linesize[i] != 0)
return;
}
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC, "Insanity detected: decoder returned an empty frame");
}
void FFMS_VideoSource::GetFrameCheck(int n) {
if (n < 0 || n >= VP.NumFrames)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_INVALID_ARGUMENT,
"Out of bounds frame requested");
}
FFMS_Frame *FFMS_VideoSource::OutputFrame(AVFrame *Frame) {
SanityCheckFrameForData(Frame);
if (LastFrameWidth != Frame->width || LastFrameHeight != Frame->height || LastFramePixelFormat != Frame->format) {
if (TargetHeight > 0 && TargetWidth > 0 && !TargetPixelFormats.empty()) {
if (!InputFormatOverridden) {
InputFormat = AV_PIX_FMT_NONE;
InputColorSpace = AVCOL_SPC_UNSPECIFIED;
InputColorRange = AVCOL_RANGE_UNSPECIFIED;
}
ReAdjustOutputFormat(Frame);
} else {
OutputFormat = (AVPixelFormat) Frame->format;
}
}
if (SWS) {
sws_scale(SWS, Frame->data, Frame->linesize, 0, Frame->height, SWSFrameData, SWSFrameLinesize);
for (int i = 0; i < 4; i++) {
LocalFrame.Data[i] = SWSFrameData[i];
LocalFrame.Linesize[i] = SWSFrameLinesize[i];
}
} else {
// Special case to avoid ugly casts
for (int i = 0; i < 4; i++) {
LocalFrame.Data[i] = Frame->data[i];
LocalFrame.Linesize[i] = Frame->linesize[i];
}
}
LocalFrame.EncodedWidth = Frame->width;
LocalFrame.EncodedHeight = Frame->height;
LocalFrame.EncodedPixelFormat = Frame->format;
LocalFrame.ScaledWidth = TargetWidth;
LocalFrame.ScaledHeight = TargetHeight;
LocalFrame.ConvertedPixelFormat = OutputFormat;
LocalFrame.KeyFrame = Frame->key_frame;
LocalFrame.PictType = av_get_picture_type_char(Frame->pict_type);
LocalFrame.RepeatPict = Frame->repeat_pict;
LocalFrame.InterlacedFrame = Frame->interlaced_frame;
LocalFrame.TopFieldFirst = Frame->top_field_first;
LocalFrame.ColorSpace = OutputColorSpaceSet ? OutputColorSpace : Frame->colorspace;
LocalFrame.ColorRange = OutputColorRangeSet ? OutputColorRange : Frame->color_range;
LocalFrame.ColorPrimaries = (OutputColorPrimaries >= 0) ? OutputColorPrimaries : Frame->color_primaries;
LocalFrame.TransferCharateristics = (OutputTransferCharateristics >= 0) ? OutputTransferCharateristics : Frame->color_trc;
LocalFrame.ChromaLocation = (OutputChromaLocation >= 0) ? OutputChromaLocation : Frame->chroma_location;
const AVFrameSideData *MasteringDisplaySideData = av_frame_get_side_data(Frame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
if (MasteringDisplaySideData) {
const AVMasteringDisplayMetadata *MasteringDisplay = reinterpret_cast<const AVMasteringDisplayMetadata *>(MasteringDisplaySideData->data);
if (MasteringDisplay->has_primaries) {
LocalFrame.HasMasteringDisplayPrimaries = MasteringDisplay->has_primaries;
for (int i = 0; i < 3; i++) {
LocalFrame.MasteringDisplayPrimariesX[i] = av_q2d(MasteringDisplay->display_primaries[i][0]);
LocalFrame.MasteringDisplayPrimariesY[i] = av_q2d(MasteringDisplay->display_primaries[i][1]);
}
LocalFrame.MasteringDisplayWhitePointX = av_q2d(MasteringDisplay->white_point[0]);
LocalFrame.MasteringDisplayWhitePointY = av_q2d(MasteringDisplay->white_point[1]);
}
if (MasteringDisplay->has_luminance) {
LocalFrame.HasMasteringDisplayLuminance = MasteringDisplay->has_luminance;
LocalFrame.MasteringDisplayMinLuminance = av_q2d(MasteringDisplay->min_luminance);
LocalFrame.MasteringDisplayMaxLuminance = av_q2d(MasteringDisplay->max_luminance);
}
}
LocalFrame.HasMasteringDisplayPrimaries = !!LocalFrame.MasteringDisplayPrimariesX[0] && !!LocalFrame.MasteringDisplayPrimariesY[0] &&
!!LocalFrame.MasteringDisplayPrimariesX[1] && !!LocalFrame.MasteringDisplayPrimariesY[1] &&
!!LocalFrame.MasteringDisplayPrimariesX[2] && !!LocalFrame.MasteringDisplayPrimariesY[2] &&
!!LocalFrame.MasteringDisplayWhitePointX && !!LocalFrame.MasteringDisplayWhitePointY;
/* MasteringDisplayMinLuminance can be 0 */
LocalFrame.HasMasteringDisplayLuminance = !!LocalFrame.MasteringDisplayMaxLuminance;
const AVFrameSideData *ContentLightSideData = av_frame_get_side_data(Frame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
if (ContentLightSideData) {
const AVContentLightMetadata *ContentLightLevel = reinterpret_cast<const AVContentLightMetadata *>(ContentLightSideData->data);
LocalFrame.ContentLightLevelMax = ContentLightLevel->MaxCLL;
LocalFrame.ContentLightLevelAverage = ContentLightLevel->MaxFALL;
}
/* Only check for either of them */
LocalFrame.HasContentLightLevel = !!LocalFrame.ContentLightLevelMax || !!LocalFrame.ContentLightLevelAverage;
LastFrameHeight = Frame->height;
LastFrameWidth = Frame->width;
LastFramePixelFormat = (AVPixelFormat) Frame->format;
return &LocalFrame;
}
FFMS_VideoSource::FFMS_VideoSource(const char *SourceFile, FFMS_Index &Index, int Track, int Threads, int SeekMode)
: Index(Index), SeekMode(SeekMode) {
try {
if (Track < 0 || Track >= static_cast<int>(Index.size()))
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Out of bounds track index selected");
if (Index[Track].TT != FFMS_TYPE_VIDEO)
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Not a video track");
if (Index[Track].empty())
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_INVALID_ARGUMENT,
"Video track contains no frames");
if (!Index.CompareFileSignature(SourceFile))
throw FFMS_Exception(FFMS_ERROR_INDEX, FFMS_ERROR_FILE_MISMATCH,
"The index does not match the source file");
Frames = Index[Track];
VideoTrack = Track;
if (Threads < 1)
DecodingThreads = (std::min)(std::thread::hardware_concurrency(), 16u);
else
DecodingThreads = Threads;
DecodeFrame = av_frame_alloc();
LastDecodedFrame = av_frame_alloc();
if (!DecodeFrame || !LastDecodedFrame)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate dummy frame.");
// Dummy allocations so the unallocated case doesn't have to be handled later
if (av_image_alloc(SWSFrameData, SWSFrameLinesize, 16, 16, AV_PIX_FMT_GRAY8, 4) < 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate dummy frame.");
LAVFOpenFile(SourceFile, FormatContext, VideoTrack);
AVCodec *Codec = avcodec_find_decoder(FormatContext->streams[VideoTrack]->codecpar->codec_id);
if (Codec == nullptr)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Video codec not found");
CodecContext = avcodec_alloc_context3(Codec);
if (CodecContext == nullptr)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate video codec context.");
if (avcodec_parameters_to_context(CodecContext, FormatContext->streams[VideoTrack]->codecpar) < 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Could not copy video decoder parameters.");
CodecContext->thread_count = DecodingThreads;
CodecContext->has_b_frames = Frames.MaxBFrames;
// Full explanation by more clever person availale here: https://github.com/Nevcairiel/LAVFilters/issues/113
if (CodecContext->codec_id == AV_CODEC_ID_H264 && CodecContext->has_b_frames)
CodecContext->has_b_frames = 15; // the maximum possible value for h264
if (avcodec_open2(CodecContext, Codec, nullptr) < 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Could not open video codec");
// Similar yet different to h264 workaround above
// vc1 simply sets has_b_frames to 1 no matter how many there are so instead we set it to the max value
// in order to not confuse our own delay guesses later
// Doesn't affect actual vc1 reordering unlike h264
if (CodecContext->codec_id == AV_CODEC_ID_VC1 && CodecContext->has_b_frames)
Delay = 7 + (CodecContext->thread_count - 1); // the maximum possible value for vc1
else
Delay = CodecContext->has_b_frames + (CodecContext->thread_count - 1); // Normal decoder delay
// Always try to decode a frame to make sure all required parameters are known
int64_t DummyPTS = 0, DummyPos = 0;
DecodeNextFrame(DummyPTS, DummyPos);
//VP.image_type = VideoInfo::IT_TFF;
VP.FPSDenominator = FormatContext->streams[VideoTrack]->time_base.num;
VP.FPSNumerator = FormatContext->streams[VideoTrack]->time_base.den;
// sanity check framerate
if (VP.FPSDenominator <= 0 || VP.FPSNumerator <= 0) {
VP.FPSDenominator = 1;
VP.FPSNumerator = 30;
}
// Calculate the average framerate
size_t TotalFrames = 0;
for (size_t i = 0; i < Frames.size(); i++)
if (!Frames[i].Hidden)
TotalFrames++;
if (TotalFrames >= 2) {
double PTSDiff = (double)(Frames.back().PTS - Frames.front().PTS);
double TD = (double)(Frames.TB.Den);
double TN = (double)(Frames.TB.Num);
VP.FPSDenominator = (unsigned int)(PTSDiff * TN / TD * 1000.0 / (TotalFrames - 1));
VP.FPSNumerator = 1000000;
}
// Set the video properties from the codec context
SetVideoProperties();
// Set the SAR from the container if the codec SAR is invalid
if (VP.SARNum <= 0 || VP.SARDen <= 0) {
VP.SARNum = FormatContext->streams[VideoTrack]->sample_aspect_ratio.num;
VP.SARDen = FormatContext->streams[VideoTrack]->sample_aspect_ratio.den;
}
// Set stereoscopic 3d type
VP.Stereo3DType = FFMS_S3D_TYPE_2D;
VP.Stereo3DFlags = 0;
for (int i = 0; i < FormatContext->streams[VideoTrack]->nb_side_data; i++) {
if (FormatContext->streams[VideoTrack]->side_data[i].type == AV_PKT_DATA_STEREO3D) {
const AVStereo3D *StereoSideData = (const AVStereo3D *)FormatContext->streams[VideoTrack]->side_data[i].data;
VP.Stereo3DType = StereoSideData->type;
VP.Stereo3DFlags = StereoSideData->flags;
} else if (FormatContext->streams[VideoTrack]->side_data[i].type == AV_PKT_DATA_MASTERING_DISPLAY_METADATA) {
const AVMasteringDisplayMetadata *MasteringDisplay = (const AVMasteringDisplayMetadata *)FormatContext->streams[VideoTrack]->side_data[i].data;
if (MasteringDisplay->has_primaries) {
VP.HasMasteringDisplayPrimaries = MasteringDisplay->has_primaries;
for (int i = 0; i < 3; i++) {
VP.MasteringDisplayPrimariesX[i] = av_q2d(MasteringDisplay->display_primaries[i][0]);
VP.MasteringDisplayPrimariesY[i] = av_q2d(MasteringDisplay->display_primaries[i][1]);
}
VP.MasteringDisplayWhitePointX = av_q2d(MasteringDisplay->white_point[0]);
VP.MasteringDisplayWhitePointY = av_q2d(MasteringDisplay->white_point[1]);
}
if (MasteringDisplay->has_luminance) {
VP.HasMasteringDisplayLuminance = MasteringDisplay->has_luminance;
VP.MasteringDisplayMinLuminance = av_q2d(MasteringDisplay->min_luminance);
VP.MasteringDisplayMaxLuminance = av_q2d(MasteringDisplay->max_luminance);
}
VP.HasMasteringDisplayPrimaries = !!VP.MasteringDisplayPrimariesX[0] && !!VP.MasteringDisplayPrimariesY[0] &&
!!VP.MasteringDisplayPrimariesX[1] && !!VP.MasteringDisplayPrimariesY[1] &&
!!VP.MasteringDisplayPrimariesX[2] && !!VP.MasteringDisplayPrimariesY[2] &&
!!VP.MasteringDisplayWhitePointX && !!VP.MasteringDisplayWhitePointY;
/* MasteringDisplayMinLuminance can be 0 */
VP.HasMasteringDisplayLuminance = !!VP.MasteringDisplayMaxLuminance;
} else if (FormatContext->streams[VideoTrack]->side_data[i].type == AV_PKT_DATA_CONTENT_LIGHT_LEVEL) {
const AVContentLightMetadata *ContentLightLevel = (const AVContentLightMetadata *)FormatContext->streams[VideoTrack]->side_data[i].data;
VP.ContentLightLevelMax = ContentLightLevel->MaxCLL;
VP.ContentLightLevelAverage = ContentLightLevel->MaxFALL;
/* Only check for either of them */
VP.HasContentLightLevel = !!VP.ContentLightLevelMax || !!VP.ContentLightLevelAverage;
}
}
// Set rotation
VP.Rotation = 0;
VP.Flip = 0;
int32_t *RotationMatrix = reinterpret_cast<int32_t *>(av_stream_get_side_data(FormatContext->streams[VideoTrack], AV_PKT_DATA_DISPLAYMATRIX, nullptr));
if (RotationMatrix) {
int64_t det = (int64_t)RotationMatrix[0] * RotationMatrix[4] - (int64_t)RotationMatrix[1] * RotationMatrix[3];
if (det < 0) {
/* Always assume an horizontal flip for simplicity, it can be changed later if rotation is 180. */
VP.Flip = 1;
/* Flip the matrix to decouple flip and rotation operations. */
av_display_matrix_flip(RotationMatrix, 1, 0);
}
int rot = lround(av_display_rotation_get(RotationMatrix));
if (rot == 180 && det < 0) {
/* This is a vertical flip with no rotation. */
VP.Flip = -1;
} else {
/* It is possible to have a 90/270 rotation and a horizontal flip:
* in this case, the rotation angle applies to the video frame
* (rather than the rendering frame), so add this step to nullify
* the conversion below. */
if (VP.Flip)
rot *= -1;
/* Return a positive value, noting that this converts angles
* from the rendering frame to the video frame. */
VP.Rotation = -rot;
if (VP.Rotation < 0)
VP.Rotation += 360;
}
}
if (SeekMode >= 0 && Frames.size() > 1) {
if (Seek(0) < 0) {
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Video track is unseekable");
} else {
avcodec_flush_buffers(CodecContext);
// Since we seeked to frame 0 we need to specify that frame 0 is once again the next frame that wil be decoded
CurrentFrame = 0;
}
}
// Cannot "output" without doing all other initialization
// This is the additional mess required for seekmode=-1 to work in a reasonable way
OutputFrame(DecodeFrame);
if (LocalFrame.HasMasteringDisplayPrimaries) {
VP.HasMasteringDisplayPrimaries = LocalFrame.HasMasteringDisplayPrimaries;
for (int i = 0; i < 3; i++) {
VP.MasteringDisplayPrimariesX[i] = LocalFrame.MasteringDisplayPrimariesX[i];
VP.MasteringDisplayPrimariesY[i] = LocalFrame.MasteringDisplayPrimariesY[i];
}
// Simply copy this from the first frame to make it easier to access
VP.MasteringDisplayWhitePointX = LocalFrame.MasteringDisplayWhitePointX;
VP.MasteringDisplayWhitePointY = LocalFrame.MasteringDisplayWhitePointY;
}
if (LocalFrame.HasMasteringDisplayLuminance) {
VP.HasMasteringDisplayLuminance = LocalFrame.HasMasteringDisplayLuminance;
VP.MasteringDisplayMinLuminance = LocalFrame.MasteringDisplayMinLuminance;
VP.MasteringDisplayMaxLuminance = LocalFrame.MasteringDisplayMaxLuminance;
}
if (LocalFrame.HasContentLightLevel) {
VP.HasContentLightLevel = LocalFrame.HasContentLightLevel;
VP.ContentLightLevelMax = LocalFrame.ContentLightLevelMax;
VP.ContentLightLevelAverage = LocalFrame.ContentLightLevelAverage;
}
} catch (FFMS_Exception &) {
Free();
throw;
}
}
FFMS_VideoSource::~FFMS_VideoSource() {
Free();
}
FFMS_Frame *FFMS_VideoSource::GetFrameByTime(double Time) {
int Frame = Frames.ClosestFrameFromPTS(static_cast<int64_t>((Time * 1000 * Frames.TB.Den) / Frames.TB.Num));
return GetFrame(Frame);
}
static AVColorRange handle_jpeg(AVPixelFormat *format) {
switch (*format) {
case AV_PIX_FMT_YUVJ420P: *format = AV_PIX_FMT_YUV420P; return AVCOL_RANGE_JPEG;
case AV_PIX_FMT_YUVJ422P: *format = AV_PIX_FMT_YUV422P; return AVCOL_RANGE_JPEG;
case AV_PIX_FMT_YUVJ444P: *format = AV_PIX_FMT_YUV444P; return AVCOL_RANGE_JPEG;
case AV_PIX_FMT_YUVJ440P: *format = AV_PIX_FMT_YUV440P; return AVCOL_RANGE_JPEG;
default: return AVCOL_RANGE_UNSPECIFIED;
}
}
void FFMS_VideoSource::SetOutputFormat(const AVPixelFormat *TargetFormats, int Width, int Height, int Resizer) {
TargetWidth = Width;
TargetHeight = Height;
TargetResizer = Resizer;
TargetPixelFormats.clear();
while (*TargetFormats != AV_PIX_FMT_NONE)
TargetPixelFormats.push_back(*TargetFormats++);
OutputColorSpaceSet = true;
OutputColorRangeSet = true;
OutputFormat = AV_PIX_FMT_NONE;
ReAdjustOutputFormat(DecodeFrame);
OutputFrame(DecodeFrame);
}
void FFMS_VideoSource::SetInputFormat(int ColorSpace, int ColorRange, AVPixelFormat Format) {
InputFormatOverridden = true;
if (Format != AV_PIX_FMT_NONE)
InputFormat = Format;
if (ColorRange != AVCOL_RANGE_UNSPECIFIED)
InputColorRange = (AVColorRange)ColorRange;
if (ColorSpace != AVCOL_SPC_UNSPECIFIED)
InputColorSpace = (AVColorSpace)ColorSpace;
if (TargetPixelFormats.size()) {
ReAdjustOutputFormat(DecodeFrame);
OutputFrame(DecodeFrame);
}
}
void FFMS_VideoSource::DetectInputFormat() {
if (InputFormat == AV_PIX_FMT_NONE)
InputFormat = CodecContext->pix_fmt;
AVColorRange RangeFromFormat = handle_jpeg(&InputFormat);
if (InputColorRange == AVCOL_RANGE_UNSPECIFIED)
InputColorRange = RangeFromFormat;
if (InputColorRange == AVCOL_RANGE_UNSPECIFIED)
InputColorRange = CodecContext->color_range;
if (InputColorSpace == AVCOL_SPC_UNSPECIFIED)
InputColorSpace = CodecContext->colorspace;
}
void FFMS_VideoSource::ReAdjustOutputFormat(AVFrame *Frame) {
if (SWS) {
sws_freeContext(SWS);
SWS = nullptr;
}
DetectInputFormat();
OutputFormat = FindBestPixelFormat(TargetPixelFormats, InputFormat);
if (OutputFormat == AV_PIX_FMT_NONE) {
ResetOutputFormat();
throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_INVALID_ARGUMENT,
"No suitable output format found");
}
OutputColorRange = handle_jpeg(&OutputFormat);
if (OutputColorRange == AVCOL_RANGE_UNSPECIFIED)
OutputColorRange = CodecContext->color_range;
if (OutputColorRange == AVCOL_RANGE_UNSPECIFIED)
OutputColorRange = InputColorRange;
OutputColorSpace = CodecContext->colorspace;
if (OutputColorSpace == AVCOL_SPC_UNSPECIFIED)
OutputColorSpace = InputColorSpace;
BCSType InputType = GuessCSType(InputFormat);
BCSType OutputType = GuessCSType(OutputFormat);
if (InputType != OutputType) {
if (OutputType == cRGB) {
OutputColorSpace = AVCOL_SPC_RGB;
OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
OutputColorPrimaries = AVCOL_PRI_UNSPECIFIED;
OutputTransferCharateristics = AVCOL_TRC_UNSPECIFIED;
OutputChromaLocation = AVCHROMA_LOC_UNSPECIFIED;
} else if (OutputType == cYUV) {
OutputColorSpace = AVCOL_SPC_BT470BG;
OutputColorRange = AVCOL_RANGE_MPEG;
OutputColorPrimaries = AVCOL_PRI_UNSPECIFIED;
OutputTransferCharateristics = AVCOL_TRC_UNSPECIFIED;
OutputChromaLocation = AVCHROMA_LOC_LEFT;
} else if (OutputType == cGRAY) {
OutputColorSpace = AVCOL_SPC_UNSPECIFIED;
OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
OutputColorPrimaries = AVCOL_PRI_UNSPECIFIED;
OutputTransferCharateristics = AVCOL_TRC_UNSPECIFIED;
OutputChromaLocation = AVCHROMA_LOC_UNSPECIFIED;
}
} else {
OutputColorPrimaries = -1;
OutputTransferCharateristics = -1;
OutputChromaLocation = -1;
}
if (InputFormat != OutputFormat ||
TargetWidth != CodecContext->width ||
TargetHeight != CodecContext->height ||
InputColorSpace != OutputColorSpace ||
InputColorRange != OutputColorRange) {
SWS = GetSwsContext(
Frame->width, Frame->height, InputFormat, InputColorSpace, InputColorRange,
TargetWidth, TargetHeight, OutputFormat, OutputColorSpace, OutputColorRange,
TargetResizer);
if (!SWS) {
ResetOutputFormat();
throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_INVALID_ARGUMENT,
"Failed to allocate SWScale context");
}
}
av_freep(&SWSFrameData[0]);
if (av_image_alloc(SWSFrameData, SWSFrameLinesize, TargetWidth, TargetHeight, OutputFormat, 4) < 0)
throw FFMS_Exception(FFMS_ERROR_SCALING, FFMS_ERROR_ALLOCATION_FAILED,
"Could not allocate frame with new resolution.");
}
void FFMS_VideoSource::ResetOutputFormat() {
if (SWS) {
sws_freeContext(SWS);
SWS = nullptr;
}
TargetWidth = -1;
TargetHeight = -1;
TargetPixelFormats.clear();
OutputFormat = AV_PIX_FMT_NONE;
OutputColorSpace = AVCOL_SPC_UNSPECIFIED;
OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
OutputColorSpaceSet = false;
OutputColorRangeSet = false;
OutputFrame(DecodeFrame);
}
void FFMS_VideoSource::ResetInputFormat() {
InputFormatOverridden = false;
InputFormat = AV_PIX_FMT_NONE;
InputColorSpace = AVCOL_SPC_UNSPECIFIED;
InputColorRange = AVCOL_RANGE_UNSPECIFIED;
ReAdjustOutputFormat(DecodeFrame);
OutputFrame(DecodeFrame);
}
void FFMS_VideoSource::SetVideoProperties() {
VP.RFFDenominator = CodecContext->time_base.num;
VP.RFFNumerator = CodecContext->time_base.den;
if (CodecContext->codec_id == AV_CODEC_ID_H264) {
if (VP.RFFNumerator & 1)
VP.RFFDenominator *= 2;
else
VP.RFFNumerator /= 2;
}
VP.NumFrames = Frames.VisibleFrameCount();
VP.TopFieldFirst = DecodeFrame->top_field_first;
VP.ColorSpace = CodecContext->colorspace;
VP.ColorRange = CodecContext->color_range;
// these pixfmt's are deprecated but still used
if (CodecContext->pix_fmt == AV_PIX_FMT_YUVJ420P ||
CodecContext->pix_fmt == AV_PIX_FMT_YUVJ422P ||
CodecContext->pix_fmt == AV_PIX_FMT_YUVJ444P
)
VP.ColorRange = AVCOL_RANGE_JPEG;
VP.FirstTime = ((Frames[Frames.RealFrameNumber(0)].PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
VP.LastTime = ((Frames[Frames.RealFrameNumber(Frames.VisibleFrameCount()-1)].PTS * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
VP.LastEndTime = (((Frames[Frames.RealFrameNumber(Frames.VisibleFrameCount()-1)].PTS + Frames.LastDuration) * Frames.TB.Num) / (double)Frames.TB.Den) / 1000;
if (CodecContext->width <= 0 || CodecContext->height <= 0)
throw FFMS_Exception(FFMS_ERROR_DECODING, FFMS_ERROR_CODEC,
"Codec returned zero size video");
// attempt to correct framerate to the proper NTSC fraction, if applicable
CorrectRationalFramerate(&VP.FPSNumerator, &VP.FPSDenominator);
// correct the timebase, if necessary
CorrectTimebase(&VP, &Frames.TB);
// Set AR variables
VP.SARNum = CodecContext->sample_aspect_ratio.num;
VP.SARDen = CodecContext->sample_aspect_ratio.den;
// Set input and output formats now that we have a CodecContext
DetectInputFormat();
OutputFormat = InputFormat;
OutputColorSpace = InputColorSpace;
OutputColorRange = InputColorRange;
}
bool FFMS_VideoSource::HasPendingDelayedFrames() {
if (InitialDecode == -1) {
if (DelayCounter > Delay) {
--DelayCounter;
return true;
}
InitialDecode = 0;
}
return false;
}
bool FFMS_VideoSource::DecodePacket(AVPacket *Packet) {
std::swap(DecodeFrame, LastDecodedFrame);
avcodec_send_packet(CodecContext, Packet);
int Ret = avcodec_receive_frame(CodecContext, DecodeFrame);
if (Ret != 0) {
std::swap(DecodeFrame, LastDecodedFrame);
if (!(Packet->flags & AV_PKT_FLAG_DISCARD))
DelayCounter++;
} else if (!!(Packet->flags & AV_PKT_FLAG_DISCARD)) {
// If sending discarded frame when the decode buffer is not empty, caller
// may still obtained bufferred decoded frames and the number of frames
// in the buffer decreases.
DelayCounter--;
}
if (Ret == 0 && InitialDecode == 1)
InitialDecode = -1;
// H.264 (PAFF) and HEVC can have one field per packet, and decoding delay needs
// to be adjusted accordingly.
if (CodecContext->codec_id == AV_CODEC_ID_H264 || CodecContext->codec_id == AV_CODEC_ID_HEVC) {
if (!PAFFAdjusted && DelayCounter > Delay && LastDecodedFrame->repeat_pict == 0 && Ret != 0) {
int OldBFrameDelay = Delay - (CodecContext->thread_count - 1);
Delay = 1 + OldBFrameDelay * 2 + (CodecContext->thread_count - 1);
PAFFAdjusted = true;
}
}
return (Ret == 0) || (DelayCounter > Delay && !InitialDecode);;
}
int FFMS_VideoSource::Seek(int n) {
int ret = -1;
DelayCounter = 0;
InitialDecode = 1;
if (!SeekByPos || Frames[n].FilePos < 0) {
ret = av_seek_frame(FormatContext, VideoTrack, Frames[n].PTS, AVSEEK_FLAG_BACKWARD);
if (ret >= 0)
return ret;
}
if (Frames[n].FilePos >= 0) {
ret = av_seek_frame(FormatContext, VideoTrack, Frames[n].FilePos + PosOffset, AVSEEK_FLAG_BYTE);
if (ret >= 0)
SeekByPos = true;
}
return ret;
}
int FFMS_VideoSource::ReadFrame(AVPacket *pkt) {
int ret = av_read_frame(FormatContext, pkt);
if (ret >= 0 || ret == AVERROR(EOF)) return ret;
// Lavf reports the beginning of the actual video data as the packet's
// position, but the reader requires the header, so we end up seeking
// to the wrong position. Wait until a read actual fails to adjust the
// seek targets, so that if this ever gets fixed upstream our workaround
// doesn't re-break it.
if (strcmp(FormatContext->iformat->name, "yuv4mpegpipe") == 0) {
PosOffset = -6;
Seek(CurrentFrame);
return av_read_frame(FormatContext, pkt);
}
return ret;
}
void FFMS_VideoSource::Free() {
avcodec_free_context(&CodecContext);
avformat_close_input(&FormatContext);
if (SWS)
sws_freeContext(SWS);
av_freep(&SWSFrameData[0]);
av_frame_free(&DecodeFrame);
av_frame_free(&LastDecodedFrame);
}
void FFMS_VideoSource::DecodeNextFrame(int64_t &AStartTime, int64_t &Pos) {
AStartTime = -1;
if (HasPendingDelayedFrames())
return;
AVPacket Packet;
InitNullPacket(Packet);
while (ReadFrame(&Packet) >= 0) {
if (Packet.stream_index != VideoTrack) {
av_packet_unref(&Packet);
continue;
}
if (AStartTime < 0)
AStartTime = Frames.UseDTS ? Packet.dts : Packet.pts;
if (Pos < 0)
Pos = Packet.pos;
bool FrameFinished = DecodePacket(&Packet);
av_packet_unref(&Packet);
if (FrameFinished)
return;
}
// Flush final frames
InitNullPacket(Packet);
DecodePacket(&Packet);
}
bool FFMS_VideoSource::SeekTo(int n, int SeekOffset) {
if (SeekMode >= 0) {
int TargetFrame = n + SeekOffset;
if (TargetFrame < 0)
throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_UNKNOWN,
"Frame accurate seeking is not possible in this file");
if (SeekMode < 3)
TargetFrame = Frames.FindClosestVideoKeyFrame(TargetFrame);
if (SeekMode == 0) {
if (n < CurrentFrame) {
Seek(0);
avcodec_flush_buffers(CodecContext);
CurrentFrame = 0;
}
} else {
// 10 frames is used as a margin to prevent excessive seeking since the predicted best keyframe isn't always selected by avformat
if (n < CurrentFrame || TargetFrame > CurrentFrame + 10 || (SeekMode == 3 && n > CurrentFrame + 10)) {
Seek(TargetFrame);
avcodec_flush_buffers(CodecContext);
return true;
}
}
} else if (n < CurrentFrame) {
throw FFMS_Exception(FFMS_ERROR_SEEKING, FFMS_ERROR_INVALID_ARGUMENT,
"Non-linear access attempted");
}
return false;
}
FFMS_Frame *FFMS_VideoSource::GetFrame(int n) {
GetFrameCheck(n);
n = Frames.RealFrameNumber(n);
if (LastFrameNum == n)
return &LocalFrame;
int SeekOffset = 0;
bool Seek = true;
do {
bool HasSeeked = false;
if (Seek) {
HasSeeked = SeekTo(n, SeekOffset);
Seek = false;
}
int64_t StartTime = AV_NOPTS_VALUE, FilePos = -1;
bool Hidden = (((unsigned) CurrentFrame < Frames.size()) && Frames[CurrentFrame].Hidden);
if (HasSeeked || !Hidden)
DecodeNextFrame(StartTime, FilePos);
if (!HasSeeked)
continue;
if (StartTime == AV_NOPTS_VALUE && !Frames.HasTS) {
if (FilePos >= 0) {
CurrentFrame = Frames.FrameFromPos(FilePos);
if (CurrentFrame >= 0)
continue;
}
// If the track doesn't have timestamps or file positions then
// just trust that we got to the right place, since we have no
// way to tell where we are
else {
CurrentFrame = n;
continue;
}
}
CurrentFrame = Frames.FrameFromPTS(StartTime);
// Is the seek destination time known? Does it belong to a frame?
if (CurrentFrame < 0) {
if (SeekMode == 1 || StartTime < 0) {
// No idea where we are so go back a bit further
SeekOffset -= 10;
Seek = true;
continue;
}
CurrentFrame = Frames.ClosestFrameFromPTS(StartTime);
}
// We want to know the frame number that we just got out of the decoder,
// but what we currently know is the frame number of the first packet
// we fed into the decoder, and these can be different with open-gop or
// aggressive (non-keyframe) seeking.
int64_t Pos = Frames[CurrentFrame].FilePos;
if (CurrentFrame > 0 && Pos != -1) {
int Prev = CurrentFrame - 1;
while (Prev >= 0 && Frames[Prev].FilePos != -1 && Frames[Prev].FilePos > Pos)
--Prev;
CurrentFrame = Prev + 1;
}
} while (++CurrentFrame <= n);
LastFrameNum = n;
return OutputFrame(DecodeFrame);
}

View file

@ -0,0 +1,118 @@
// Copyright (c) 2007-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFVIDEOSOURCE_H
#define FFVIDEOSOURCE_H
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libavutil/stereo3d.h>
#include <libavutil/display.h>
#include <libavutil/mastering_display_metadata.h>
}
#include <vector>
#include "track.h"
#include "utils.h"
struct FFMS_VideoSource {
private:
SwsContext *SWS = nullptr;
int Delay = 0;
int DelayCounter = 0;
int InitialDecode = 1;
bool PAFFAdjusted = false;
int LastFrameHeight = -1;
int LastFrameWidth = -1;
AVPixelFormat LastFramePixelFormat = AV_PIX_FMT_NONE;
int TargetHeight = -1;
int TargetWidth = -1;
std::vector<AVPixelFormat> TargetPixelFormats;
int TargetResizer = 0;
AVPixelFormat OutputFormat = AV_PIX_FMT_NONE;
AVColorRange OutputColorRange = AVCOL_RANGE_UNSPECIFIED;
AVColorSpace OutputColorSpace = AVCOL_SPC_UNSPECIFIED;
bool OutputColorRangeSet = false;
bool OutputColorSpaceSet = false;
int OutputColorPrimaries = -1;
int OutputTransferCharateristics = -1;
int OutputChromaLocation = -1;
bool InputFormatOverridden = false;
AVPixelFormat InputFormat = AV_PIX_FMT_NONE;
AVColorRange InputColorRange = AVCOL_RANGE_UNSPECIFIED;
AVColorSpace InputColorSpace = AVCOL_SPC_UNSPECIFIED;
uint8_t *SWSFrameData[4] = {};
int SWSFrameLinesize[4] = {};
void DetectInputFormat();
bool HasPendingDelayedFrames();
FFMS_VideoProperties VP = {};
FFMS_Frame LocalFrame = {};
AVFrame *DecodeFrame = nullptr;
AVFrame *LastDecodedFrame = nullptr;
int LastFrameNum = 0;
FFMS_Index &Index;
FFMS_Track Frames;
int VideoTrack;
int CurrentFrame = 1;
int DecodingThreads;
AVCodecContext *CodecContext = nullptr;
AVFormatContext *FormatContext = nullptr;
int SeekMode;
bool SeekByPos = false;
int PosOffset = 0;
void ReAdjustOutputFormat(AVFrame *Frame);
FFMS_Frame *OutputFrame(AVFrame *Frame);
void SetVideoProperties();
bool DecodePacket(AVPacket *Packet);
void DecodeNextFrame(int64_t &PTS, int64_t &Pos);
bool SeekTo(int n, int SeekOffset);
int Seek(int n);
int ReadFrame(AVPacket *pkt);
void Free();
static void SanityCheckFrameForData(AVFrame *Frame);
public:
FFMS_VideoSource(const char *SourceFile, FFMS_Index &Index, int Track, int Threads, int SeekMode);
~FFMS_VideoSource();
const FFMS_VideoProperties& GetVideoProperties() { return VP; }
FFMS_Track *GetTrack() { return &Frames; }
FFMS_Frame *GetFrame(int n);
void GetFrameCheck(int n);
FFMS_Frame *GetFrameByTime(double Time);
void SetOutputFormat(const AVPixelFormat *TargetFormats, int Width, int Height, int Resizer);
void ResetOutputFormat();
void SetInputFormat(int ColorSpace, int ColorRange, AVPixelFormat Format);
void ResetInputFormat();
};
#endif

View file

@ -0,0 +1,263 @@
// Copyright (c) 2007-2015 The FFmpegSource Project
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "videoutils.h"
#include <algorithm>
#include <cmath>
/* if you have this, we'll assume you have a new enough libavutil too */
extern "C" {
#include <libavutil/opt.h>
}
SwsContext *GetSwsContext(int SrcW, int SrcH, AVPixelFormat SrcFormat, int SrcColorSpace, int SrcColorRange, int DstW, int DstH, AVPixelFormat DstFormat, int DstColorSpace, int DstColorRange, int64_t Flags) {
Flags |= SWS_FULL_CHR_H_INT | SWS_FULL_CHR_H_INP | SWS_ACCURATE_RND;
SwsContext *Context = sws_alloc_context();
if (!Context) return nullptr;
// 0 = limited range, 1 = full range
int SrcRange = SrcColorRange == AVCOL_RANGE_JPEG;
if (SrcColorRange == AVCOL_RANGE_UNSPECIFIED)
SrcRange = (GuessCSType(SrcFormat) != cYUV);
int DstRange = DstColorRange == AVCOL_RANGE_JPEG;
if (DstColorRange == AVCOL_RANGE_UNSPECIFIED)
DstRange = (GuessCSType(DstFormat) != cYUV);
av_opt_set_int(Context, "sws_flags", Flags, 0);
av_opt_set_int(Context, "srcw", SrcW, 0);
av_opt_set_int(Context, "srch", SrcH, 0);
av_opt_set_int(Context, "dstw", DstW, 0);
av_opt_set_int(Context, "dsth", DstH, 0);
av_opt_set_int(Context, "src_range", SrcRange, 0);
av_opt_set_int(Context, "dst_range", DstRange, 0);
av_opt_set_int(Context, "src_format", SrcFormat, 0);
av_opt_set_int(Context, "dst_format", DstFormat, 0);
sws_setColorspaceDetails(Context,
sws_getCoefficients(SrcColorSpace), SrcRange,
sws_getCoefficients(DstColorSpace), DstRange,
0, 1 << 16, 1 << 16);
if (sws_init_context(Context, nullptr, nullptr) < 0) {
sws_freeContext(Context);
return nullptr;
}
return Context;
}
/***************************
**
** Two functions for making FFMS pretend it's not quite as VFR-based as it really is.
**
***************************/
// attempt to correct framerate to a common fraction if close to one
void CorrectRationalFramerate(int *Num, int *Den) {
// Make sure fps is a normalized rational number
av_reduce(Den, Num, *Den, *Num, INT_MAX);
const double fps = static_cast<double>(*Num) / *Den;
const int fpsList[] = { 24, 25, 30, 48, 50, 60, 100, 120 };
for (size_t i = 0; i < sizeof(fpsList) / sizeof(fpsList[0]); i++) {
const double delta = (fpsList[i] - static_cast<double>(fpsList[i]) / 1.001) / 2.0;
if (fabs(fps - fpsList[i]) < delta) {
*Num = fpsList[i];
*Den = 1;
break;
} else if ((fpsList[i] % 25) && (fabs(fps - static_cast<double>(fpsList[i]) / 1.001) < delta)) {
*Num = fpsList[i] * 1000;
*Den = 1001;
break;
}
}
}
// correct the timebase if it is invalid
void CorrectTimebase(FFMS_VideoProperties *VP, FFMS_TrackTimeBase *TTimebase) {
double Timebase = (double)TTimebase->Num / TTimebase->Den;
double FPS = (double)VP->FPSNumerator / VP->FPSDenominator;
if ((1000 / Timebase) / FPS < 1) {
TTimebase->Den = VP->FPSNumerator;
TTimebase->Num = (int64_t)VP->FPSDenominator * 1000;
}
}
/***************************
**
** Since avcodec_find_best_pix_fmt() is broken, we have our own implementation of it here.
**
***************************/
BCSType GuessCSType(AVPixelFormat p) {
// guessing the colorspace type from the name is kinda hackish but libav doesn't export this kind of metadata
// special case since pal8 is assumed to be rgb32
if (p == AV_PIX_FMT_PAL8)
return cRGB;
if (av_pix_fmt_desc_get(p)->flags & AV_PIX_FMT_FLAG_HWACCEL)
return cUNUSABLE;
if (av_pix_fmt_desc_get(p)->flags & AV_PIX_FMT_FLAG_PAL)
return cUNUSABLE;
if (av_pix_fmt_desc_get(p)->flags & AV_PIX_FMT_FLAG_RGB)
return cRGB;
if (av_pix_fmt_desc_get(p)->nb_components <= 2)
return cGRAY;
if (av_pix_fmt_desc_get(p)->nb_components >= 3)
return cYUV;
return cUNUSABLE; // should never come here
}
struct LossAttributes {
AVPixelFormat Format;
int ChromaUndersampling;
int ChromaOversampling;
int DepthDifference;
int CSLoss; // 0 = no difference, 1 = unused, 2 = full conversion required, 3 = alpha loss, 4 = full conversion plus alpha loss, 5 = complete color loss
int CSGain; // alpha plane added, gray converted to yuv/rgb
};
static int GetPseudoDepth(const AVPixFmtDescriptor &Desc) {
// Comparing the pseudo depth makes sure that rgb565-ish formats get selected over rgb555-ish ones
int depth = 0;
for (int i = 0; i < Desc.nb_components; i++)
depth = FFMAX(depth, Desc.comp[i].depth);
return depth;
}
static LossAttributes CalculateLoss(AVPixelFormat Dst, AVPixelFormat Src) {
const AVPixFmtDescriptor &SrcDesc = *av_pix_fmt_desc_get(Src);
const AVPixFmtDescriptor &DstDesc = *av_pix_fmt_desc_get(Dst);
BCSType SrcCS = GuessCSType(Src);
BCSType DstCS = GuessCSType(Dst);
LossAttributes Loss;
Loss.Format = Dst;
Loss.DepthDifference = GetPseudoDepth(DstDesc) - GetPseudoDepth(SrcDesc);;
Loss.ChromaOversampling = FFMAX(0, SrcDesc.log2_chroma_h - DstDesc.log2_chroma_h) + FFMAX(0, SrcDesc.log2_chroma_w - DstDesc.log2_chroma_w);
Loss.ChromaUndersampling = FFMAX(0, DstDesc.log2_chroma_h - SrcDesc.log2_chroma_h) + FFMAX(0, DstDesc.log2_chroma_w - SrcDesc.log2_chroma_w);
Loss.CSGain = 0;
if (SrcCS == DstCS) {
Loss.CSLoss = 0;
} else if (SrcCS == cGRAY) {
Loss.CSGain = 1;
Loss.ChromaOversampling = 0;
Loss.ChromaUndersampling = 0;
Loss.CSLoss = 0;
} else if (DstCS == cGRAY) {
Loss.ChromaOversampling = 0;
Loss.ChromaUndersampling = 0;
Loss.CSLoss = 5;
} else {
Loss.CSLoss = 2;
}
if (Loss.CSLoss < 3 && (DstDesc.nb_components == SrcDesc.nb_components - 1)) {
if (Loss.CSLoss == 2)
Loss.CSLoss = 4;
else
Loss.CSLoss = 3;
}
// Added alpha plane
if (Loss.CSLoss == 0 && (SrcDesc.nb_components == DstDesc.nb_components - 1)) {
Loss.CSGain = 1;
}
return Loss;
}
AVPixelFormat FindBestPixelFormat(const std::vector<AVPixelFormat> &Dsts, AVPixelFormat Src) {
// some trivial special cases to make sure there's as little conversion as possible
if (Dsts.empty())
return AV_PIX_FMT_NONE;
if (Dsts.size() == 1)
return Dsts[0];
// is the input in the output?
auto i = std::find(Dsts.begin(), Dsts.end(), Src);
if (i != Dsts.end())
return Src;
// If it's an evil paletted format pretend it's normal RGB when calculating loss
if (Src == AV_PIX_FMT_PAL8)
Src = AV_PIX_FMT_RGB32;
std::vector<AVPixelFormat> OutputDsts;
for (auto DstFmt = Dsts.begin(); DstFmt != Dsts.end(); ++DstFmt) {
// Skip outputing to formwats we can't convert to, this avoids swscale init failures later in the code
if (sws_isSupportedOutput(*DstFmt))
OutputDsts.push_back(*DstFmt);
}
if (OutputDsts.empty())
return AV_PIX_FMT_NONE;
i = OutputDsts.begin();
LossAttributes Loss = CalculateLoss(*i++, Src);
for (; i != OutputDsts.end(); ++i) {
LossAttributes CLoss = CalculateLoss(*i, Src);
if (Loss.CSLoss >= 3 && CLoss.CSLoss < Loss.CSLoss) { // favor the same color format output
Loss = CLoss;
} else if (Loss.DepthDifference >= 0 && CLoss.DepthDifference >= 0) { // focus on chroma undersamling and conversion loss if the target depth has been achieved
if ((CLoss.ChromaUndersampling < Loss.ChromaUndersampling)
|| (CLoss.ChromaUndersampling == Loss.ChromaUndersampling && CLoss.CSLoss < Loss.CSLoss)
|| (CLoss.ChromaUndersampling == Loss.ChromaUndersampling && CLoss.CSLoss == Loss.CSLoss && CLoss.DepthDifference < Loss.DepthDifference)
|| (CLoss.ChromaUndersampling == Loss.ChromaUndersampling && CLoss.CSLoss == Loss.CSLoss
&& CLoss.DepthDifference == Loss.DepthDifference && CLoss.ChromaOversampling < Loss.ChromaOversampling))
Loss = CLoss;
} else { // put priority on reaching the same depth as the input
if ((CLoss.DepthDifference > Loss.DepthDifference)
|| (CLoss.DepthDifference == Loss.DepthDifference && CLoss.ChromaUndersampling < Loss.ChromaUndersampling)
|| (CLoss.DepthDifference == Loss.DepthDifference && CLoss.ChromaUndersampling == Loss.ChromaUndersampling && CLoss.CSLoss < Loss.CSLoss)
|| (CLoss.DepthDifference == Loss.DepthDifference && CLoss.ChromaUndersampling == Loss.ChromaUndersampling
&& CLoss.CSLoss == Loss.CSLoss && CLoss.ChromaOversampling < Loss.ChromaOversampling))
Loss = CLoss;
else if (CLoss.DepthDifference == Loss.DepthDifference && CLoss.ChromaUndersampling == Loss.ChromaUndersampling
&& CLoss.CSLoss == Loss.CSLoss && CLoss.ChromaOversampling == Loss.ChromaOversampling && CLoss.CSGain < Loss.CSGain)
Loss = CLoss;
}
}
return Loss.Format;
}
void ParseVP8(const uint8_t Buf, bool *Invisible, int *PictType) {
*PictType = (Buf & 0x01) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
*Invisible = (*Invisible || !(Buf & 0x10));
}
void ParseVP9(const uint8_t Buf, bool *Invisible, int *PictType)
{
int profile = ((Buf & 0x20) >> 5) | ((Buf & 0x10) >> 3);
int shift = (profile == 3);
if (Buf & (0x8 >> shift)) {
*Invisible = false;
*PictType = AV_PICTURE_TYPE_P;
} else {
*PictType = (Buf & (0x4 >> shift)) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
*Invisible = !(Buf & (0x2 >> shift));
}
}

View file

@ -0,0 +1,55 @@
// Copyright (c) 2007-2015 The FFmpegSource Project
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
extern "C" {
#include <libavutil/mem.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/pixdesc.h>
}
// must be included after ffmpeg headers
#include "ffmscompat.h"
#include <vector>
#include "ffms.h"
enum BCSType {
cGRAY,
cYUV,
cRGB,
cUNUSABLE
};
// swscale and pp-related functions
SwsContext *GetSwsContext(int SrcW, int SrcH, AVPixelFormat SrcFormat, int SrcColorSpace, int SrcColorRange, int DstW, int DstH, AVPixelFormat DstFormat, int DstColorSpace, int DstColorRange, int64_t Flags);
BCSType GuessCSType(AVPixelFormat p);
// timebase-related functions
void CorrectRationalFramerate(int *Num, int *Den);
void CorrectTimebase(FFMS_VideoProperties *VP, FFMS_TrackTimeBase *TTimebase);
// our implementation of avcodec_find_best_pix_fmt()
AVPixelFormat FindBestPixelFormat(const std::vector<AVPixelFormat> &Dsts, AVPixelFormat Src);
// handling of alt-refs in VP8 and VP9
void ParseVP8(const uint8_t Buf, bool *Invisible, int *PictType);
void ParseVP9(const uint8_t Buf, bool *Invisible, int *PictType);

145
ffms2/src/core/zipfile.cpp Normal file
View file

@ -0,0 +1,145 @@
// Copyright (c) 2014 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "zipfile.h"
extern "C" {
#include <libavutil/avutil.h>
}
#include "utils.h"
ZipFile::ZipFile(const char *filename, const char *mode)
: file(filename, mode, FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ)
, is_file(true)
, state(Initial) {
buffer.resize(65536);
z = {};
}
ZipFile::ZipFile()
: is_file(false)
, state(Initial) {
buffer.resize(65536);
z = {};
}
ZipFile::ZipFile(const uint8_t *in_buffer, const size_t size)
: index_buffer(in_buffer, in_buffer + size)
, is_file(false)
, state(Initial) {
z = {};
}
ZipFile::~ZipFile() {
if (state == Inflate)
inflateEnd(&z);
if (state == Deflate)
deflateEnd(&z);
}
void ZipFile::Read(void *data, size_t size) {
if (state == Deflate) {
deflateEnd(&z);
state = Initial;
}
if (state != Inflate) {
if (inflateInit(&z) != Z_OK)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to initialize zlib");
state = Inflate;
}
z.next_out = static_cast<unsigned char *>(data);
z.avail_out = size;
if (!z.avail_in && !is_file) {
z.next_in = reinterpret_cast<Bytef*>(&index_buffer[0]);
z.avail_in = index_buffer.size();
}
do {
if (!z.avail_in && is_file) {
z.next_in = reinterpret_cast<Bytef*>(&buffer[0]);
z.avail_in = file.Read(&buffer[0], buffer.size());
}
if (!z.avail_in) {
if (!is_file)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to read data: Buffer is empty");
else if (!file.Tell())
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to read data: File is empty");
}
switch (inflate(&z, Z_SYNC_FLUSH)) {
case Z_NEED_DICT:
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to read data: Dictionary error.");
case Z_DATA_ERROR:
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to read data: Data error.");
case Z_MEM_ERROR:
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to read data: Memory error.");
case Z_STREAM_END:
if (z.avail_out > 0)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to read data: Stream ended early");
}
} while (z.avail_out);
}
int ZipFile::Write(const void *data, size_t size) {
if (state == Inflate) {
inflateEnd(&z);
state = Initial;
}
if (state != Deflate) {
if (deflateInit(&z, 5) != Z_OK)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_FILE_READ, "Failed to initialize zlib");
state = Deflate;
}
z.next_in = static_cast<unsigned char *>(const_cast<void *>(data));
z.avail_in = size;
int ret = 0;
do {
z.avail_out = buffer.size();
z.next_out = reinterpret_cast<Bytef*>(&buffer[0]);
ret = deflate(&z, size > 0 ? Z_NO_FLUSH : Z_FINISH);
uInt written = buffer.size() - z.avail_out;
if (written) {
if (is_file)
file.Write(&buffer[0], written);
else
index_buffer.insert(index_buffer.end(), &buffer[0], &buffer[written]);
}
} while (z.avail_out == 0);
return ret;
}
void ZipFile::Finish() {
while (Write(nullptr, 0) != Z_STREAM_END);
deflateEnd(&z);
state = Initial;
}
uint8_t *ZipFile::GetBuffer(size_t *size) {
uint8_t *ret = (uint8_t *)av_malloc(index_buffer.size());
if (ret == nullptr)
throw FFMS_Exception(FFMS_ERROR_PARSER, FFMS_ERROR_ALLOCATION_FAILED, "Failed to allocate index return buffer");
memcpy(ret, reinterpret_cast<uint8_t *>(&index_buffer[0]), index_buffer.size());
*size = index_buffer.size();
return ret;
}

65
ffms2/src/core/zipfile.h Normal file
View file

@ -0,0 +1,65 @@
// Copyright (c) 2014 Thomas Goyne <tgoyne@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef ZIPFILE_H
#define ZIPFILE_H
#include "filehandle.h"
#include <vector>
#include <zlib.h>
class ZipFile {
FileHandle file;
std::vector<char> buffer;
std::vector<uint8_t> index_buffer;
bool is_file;
z_stream z;
enum {
Initial,
Inflate,
Deflate
} state;
public:
ZipFile(const char *filename, const char *mode);
ZipFile(const uint8_t *in_buffer, const size_t size);
ZipFile();
~ZipFile();
void Read(void *buffer, size_t size);
int Write(const void *buffer, size_t size);
void Finish();
uint8_t *GetBuffer(size_t *size);
template<typename T>
T Read() {
T ret = T();
Read(&ret, sizeof(T));
return ret;
}
template<typename T>
void Write(T const& value) {
Write(&value, sizeof value);
}
};
#endif

View file

@ -0,0 +1,285 @@
// Copyright (c) 2008-2009 Karl Blomster
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "ffms.h"
#ifdef _WIN32
#include "vsutf16.h"
#endif
#include <cinttypes>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <stdexcept>
namespace {
long long IndexMask = 0;
int Verbose = 0;
int IgnoreErrors = 0;
bool Overwrite = false;
bool PrintProgress = true;
bool WriteTC = false;
bool WriteKF = false;
std::string InputFile;
std::string CacheFile;
struct Error {
std::string msg;
Error(const char *msg) : msg(msg) {}
Error(const char *msg, FFMS_ErrorInfo const& e) : msg(msg) {
this->msg.append(e.Buffer);
}
};
void PrintUsage() {
std::cout <<
"FFmpegSource2 indexing app\n"
"Usage: ffmsindex [options] inputfile [outputfile]\n"
"If no output filename is specified, inputfile.ffindex will be used.\n"
"\n"
"Options:\n"
"-f Force overwriting of existing index file, if any (default: no)\n"
"-v Set FFmpeg verbosity level. Can be repeated for more verbosity. (default: no messages printed)\n"
"-p Disable progress reporting. (default: progress reporting on)\n"
"-c Write timecodes for all video tracks to outputfile_track00.tc.txt (default: no)\n"
"-k Write keyframes for all video tracks to outputfile_track00.kf.txt (default: no)\n"
"-t N Set the audio indexing mask to N (-1 means index all tracks, 0 means index none, default: 0)\n"
"-s N Set audio decoding error handling. See the documentation for details. (default: 0)\n"
<< std::endl;
}
void ParseCMDLine(int argc, const char *argv[]) {
for (int i = 1; i < argc; ++i) {
const char *Option = argv[i];
#define OPTION_ARG(dst, flag, parse) try { dst = parse(i + 1 < argc ? argv[i+1] : throw Error("Error: missing argument for -" flag)); i++; } catch (std::logic_error &) { throw Error("Error: invalid argument specified for -" flag); }
if (!strcmp(Option, "-f")) {
Overwrite = true;
} else if (!strcmp(Option, "-v")) {
Verbose++;
} else if (!strcmp(Option, "-p")) {
PrintProgress = false;
} else if (!strcmp(Option, "-c")) {
WriteTC = true;
} else if (!strcmp(Option, "-k")) {
WriteKF = true;
} else if (!strcmp(Option, "-t")) {
OPTION_ARG(IndexMask, "t", std::stoll);
} else if (!strcmp(Option, "-s")) {
OPTION_ARG(IgnoreErrors, "s", std::stoi);
} else if (InputFile.empty()) {
InputFile = Option;
} else if (CacheFile.empty()) {
CacheFile = Option;
} else {
std::cout << "Warning: ignoring unknown option " << Option << std::endl;
}
}
if (IgnoreErrors < 0 || IgnoreErrors > 3)
throw Error("Error: invalid error handling mode");
if (InputFile.empty())
throw Error("Error: no input file specified");
if (CacheFile.empty()) {
CacheFile = InputFile;
CacheFile.append(".ffindex");
}
}
int FFMS_CC UpdateProgress(int64_t Current, int64_t Total, void *Private) {
if (!PrintProgress)
return 0;
int Percentage = int((double(Current) / double(Total)) * 100);
if (Private) {
int *LastPercentage = (int *)Private;
if (Percentage <= *LastPercentage)
return 0;
*LastPercentage = Percentage;
}
std::cout << "Indexing, please wait... " << Percentage << "% \r" << std::flush;
return 0;
}
std::string DumpFilename(FFMS_Track *Track, int TrackNum, const char *Suffix) {
if (FFMS_GetTrackType(Track) != FFMS_TYPE_VIDEO || !FFMS_GetNumFrames(Track))
return "";
char tn[11];
snprintf(tn, 11, "%02" PRIu32"", (uint32_t) TrackNum);
return CacheFile + "_track" + tn + Suffix;
}
void DoIndexing() {
char ErrorMsg[1024];
FFMS_ErrorInfo E;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
int Progress = 0;
FFMS_Index *Index = FFMS_ReadIndex(CacheFile.c_str(), &E);
if (Index) {
FFMS_DestroyIndex(Index);
if (!Overwrite)
throw Error("Error: index file already exists, use -f if you are sure you want to overwrite it.");
}
UpdateProgress(0, 100, nullptr);
FFMS_Indexer *Indexer = FFMS_CreateIndexer(InputFile.c_str(), &E);
if (Indexer == nullptr)
throw Error("\nFailed to initialize indexing: ", E);
FFMS_SetProgressCallback(Indexer, UpdateProgress, &Progress);
// Treat -1 as meaning track numbers above sizeof(long long) * 8 too, dumping implies indexing
if (IndexMask == -1)
FFMS_TrackTypeIndexSettings(Indexer, FFMS_TYPE_AUDIO, 1, 0);
// Apply attributes to remaining tracks (will set the attributes again on some tracks)
for (int i = 0; i < static_cast<int>(sizeof(IndexMask) * 8); i++) {
if ((IndexMask >> i) & 1)
FFMS_TrackIndexSettings(Indexer, i, 1, 0);
}
Index = FFMS_DoIndexing2(Indexer, IgnoreErrors, &E);
// The indexer is always freed
Indexer = nullptr;
if (Index == nullptr)
throw Error("\nIndexing error: ", E);
UpdateProgress(100, 100, nullptr);
std::cout << std::endl;
if (WriteTC) {
if (PrintProgress)
std::cout << "Writing timecodes... ";
int NumTracks = FFMS_GetNumTracks(Index);
for (int t = 0; t < NumTracks; t++) {
FFMS_Track *Track = FFMS_GetTrackFromIndex(Index, t);
std::string Filename = DumpFilename(Track, t, ".tc.txt");
if (!Filename.empty()) {
if (FFMS_WriteTimecodes(Track, Filename.c_str(), &E))
std::cout << std::endl << "Failed to write timecodes file "
<< Filename << ": " << E.Buffer << std::endl;
}
}
if (PrintProgress)
std::cout << "done." << std::endl;
}
if (WriteKF) {
if (PrintProgress)
std::cout << "Writing keyframes... ";
int NumTracks = FFMS_GetNumTracks(Index);
for (int t = 0; t < NumTracks; t++) {
FFMS_Track *Track = FFMS_GetTrackFromIndex(Index, t);
std::string Filename = DumpFilename(Track, t, ".kf.txt");
if (!Filename.empty()) {
std::ofstream kf(Filename.c_str());
kf << "# keyframe format v1\n"
"fps 0\n";
int FrameCount = FFMS_GetNumFrames(Track);
for (int CurFrameNum = 0; CurFrameNum < FrameCount; CurFrameNum++) {
if (FFMS_GetFrameInfo(Track, CurFrameNum)->KeyFrame)
kf << CurFrameNum << "\n";
}
}
}
if (PrintProgress)
std::cout << "done. " << std::endl;
}
if (PrintProgress)
std::cout << "Writing index... ";
int error = FFMS_WriteIndex(CacheFile.c_str(), Index, &E);
FFMS_DestroyIndex(Index);
if (error)
throw Error("Error writing index: ", E);
if (PrintProgress)
std::cout << "done." << std::endl;
}
} // namespace {
#ifdef _WIN32
int wmain(int argc, const wchar_t *_argv[]) {
std::vector<const char *> StringPtrs(argc);
std::vector<std::string> StringStorage(argc);
for (int i = 0; i < argc; i++) {
StringStorage[i] = utf16_to_utf8(_argv[i]);
StringPtrs[i] = StringStorage[i].c_str();
}
const char **argv = StringPtrs.data();
#else
int main(int argc, const char *argv[]) {
#endif
try {
if (argc <= 1) {
PrintUsage();
return 0;
}
ParseCMDLine(argc, argv);
} catch (Error const& e) {
std::cout << e.msg << std::endl;
return 1;
}
FFMS_Init(0, 0);
switch (Verbose) {
case 0: FFMS_SetLogLevel(FFMS_LOG_QUIET); break;
case 1: FFMS_SetLogLevel(FFMS_LOG_WARNING); break;
case 2: FFMS_SetLogLevel(FFMS_LOG_INFO); break;
case 3: FFMS_SetLogLevel(FFMS_LOG_VERBOSE); break;
default: FFMS_SetLogLevel(FFMS_LOG_DEBUG); // if user used -v 4 or more times, he deserves the spam
}
try {
DoIndexing();
} catch (Error const& e) {
std::cout << e.msg << std::endl;
FFMS_Deinit();
return 1;
}
FFMS_Deinit();
return 0;
}

46
ffms2/src/index/vsutf16.h Normal file
View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2017 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth 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.
*
* VapourSynth 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 VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef VSUTF16_H
#define VSUTF16_H
#include <string>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
static std::string utf16_to_utf8(const std::wstring &wstr) {
int required_size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
std::string buffer;
buffer.resize(required_size - 1);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), static_cast<int>(wstr.size()), &buffer[0], required_size, nullptr, nullptr);
return buffer;
}
static std::wstring utf16_from_utf8(const std::string &str) {
int required_size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
std::wstring wbuffer;
wbuffer.resize(required_size - 1);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), static_cast<int>(str.size()), &wbuffer[0], required_size);
return wbuffer;
}
#endif

View file

@ -0,0 +1,174 @@
/*****************************************************************************
* Copyright (c) 2012-2015 Fredrik Mellbin
* --- Legal stuff ---
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*****************************************************************************/
#ifndef VSHELPER_H
#define VSHELPER_H
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#ifdef _WIN32
#include <malloc.h>
#endif
#include "VapourSynth.h"
/* Visual Studio doesn't recognize inline in c mode */
#if defined(_MSC_VER) && !defined(__cplusplus)
#define inline _inline
#endif
/* A kinda portable definition of the C99 restrict keyword (or its inofficial C++ equivalent) */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* Available in C99 */
#define VS_RESTRICT restrict
#elif defined(__cplusplus) || defined(_MSC_VER) /* Almost all relevant C++ compilers support it so just assume it works */
#define VS_RESTRICT __restrict
#else /* Not supported */
#define VS_RESTRICT
#endif
#ifdef _WIN32
#define VS_ALIGNED_MALLOC(pptr, size, alignment) do { *(pptr) = _aligned_malloc((size), (alignment)); } while (0)
#define VS_ALIGNED_FREE(ptr) do { _aligned_free((ptr)); } while (0)
#else
#define VS_ALIGNED_MALLOC(pptr, size, alignment) do { if(posix_memalign((void**)(pptr), (alignment), (size))) *((void**)pptr) = NULL; } while (0)
#define VS_ALIGNED_FREE(ptr) do { free((ptr)); } while (0)
#endif
#define VSMAX(a,b) ((a) > (b) ? (a) : (b))
#define VSMIN(a,b) ((a) > (b) ? (b) : (a))
#ifdef __cplusplus
/* A nicer templated malloc for all the C++ users out there */
#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
template<typename T=void>
#else
template<typename T>
#endif
static inline T* vs_aligned_malloc(size_t size, size_t alignment) {
#ifdef _WIN32
return (T*)_aligned_malloc(size, alignment);
#else
void *tmp = NULL;
if (posix_memalign(&tmp, alignment, size))
tmp = 0;
return (T*)tmp;
#endif
}
static inline void vs_aligned_free(void *ptr) {
VS_ALIGNED_FREE(ptr);
}
#endif /* __cplusplus */
/* convenience function for checking if the format never changes between frames */
static inline int isConstantFormat(const VSVideoInfo *vi) {
return vi->height > 0 && vi->width > 0 && vi->format;
}
/* convenience function to check for if two clips have the same format (unknown/changeable will be considered the same too) */
static inline int isSameFormat(const VSVideoInfo *v1, const VSVideoInfo *v2) {
return v1->height == v2->height && v1->width == v2->width && v1->format == v2->format;
}
/* multiplies and divides a rational number, such as a frame duration, in place and reduces the result */
static inline void muldivRational(int64_t *num, int64_t *den, int64_t mul, int64_t div) {
/* do nothing if the rational number is invalid */
if (!*den)
return;
/* nobody wants to accidentally divide by zero */
assert(div);
int64_t a, b;
*num *= mul;
*den *= div;
a = *num;
b = *den;
while (b != 0) {
int64_t t = a;
a = b;
b = t % b;
}
if (a < 0)
a = -a;
*num /= a;
*den /= a;
}
/* reduces a rational number */
static inline void vs_normalizeRational(int64_t *num, int64_t *den) {
muldivRational(num, den, 1, 1);
}
/* add two rational numbers and reduces the result */
static inline void vs_addRational(int64_t *num, int64_t *den, int64_t addnum, int64_t addden) {
/* do nothing if the rational number is invalid */
if (!*den)
return;
/* nobody wants to accidentally add an invalid rational number */
assert(addden);
if (*den == addden) {
*num += addnum;
} else {
int64_t temp = addden;
addnum *= *den;
addden *= *den;
*num *= temp;
*den *= temp;
*num += addnum;
vs_normalizeRational(num, den);
}
}
/* converts an int64 to int with saturation, useful to silence warnings when reading int properties among other things */
static inline int int64ToIntS(int64_t i) {
if (i > INT_MAX)
return INT_MAX;
else if (i < INT_MIN)
return INT_MIN;
else return (int)i;
}
static inline void vs_bitblt(void *dstp, int dst_stride, const void *srcp, int src_stride, size_t row_size, size_t height) {
if (height) {
if (src_stride == dst_stride && src_stride == (int)row_size) {
memcpy(dstp, srcp, row_size * height);
} else {
const uint8_t *srcp8 = (const uint8_t *)srcp;
uint8_t *dstp8 = (uint8_t *)dstp;
size_t i;
for (i = 0; i < height; i++) {
memcpy(dstp8, srcp8, row_size);
srcp8 += src_stride;
dstp8 += dst_stride;
}
}
}
}
/* check if the frame dimensions are valid for a given format */
/* returns non-zero for valid width and height */
static inline int areValidDimensions(const VSFormat *fi, int width, int height) {
return !(width % (1 << fi->subSamplingW) || height % (1 << fi->subSamplingH));
}
/* Visual Studio doesn't recognize inline in c mode */
#if defined(_MSC_VER) && !defined(__cplusplus)
#undef inline
#endif
#endif

View file

@ -0,0 +1,342 @@
/*
* Copyright (c) 2012-2017 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth 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.
*
* VapourSynth 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 VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef VAPOURSYNTH_H
#define VAPOURSYNTH_H
#include <stdint.h>
#define VAPOURSYNTH_API_MAJOR 3
#define VAPOURSYNTH_API_MINOR 5
#define VAPOURSYNTH_API_VERSION ((VAPOURSYNTH_API_MAJOR << 16) | (VAPOURSYNTH_API_MINOR))
/* Convenience for C++ users. */
#ifdef __cplusplus
# define VS_EXTERN_C extern "C"
# if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
# define VS_NOEXCEPT noexcept
# else
# define VS_NOEXCEPT
# endif
#else
# define VS_EXTERN_C
# define VS_NOEXCEPT
#endif
#if defined(_WIN32) && !defined(_WIN64)
# define VS_CC __stdcall
#else
# define VS_CC
#endif
/* And now for some symbol hide-and-seek... */
#if defined(_WIN32) /* Windows being special */
# define VS_EXTERNAL_API(ret) VS_EXTERN_C __declspec(dllexport) ret VS_CC
#elif defined(__GNUC__) && __GNUC__ >= 4
# define VS_EXTERNAL_API(ret) VS_EXTERN_C __attribute__((visibility("default"))) ret VS_CC
#else
# define VS_EXTERNAL_API(ret) VS_EXTERN_C ret VS_CC
#endif
#if !defined(VS_CORE_EXPORTS) && defined(_WIN32)
# define VS_API(ret) VS_EXTERN_C __declspec(dllimport) ret VS_CC
#else
# define VS_API(ret) VS_EXTERNAL_API(ret)
#endif
typedef struct VSFrameRef VSFrameRef;
typedef struct VSNodeRef VSNodeRef;
typedef struct VSCore VSCore;
typedef struct VSPlugin VSPlugin;
typedef struct VSNode VSNode;
typedef struct VSFuncRef VSFuncRef;
typedef struct VSMap VSMap;
typedef struct VSAPI VSAPI;
typedef struct VSFrameContext VSFrameContext;
typedef enum VSColorFamily {
/* all planar formats */
cmGray = 1000000,
cmRGB = 2000000,
cmYUV = 3000000,
cmYCoCg = 4000000,
/* special for compatibility */
cmCompat = 9000000
} VSColorFamily;
typedef enum VSSampleType {
stInteger = 0,
stFloat = 1
} VSSampleType;
/* The +10 is so people won't be using the constants interchangably "by accident" */
typedef enum VSPresetFormat {
pfNone = 0,
pfGray8 = cmGray + 10,
pfGray16,
pfGrayH,
pfGrayS,
pfYUV420P8 = cmYUV + 10,
pfYUV422P8,
pfYUV444P8,
pfYUV410P8,
pfYUV411P8,
pfYUV440P8,
pfYUV420P9,
pfYUV422P9,
pfYUV444P9,
pfYUV420P10,
pfYUV422P10,
pfYUV444P10,
pfYUV420P16,
pfYUV422P16,
pfYUV444P16,
pfYUV444PH,
pfYUV444PS,
pfYUV420P12,
pfYUV422P12,
pfYUV444P12,
pfYUV420P14,
pfYUV422P14,
pfYUV444P14,
pfRGB24 = cmRGB + 10,
pfRGB27,
pfRGB30,
pfRGB48,
pfRGBH,
pfRGBS,
/* special for compatibility, if you implement these in any filter I'll personally kill you */
/* I'll also change their ids around to break your stuff regularly */
pfCompatBGR32 = cmCompat + 10,
pfCompatYUY2
} VSPresetFormat;
typedef enum VSFilterMode {
fmParallel = 100, /* completely parallel execution */
fmParallelRequests = 200, /* for filters that are serial in nature but can request one or more frames they need in advance */
fmUnordered = 300, /* for filters that modify their internal state every request */
fmSerial = 400 /* for source filters and compatibility with other filtering architectures */
} VSFilterMode;
typedef struct VSFormat {
char name[32];
int id;
int colorFamily; /* see VSColorFamily */
int sampleType; /* see VSSampleType */
int bitsPerSample; /* number of significant bits */
int bytesPerSample; /* actual storage is always in a power of 2 and the smallest possible that can fit the number of bits used per sample */
int subSamplingW; /* log2 subsampling factor, applied to second and third plane */
int subSamplingH;
int numPlanes; /* implicit from colorFamily */
} VSFormat;
typedef enum VSNodeFlags {
nfNoCache = 1,
nfIsCache = 2,
nfMakeLinear = 4 /* api 3.3 */
} VSNodeFlags;
typedef enum VSPropTypes {
ptUnset = 'u',
ptInt = 'i',
ptFloat = 'f',
ptData = 's',
ptNode = 'c',
ptFrame = 'v',
ptFunction = 'm'
} VSPropTypes;
typedef enum VSGetPropErrors {
peUnset = 1,
peType = 2,
peIndex = 4
} VSGetPropErrors;
typedef enum VSPropAppendMode {
paReplace = 0,
paAppend = 1,
paTouch = 2
} VSPropAppendMode;
typedef struct VSCoreInfo {
const char *versionString;
int core;
int api;
int numThreads;
int64_t maxFramebufferSize;
int64_t usedFramebufferSize;
} VSCoreInfo;
typedef struct VSVideoInfo {
const VSFormat *format;
int64_t fpsNum;
int64_t fpsDen;
int width;
int height;
int numFrames; /* api 3.2 - no longer allowed to be 0 */
int flags;
} VSVideoInfo;
typedef enum VSActivationReason {
arInitial = 0,
arFrameReady = 1,
arAllFramesReady = 2,
arError = -1
} VSActivationReason;
typedef enum VSMessageType {
mtDebug = 0,
mtWarning = 1,
mtCritical = 2,
mtFatal = 3
} VSMessageType;
/* core entry point */
typedef const VSAPI *(VS_CC *VSGetVapourSynthAPI)(int version);
/* plugin function and filter typedefs */
typedef void (VS_CC *VSPublicFunction)(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi);
typedef void (VS_CC *VSRegisterFunction)(const char *name, const char *args, VSPublicFunction argsFunc, void *functionData, VSPlugin *plugin);
typedef void (VS_CC *VSConfigPlugin)(const char *identifier, const char *defaultNamespace, const char *name, int apiVersion, int readonly, VSPlugin *plugin);
typedef void (VS_CC *VSInitPlugin)(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin);
typedef void (VS_CC *VSFreeFuncData)(void *userData);
typedef void (VS_CC *VSFilterInit)(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi);
typedef const VSFrameRef *(VS_CC *VSFilterGetFrame)(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi);
typedef void (VS_CC *VSFilterFree)(void *instanceData, VSCore *core, const VSAPI *vsapi);
/* other */
typedef void (VS_CC *VSFrameDoneCallback)(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg);
typedef void (VS_CC *VSMessageHandler)(int msgType, const char *msg, void *userData);
struct VSAPI {
VSCore *(VS_CC *createCore)(int threads) VS_NOEXCEPT;
void (VS_CC *freeCore)(VSCore *core) VS_NOEXCEPT;
const VSCoreInfo *(VS_CC *getCoreInfo)(VSCore *core) VS_NOEXCEPT;
const VSFrameRef *(VS_CC *cloneFrameRef)(const VSFrameRef *f) VS_NOEXCEPT;
VSNodeRef *(VS_CC *cloneNodeRef)(VSNodeRef *node) VS_NOEXCEPT;
VSFuncRef *(VS_CC *cloneFuncRef)(VSFuncRef *f) VS_NOEXCEPT;
void (VS_CC *freeFrame)(const VSFrameRef *f) VS_NOEXCEPT;
void (VS_CC *freeNode)(VSNodeRef *node) VS_NOEXCEPT;
void (VS_CC *freeFunc)(VSFuncRef *f) VS_NOEXCEPT;
VSFrameRef *(VS_CC *newVideoFrame)(const VSFormat *format, int width, int height, const VSFrameRef *propSrc, VSCore *core) VS_NOEXCEPT;
VSFrameRef *(VS_CC *copyFrame)(const VSFrameRef *f, VSCore *core) VS_NOEXCEPT;
void (VS_CC *copyFrameProps)(const VSFrameRef *src, VSFrameRef *dst, VSCore *core) VS_NOEXCEPT;
void (VS_CC *registerFunction)(const char *name, const char *args, VSPublicFunction argsFunc, void *functionData, VSPlugin *plugin) VS_NOEXCEPT;
VSPlugin *(VS_CC *getPluginById)(const char *identifier, VSCore *core) VS_NOEXCEPT;
VSPlugin *(VS_CC *getPluginByNs)(const char *ns, VSCore *core) VS_NOEXCEPT;
VSMap *(VS_CC *getPlugins)(VSCore *core) VS_NOEXCEPT;
VSMap *(VS_CC *getFunctions)(VSPlugin *plugin) VS_NOEXCEPT;
void (VS_CC *createFilter)(const VSMap *in, VSMap *out, const char *name, VSFilterInit init, VSFilterGetFrame getFrame, VSFilterFree free, int filterMode, int flags, void *instanceData, VSCore *core) VS_NOEXCEPT;
void (VS_CC *setError)(VSMap *map, const char *errorMessage) VS_NOEXCEPT; /* use to signal errors outside filter getframe functions */
const char *(VS_CC *getError)(const VSMap *map) VS_NOEXCEPT; /* use to query errors, returns 0 if no error */
void (VS_CC *setFilterError)(const char *errorMessage, VSFrameContext *frameCtx) VS_NOEXCEPT; /* use to signal errors in the filter getframe function */
VSMap *(VS_CC *invoke)(VSPlugin *plugin, const char *name, const VSMap *args) VS_NOEXCEPT;
const VSFormat *(VS_CC *getFormatPreset)(int id, VSCore *core) VS_NOEXCEPT;
const VSFormat *(VS_CC *registerFormat)(int colorFamily, int sampleType, int bitsPerSample, int subSamplingW, int subSamplingH, VSCore *core) VS_NOEXCEPT;
const VSFrameRef *(VS_CC *getFrame)(int n, VSNodeRef *node, char *errorMsg, int bufSize) VS_NOEXCEPT; /* do never use inside a filter's getframe function, for external applications using the core as a library or for requesting frames in a filter constructor */
void (VS_CC *getFrameAsync)(int n, VSNodeRef *node, VSFrameDoneCallback callback, void *userData) VS_NOEXCEPT; /* do never use inside a filter's getframe function, for external applications using the core as a library or for requesting frames in a filter constructor */
const VSFrameRef *(VS_CC *getFrameFilter)(int n, VSNodeRef *node, VSFrameContext *frameCtx) VS_NOEXCEPT; /* only use inside a filter's getframe function */
void (VS_CC *requestFrameFilter)(int n, VSNodeRef *node, VSFrameContext *frameCtx) VS_NOEXCEPT; /* only use inside a filter's getframe function */
void (VS_CC *queryCompletedFrame)(VSNodeRef **node, int *n, VSFrameContext *frameCtx) VS_NOEXCEPT; /* only use inside a filter's getframe function */
void (VS_CC *releaseFrameEarly)(VSNodeRef *node, int n, VSFrameContext *frameCtx) VS_NOEXCEPT; /* only use inside a filter's getframe function */
int (VS_CC *getStride)(const VSFrameRef *f, int plane) VS_NOEXCEPT;
const uint8_t *(VS_CC *getReadPtr)(const VSFrameRef *f, int plane) VS_NOEXCEPT;
uint8_t *(VS_CC *getWritePtr)(VSFrameRef *f, int plane) VS_NOEXCEPT;
VSFuncRef *(VS_CC *createFunc)(VSPublicFunction func, void *userData, VSFreeFuncData free, VSCore *core, const VSAPI *vsapi) VS_NOEXCEPT;
void (VS_CC *callFunc)(VSFuncRef *func, const VSMap *in, VSMap *out, VSCore *core, const VSAPI *vsapi) VS_NOEXCEPT; /* core and vsapi arguments are completely ignored, they only remain to preserve ABI */
/* property access functions */
VSMap *(VS_CC *createMap)(void) VS_NOEXCEPT;
void (VS_CC *freeMap)(VSMap *map) VS_NOEXCEPT;
void (VS_CC *clearMap)(VSMap *map) VS_NOEXCEPT;
const VSVideoInfo *(VS_CC *getVideoInfo)(VSNodeRef *node) VS_NOEXCEPT;
void (VS_CC *setVideoInfo)(const VSVideoInfo *vi, int numOutputs, VSNode *node) VS_NOEXCEPT;
const VSFormat *(VS_CC *getFrameFormat)(const VSFrameRef *f) VS_NOEXCEPT;
int (VS_CC *getFrameWidth)(const VSFrameRef *f, int plane) VS_NOEXCEPT;
int (VS_CC *getFrameHeight)(const VSFrameRef *f, int plane) VS_NOEXCEPT;
const VSMap *(VS_CC *getFramePropsRO)(const VSFrameRef *f) VS_NOEXCEPT;
VSMap *(VS_CC *getFramePropsRW)(VSFrameRef *f) VS_NOEXCEPT;
int (VS_CC *propNumKeys)(const VSMap *map) VS_NOEXCEPT;
const char *(VS_CC *propGetKey)(const VSMap *map, int index) VS_NOEXCEPT;
int (VS_CC *propNumElements)(const VSMap *map, const char *key) VS_NOEXCEPT;
char (VS_CC *propGetType)(const VSMap *map, const char *key) VS_NOEXCEPT;
int64_t(VS_CC *propGetInt)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
double(VS_CC *propGetFloat)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
const char *(VS_CC *propGetData)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
int (VS_CC *propGetDataSize)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
VSNodeRef *(VS_CC *propGetNode)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
const VSFrameRef *(VS_CC *propGetFrame)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
VSFuncRef *(VS_CC *propGetFunc)(const VSMap *map, const char *key, int index, int *error) VS_NOEXCEPT;
int (VS_CC *propDeleteKey)(VSMap *map, const char *key) VS_NOEXCEPT;
int (VS_CC *propSetInt)(VSMap *map, const char *key, int64_t i, int append) VS_NOEXCEPT;
int (VS_CC *propSetFloat)(VSMap *map, const char *key, double d, int append) VS_NOEXCEPT;
int (VS_CC *propSetData)(VSMap *map, const char *key, const char *data, int size, int append) VS_NOEXCEPT;
int (VS_CC *propSetNode)(VSMap *map, const char *key, VSNodeRef *node, int append) VS_NOEXCEPT;
int (VS_CC *propSetFrame)(VSMap *map, const char *key, const VSFrameRef *f, int append) VS_NOEXCEPT;
int (VS_CC *propSetFunc)(VSMap *map, const char *key, VSFuncRef *func, int append) VS_NOEXCEPT;
int64_t (VS_CC *setMaxCacheSize)(int64_t bytes, VSCore *core) VS_NOEXCEPT;
int (VS_CC *getOutputIndex)(VSFrameContext *frameCtx) VS_NOEXCEPT;
VSFrameRef *(VS_CC *newVideoFrame2)(const VSFormat *format, int width, int height, const VSFrameRef **planeSrc, const int *planes, const VSFrameRef *propSrc, VSCore *core) VS_NOEXCEPT;
void (VS_CC *setMessageHandler)(VSMessageHandler handler, void *userData) VS_NOEXCEPT;
int (VS_CC *setThreadCount)(int threads, VSCore *core) VS_NOEXCEPT;
const char *(VS_CC *getPluginPath)(const VSPlugin *plugin) VS_NOEXCEPT;
/* api 3.1 */
const int64_t *(VS_CC *propGetIntArray)(const VSMap *map, const char *key, int *error) VS_NOEXCEPT;
const double *(VS_CC *propGetFloatArray)(const VSMap *map, const char *key, int *error) VS_NOEXCEPT;
int (VS_CC *propSetIntArray)(VSMap *map, const char *key, const int64_t *i, int size) VS_NOEXCEPT;
int (VS_CC *propSetFloatArray)(VSMap *map, const char *key, const double *d, int size) VS_NOEXCEPT;
/* api 3.4 */
void (VS_CC *logMessage)(int msgType, const char *msg) VS_NOEXCEPT;
};
VS_API(const VSAPI *) getVapourSynthAPI(int version) VS_NOEXCEPT;
#endif /* VAPOURSYNTH_H */

View file

@ -0,0 +1,373 @@
// Copyright (c) 2012-2018 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "vapoursource.h"
#include "../core/utils.h"
#include "VSHelper.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
static int GetNumPixFmts() {
int n = 0;
while (av_get_pix_fmt_name((AVPixelFormat)n))
n++;
return n;
}
static bool IsRealNativeEndianPlanar(const AVPixFmtDescriptor &desc) {
// reject all special flags
if (desc.flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_BAYER | AV_PIX_FMT_FLAG_HWACCEL | AV_PIX_FMT_FLAG_BITSTREAM))
return false;
int used_planes = 0;
for (int i = 0; i < desc.nb_components; i++)
used_planes = std::max(used_planes, (int)desc.comp[i].plane + 1);
bool temp = (used_planes == desc.nb_components) && (desc.comp[0].depth >= 8);
if (!temp)
return false;
else if (desc.comp[0].depth == 8)
return temp;
else
return (AV_PIX_FMT_YUV420P10 == AV_PIX_FMT_YUV420P10BE ? !!(desc.flags & AV_PIX_FMT_FLAG_BE) : !(desc.flags & AV_PIX_FMT_FLAG_BE));
}
static int GetSampleType(const AVPixFmtDescriptor &desc) {
return (desc.flags & AV_PIX_FMT_FLAG_FLOAT) ? stFloat : stInteger;
}
static bool HasAlpha(const AVPixFmtDescriptor &desc) {
return !!(desc.flags & AV_PIX_FMT_FLAG_ALPHA);
}
static int GetColorFamily(const AVPixFmtDescriptor &desc) {
if (desc.nb_components <= 2)
return cmGray;
else if (desc.flags & AV_PIX_FMT_FLAG_RGB)
return cmRGB;
else
return cmYUV;
}
static int FormatConversionToPixelFormat(int id, bool alpha, VSCore *core, const VSAPI *vsapi) {
const VSFormat *f = vsapi->getFormatPreset(id, core);
int npixfmt = GetNumPixFmts();
// Look for a suitable format without alpha first to not waste memory
if (!alpha) {
for (int i = 0; i < npixfmt; i++) {
const AVPixFmtDescriptor &desc = *av_pix_fmt_desc_get((AVPixelFormat)i);
if (IsRealNativeEndianPlanar(desc) && !HasAlpha(desc)
&& GetColorFamily(desc) == f->colorFamily
&& desc.comp[0].depth == f->bitsPerSample
&& desc.log2_chroma_w == f->subSamplingW
&& desc.log2_chroma_h == f->subSamplingH
&& GetSampleType(desc) == f->sampleType)
return i;
}
}
// Try all remaining formats
for (int i = 0; i < npixfmt; i++) {
const AVPixFmtDescriptor &desc = *av_pix_fmt_desc_get((AVPixelFormat)i);
if (IsRealNativeEndianPlanar(desc) && HasAlpha(desc)
&& GetColorFamily(desc) == f->colorFamily
&& desc.comp[0].depth == f->bitsPerSample
&& desc.log2_chroma_w == f->subSamplingW
&& desc.log2_chroma_h == f->subSamplingH
&& GetSampleType(desc) == f->sampleType)
return i;
}
return AV_PIX_FMT_NONE;
}
static const VSFormat *FormatConversionToVS(int id, VSCore *core, const VSAPI *vsapi) {
const AVPixFmtDescriptor &desc = *av_pix_fmt_desc_get((AVPixelFormat)id);
return vsapi->registerFormat(
GetColorFamily(desc),
GetSampleType(desc),
desc.comp[0].depth,
desc.log2_chroma_w,
desc.log2_chroma_h, core);
}
void VS_CC VSVideoSource::Init(VSMap *, VSMap *, void **instanceData, VSNode *node, VSCore *, const VSAPI *vsapi) {
VSVideoSource *Source = static_cast<VSVideoSource *>(*instanceData);
vsapi->setVideoInfo(Source->VI, Source->OutputAlpha ? 2 : 1, node);
}
const VSFrameRef *VS_CC VSVideoSource::GetFrame(int n, int activationReason, void **instanceData, void **, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) {
VSVideoSource *vs = static_cast<VSVideoSource *>(*instanceData);
if (activationReason == arInitial) {
char ErrorMsg[1024];
FFMS_ErrorInfo E;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
std::string buf = "Source: ";
int OutputIndex = vs->OutputAlpha ? vsapi->getOutputIndex(frameCtx) : 0;
VSFrameRef *Dst = vsapi->newVideoFrame(vs->VI[OutputIndex].format, vs->VI[OutputIndex].width, vs->VI[OutputIndex].height, nullptr, core);
VSMap *Props = vsapi->getFramePropsRW(Dst);
const FFMS_Frame *Frame = nullptr;
if (vs->FPSNum > 0 && vs->FPSDen > 0) {
double currentTime = FFMS_GetVideoProperties(vs->V)->FirstTime +
(double)(n * (int64_t)vs->FPSDen) / vs->FPSNum;
Frame = FFMS_GetFrameByTime(vs->V, currentTime, &E);
vsapi->propSetInt(Props, "_DurationNum", vs->FPSDen, paReplace);
vsapi->propSetInt(Props, "_DurationDen", vs->FPSNum, paReplace);
vsapi->propSetFloat(Props, "_AbsoluteTime", currentTime, paReplace);
} else {
Frame = FFMS_GetFrame(vs->V, n, &E);
FFMS_Track *T = FFMS_GetTrackFromVideo(vs->V);
const FFMS_TrackTimeBase *TB = FFMS_GetTimeBase(T);
int64_t num;
if (n + 1 < vs->VI[0].numFrames)
num = FFMS_GetFrameInfo(T, n + 1)->PTS - FFMS_GetFrameInfo(T, n)->PTS;
else if (n > 0) // simply use the second to last frame's duration for the last one, should be good enough
num = FFMS_GetFrameInfo(T, n)->PTS - FFMS_GetFrameInfo(T, n - 1)->PTS;
else // just make it one timebase if it's a single frame clip
num = 1;
int64_t DurNum = TB->Num * num;
int64_t DurDen = TB->Den * 1000;
muldivRational(&DurNum, &DurDen, 1, 1);
vsapi->propSetInt(Props, "_DurationNum", DurNum, paReplace);
vsapi->propSetInt(Props, "_DurationDen", DurDen, paReplace);
vsapi->propSetFloat(Props, "_AbsoluteTime", ((static_cast<double>(TB->Num) / 1000) * FFMS_GetFrameInfo(T, n)->PTS) / TB->Den, paReplace);
}
if (Frame == nullptr) {
buf += E.Buffer;
vsapi->setFilterError(buf.c_str(), frameCtx);
return nullptr;
}
// Set AR variables
if (vs->SARNum > 0 && vs->SARDen > 0) {
vsapi->propSetInt(Props, "_SARNum", vs->SARNum, paReplace);
vsapi->propSetInt(Props, "_SARDen", vs->SARDen, paReplace);
}
vsapi->propSetInt(Props, "_Matrix", Frame->ColorSpace, paReplace);
vsapi->propSetInt(Props, "_Primaries", Frame->ColorPrimaries, paReplace);
vsapi->propSetInt(Props, "_Transfer", Frame->TransferCharateristics, paReplace);
if (Frame->ChromaLocation > 0)
vsapi->propSetInt(Props, "_ChromaLocation", Frame->ChromaLocation - 1, paReplace);
if (Frame->ColorRange == FFMS_CR_MPEG)
vsapi->propSetInt(Props, "_ColorRange", 1, paReplace);
else if (Frame->ColorRange == FFMS_CR_JPEG)
vsapi->propSetInt(Props, "_ColorRange", 0, paReplace);
vsapi->propSetData(Props, "_PictType", &Frame->PictType, 1, paReplace);
// Set field information
int FieldBased = 0;
if (Frame->InterlacedFrame)
FieldBased = (Frame->TopFieldFirst ? 2 : 1);
vsapi->propSetInt(Props, "_FieldBased", FieldBased, paReplace);
if (Frame->HasMasteringDisplayPrimaries) {
vsapi->propSetFloatArray(Props, "MasteringDisplayPrimariesX", Frame->MasteringDisplayPrimariesX, 3);
vsapi->propSetFloatArray(Props, "MasteringDisplayPrimariesY", Frame->MasteringDisplayPrimariesY, 3);
vsapi->propSetFloat(Props, "MasteringDisplayWhitePointX", Frame->MasteringDisplayWhitePointX, paReplace);
vsapi->propSetFloat(Props, "MasteringDisplayWhitePointY", Frame->MasteringDisplayWhitePointY, paReplace);
}
if (Frame->HasMasteringDisplayLuminance) {
vsapi->propSetFloat(Props, "MasteringDisplayMinLuminance", Frame->MasteringDisplayMinLuminance, paReplace);
vsapi->propSetFloat(Props, "MasteringDisplayMaxLuminance", Frame->MasteringDisplayMaxLuminance, paReplace);
}
if (Frame->HasContentLightLevel) {
vsapi->propSetFloat(Props, "ContentLightLevelMax", Frame->ContentLightLevelMax, paReplace);
vsapi->propSetFloat(Props, "ContentLightLevelAverage", Frame->ContentLightLevelAverage, paReplace);
}
if (OutputIndex == 0)
OutputFrame(Frame, Dst, vsapi);
else
OutputAlphaFrame(Frame, vs->VI[0].format->numPlanes, Dst, vsapi);
return Dst;
}
return nullptr;
}
void VS_CC VSVideoSource::Free(void *instanceData, VSCore *, const VSAPI *) {
FFMS_Deinit();
delete static_cast<VSVideoSource *>(instanceData);
}
VSVideoSource::VSVideoSource(const char *SourceFile, int Track, FFMS_Index *Index,
int AFPSNum, int AFPSDen, int Threads, int SeekMode, int /*RFFMode*/,
int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
int Format, bool OutputAlpha, const VSAPI *vsapi, VSCore *core)
: FPSNum(AFPSNum), FPSDen(AFPSDen), OutputAlpha(OutputAlpha) {
VI[0] = {};
VI[1] = {};
char ErrorMsg[1024];
FFMS_ErrorInfo E;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
V = FFMS_CreateVideoSource(SourceFile, Track, Index, Threads, SeekMode, &E);
if (!V) {
throw std::runtime_error(std::string("Source: ") + E.Buffer);
}
try {
InitOutputFormat(ResizeToWidth, ResizeToHeight, ResizerName, Format, vsapi, core);
} catch (std::exception &) {
FFMS_DestroyVideoSource(V);
throw;
}
const FFMS_VideoProperties *VP = FFMS_GetVideoProperties(V);
if (FPSNum > 0 && FPSDen > 0) {
muldivRational(&FPSNum, &FPSDen, 1, 1);
VI[0].fpsDen = FPSDen;
VI[0].fpsNum = FPSNum;
if (VP->NumFrames > 1) {
VI[0].numFrames = static_cast<int>((VP->LastTime - VP->FirstTime) * (1 + 1. / (VP->NumFrames - 1)) * FPSNum / FPSDen + 0.5);
if (VI[0].numFrames < 1)
VI[0].numFrames = 1;
} else {
VI[0].numFrames = 1;
}
} else {
VI[0].fpsDen = VP->FPSDenominator;
VI[0].fpsNum = VP->FPSNumerator;
VI[0].numFrames = VP->NumFrames;
muldivRational(&VI[0].fpsNum, &VI[0].fpsDen, 1, 1);
}
if (OutputAlpha) {
VI[1] = VI[0];
VI[1].format = vsapi->registerFormat(cmGray, VI[0].format->sampleType, VI[0].format->bitsPerSample, VI[0].format->subSamplingW, VI[0].format->subSamplingH, core);
}
SARNum = VP->SARNum;
SARDen = VP->SARDen;
}
VSVideoSource::~VSVideoSource() {
FFMS_DestroyVideoSource(V);
}
void VSVideoSource::InitOutputFormat(int ResizeToWidth, int ResizeToHeight,
const char *ResizerName, int ConvertToFormat, const VSAPI *vsapi, VSCore *core) {
char ErrorMsg[1024];
FFMS_ErrorInfo E;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
const FFMS_Frame *F = FFMS_GetFrame(V, 0, &E);
if (!F) {
std::string buf = "Source: ";
buf += E.Buffer;
throw std::runtime_error(buf);
}
std::vector<int> TargetFormats;
int npixfmt = GetNumPixFmts();
for (int i = 0; i < npixfmt; i++)
if (IsRealNativeEndianPlanar(*av_pix_fmt_desc_get((AVPixelFormat)i)))
TargetFormats.push_back(i);
TargetFormats.push_back(AV_PIX_FMT_NONE);
int TargetPixelFormat = AV_PIX_FMT_NONE;
if (ConvertToFormat != pfNone) {
TargetPixelFormat = FormatConversionToPixelFormat(ConvertToFormat, OutputAlpha, core, vsapi);
if (TargetPixelFormat == AV_PIX_FMT_NONE)
throw std::runtime_error(std::string("Source: Invalid output colorspace specified"));
TargetFormats.clear();
TargetFormats.push_back(TargetPixelFormat);
TargetFormats.push_back(-1);
}
if (ResizeToWidth <= 0)
ResizeToWidth = F->EncodedWidth;
if (ResizeToHeight <= 0)
ResizeToHeight = F->EncodedHeight;
int Resizer = ResizerNameToSWSResizer(ResizerName);
if (Resizer == 0)
throw std::runtime_error(std::string("Source: Invalid resizer name specified"));
if (FFMS_SetOutputFormatV2(V, &TargetFormats[0],
ResizeToWidth, ResizeToHeight, Resizer, &E))
throw std::runtime_error(std::string("Source: No suitable output format found"));
F = FFMS_GetFrame(V, 0, &E);
TargetFormats.clear();
TargetFormats.push_back(F->ConvertedPixelFormat);
TargetFormats.push_back(-1);
// This trick is required to first get the "best" default format and then set only that format as the output
if (FFMS_SetOutputFormatV2(V, TargetFormats.data(), ResizeToWidth, ResizeToHeight, Resizer, &E))
throw std::runtime_error(std::string("Source: No suitable output format found"));
F = FFMS_GetFrame(V, 0, &E);
// Don't output alpha if the clip doesn't have it
if (!HasAlpha(*av_pix_fmt_desc_get((AVPixelFormat)F->ConvertedPixelFormat)))
OutputAlpha = false;
VI[0].format = FormatConversionToVS(F->ConvertedPixelFormat, core, vsapi);
if (!VI[0].format)
throw std::runtime_error(std::string("Source: No suitable output format found"));
VI[0].width = F->ScaledWidth;
VI[0].height = F->ScaledHeight;
// Crop to obey subsampling width/height requirements
VI[0].width -= VI[0].width % (1 << VI[0].format->subSamplingW);
VI[0].height -= VI[0].height % (1 << VI[0].format->subSamplingH);
}
void VSVideoSource::OutputFrame(const FFMS_Frame *Frame, VSFrameRef *Dst, const VSAPI *vsapi) {
const int RGBPlaneOrder[3] = { 2, 0, 1 };
const VSFormat *fi = vsapi->getFrameFormat(Dst);
if (fi->colorFamily == cmRGB) {
for (int i = 0; i < fi->numPlanes; i++)
vs_bitblt(vsapi->getWritePtr(Dst, i), vsapi->getStride(Dst, i), Frame->Data[RGBPlaneOrder[i]], Frame->Linesize[RGBPlaneOrder[i]],
vsapi->getFrameWidth(Dst, i) * fi->bytesPerSample, vsapi->getFrameHeight(Dst, i));
} else {
for (int i = 0; i < fi->numPlanes; i++)
vs_bitblt(vsapi->getWritePtr(Dst, i), vsapi->getStride(Dst, i), Frame->Data[i], Frame->Linesize[i],
vsapi->getFrameWidth(Dst, i) * fi->bytesPerSample, vsapi->getFrameHeight(Dst, i));
}
}
void VSVideoSource::OutputAlphaFrame(const FFMS_Frame *Frame, int Plane, VSFrameRef *Dst, const VSAPI *vsapi) {
const VSFormat *fi = vsapi->getFrameFormat(Dst);
vs_bitblt(vsapi->getWritePtr(Dst, 0), vsapi->getStride(Dst, 0), Frame->Data[Plane], Frame->Linesize[Plane],
vsapi->getFrameWidth(Dst, 0) * fi->bytesPerSample, vsapi->getFrameHeight(Dst, 0));
}

View file

@ -0,0 +1,63 @@
// Copyright (c) 2012-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef FFVAPOURSOURCES_H
#define FFVAPOURSOURCES_H
extern "C" {
#include <libavutil/avutil.h>
#include <libavutil/common.h>
#include <libavutil/pixdesc.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}
#include "VapourSynth.h"
#include "ffms.h"
#include "ffmscompat.h"
struct VSVideoSource {
private:
VSVideoInfo VI[2];
FFMS_VideoSource *V;
int64_t FPSNum;
int64_t FPSDen;
int SARNum;
int SARDen;
bool OutputAlpha;
void InitOutputFormat(int ResizeToWidth, int ResizeToHeight,
const char *ResizerName, int ConvertToFormat, const VSAPI *vsapi, VSCore *core);
static void OutputFrame(const FFMS_Frame *Frame, VSFrameRef *Dst, const VSAPI *vsapi);
static void OutputAlphaFrame(const FFMS_Frame *Frame, int Plane, VSFrameRef *Dst, const VSAPI *vsapi);
public:
VSVideoSource(const char *SourceFile, int Track, FFMS_Index *Index,
int AFPSNum, int AFPSDen, int Threads, int SeekMode, int RFFMode,
int ResizeToWidth, int ResizeToHeight, const char *ResizerName,
int Format, bool OutputAlpha, const VSAPI *vsapi, VSCore *core);
~VSVideoSource();
static void VS_CC Init(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi);
static const VSFrameRef *VS_CC GetFrame(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi);
static void VS_CC Free(void *instanceData, VSCore *core, const VSAPI *vsapi);
};
#endif

View file

@ -0,0 +1,239 @@
// Copyright (c) 2012-2017 Fredrik Mellbin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "ffms.h"
#include "vapoursource.h"
#include "VSHelper.h"
#include "../core/utils.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
static void VS_CC CreateIndex(const VSMap *in, VSMap *out, void *, VSCore *, const VSAPI *vsapi) {
FFMS_Init(0, 0);
char ErrorMsg[1024];
FFMS_ErrorInfo E;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
int err;
std::set<int> IndexTracks;
const char *Source = vsapi->propGetData(in, "source", 0, nullptr);
const char *CacheFile = vsapi->propGetData(in, "cachefile", 0, &err);
int NumIndexTracks = vsapi->propNumElements(in, "indextracks");
bool IndexAllTracks = (NumIndexTracks == 1) && (int64ToIntS(vsapi->propGetInt(in, "indextracks", 0, nullptr)) == -1);
if (!IndexAllTracks) {
for (int i = 0; i < NumIndexTracks; i++) {
int Track = int64ToIntS(vsapi->propGetInt(in, "indextracks", i, nullptr));
IndexTracks.insert(Track);
}
}
int ErrorHandling = int64ToIntS(vsapi->propGetInt(in, "errorhandling", 0, &err));
if (err)
ErrorHandling = FFMS_IEH_IGNORE;
bool OverWrite = !!vsapi->propGetInt(in, "overwrite", 0, &err);
std::string DefaultCache(Source);
if (!CacheFile || !strcmp(CacheFile, "")) {
DefaultCache.append(".ffindex");
CacheFile = DefaultCache.c_str();
}
FFMS_Index *Index = FFMS_ReadIndex(CacheFile, &E);
if (OverWrite || !Index || (Index && FFMS_IndexBelongsToFile(Index, Source, nullptr) != FFMS_ERROR_SUCCESS)) {
FFMS_Indexer *Indexer = FFMS_CreateIndexer(Source, &E);
if (!Indexer) {
FFMS_DestroyIndex(Index);
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
}
if (IndexAllTracks) {
FFMS_TrackTypeIndexSettings(Indexer, FFMS_TYPE_AUDIO, 1, 0);
} else {
for (int i : IndexTracks)
FFMS_TrackIndexSettings(Indexer, i, 1, 0);
}
Index = FFMS_DoIndexing2(Indexer, ErrorHandling, &E);
if (!Index)
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
if (FFMS_WriteIndex(CacheFile, Index, &E)) {
FFMS_DestroyIndex(Index);
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
}
FFMS_DestroyIndex(Index);
if (!OverWrite)
vsapi->propSetData(out, "result", "Index generated", -1, paReplace);
else
vsapi->propSetData(out, "result", "Index generated (forced overwrite)", -1, paReplace);
} else {
FFMS_DestroyIndex(Index);
vsapi->propSetData(out, "result", "Valid index already exists", -1, paReplace);
}
FFMS_Deinit();
}
static void VS_CC CreateSource(const VSMap *in, VSMap *out, void *, VSCore *core, const VSAPI *vsapi) {
FFMS_Init(0, 0);
char ErrorMsg[1024];
FFMS_ErrorInfo E;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
int err;
const char *Source = vsapi->propGetData(in, "source", 0, nullptr);
int Track = int64ToIntS(vsapi->propGetInt(in, "track", 0, &err));
if (err)
Track = -1;
bool Cache = !!vsapi->propGetInt(in, "cache", 0, &err);
if (err)
Cache = true;
const char *CacheFile = vsapi->propGetData(in, "cachefile", 0, &err);
int FPSNum = int64ToIntS(vsapi->propGetInt(in, "fpsnum", 0, &err));
if (err)
FPSNum = -1;
int FPSDen = int64ToIntS(vsapi->propGetInt(in, "fpsden", 0, &err));
if (err)
FPSDen = 1;
int Threads = int64ToIntS(vsapi->propGetInt(in, "threads", 0, &err));
const char *Timecodes = vsapi->propGetData(in, "timecodes", 0, &err);
int SeekMode = int64ToIntS(vsapi->propGetInt(in, "seekmode", 0, &err));
if (err)
SeekMode = FFMS_SEEK_NORMAL;
int RFFMode = int64ToIntS(vsapi->propGetInt(in, "rffmode", 0, &err));
int Width = int64ToIntS(vsapi->propGetInt(in, "width", 0, &err));
int Height = int64ToIntS(vsapi->propGetInt(in, "height", 0, &err));
const char *Resizer = vsapi->propGetData(in, "resizer", 0, &err);
if (err)
Resizer = "BICUBIC";
int Format = int64ToIntS(vsapi->propGetInt(in, "format", 0, &err));
bool OutputAlpha = !!vsapi->propGetInt(in, "alpha", 0, &err);
if (err)
OutputAlpha = false;
if (FPSDen < 1)
return vsapi->setError(out, "Source: FPS denominator needs to be 1 or higher");
if (Track <= -2)
return vsapi->setError(out, "Source: No video track selected");
if (SeekMode < -1 || SeekMode > 3)
return vsapi->setError(out, "Source: Invalid seekmode selected");
if (RFFMode < 0 || RFFMode > 2)
return vsapi->setError(out, "Source: Invalid RFF mode selected");
if (RFFMode > 0 && FPSNum > 0)
return vsapi->setError(out, "Source: RFF modes may not be combined with CFR conversion");
if (Timecodes && IsSamePath(Source, Timecodes))
return vsapi->setError(out, "Source: Timecodes will overwrite the source");
FFMS_Index *Index = nullptr;
std::string DefaultCache;
if (Cache) {
if (CacheFile && *CacheFile) {
if (IsSamePath(Source, CacheFile))
return vsapi->setError(out, "Source: Cache will overwrite the source");
Index = FFMS_ReadIndex(CacheFile, &E);
} else {
DefaultCache = Source;
DefaultCache += ".ffindex";
CacheFile = DefaultCache.c_str();
Index = FFMS_ReadIndex(CacheFile, &E);
// Reindex if the index doesn't match the file and its name wasn't
// explicitly given
if (Index && FFMS_IndexBelongsToFile(Index, Source, nullptr) != FFMS_ERROR_SUCCESS) {
FFMS_DestroyIndex(Index);
Index = nullptr;
}
}
}
if (!Index) {
FFMS_Indexer *Indexer = FFMS_CreateIndexer(Source, &E);
if (!Indexer)
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
Index = FFMS_DoIndexing2(Indexer, FFMS_IEH_CLEAR_TRACK, &E);
if (!Index)
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
if (Cache)
if (FFMS_WriteIndex(CacheFile, Index, &E)) {
FFMS_DestroyIndex(Index);
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
}
}
if (Track == -1)
Track = FFMS_GetFirstIndexedTrackOfType(Index, FFMS_TYPE_VIDEO, &E);
if (Track < 0) {
FFMS_DestroyIndex(Index);
return vsapi->setError(out, "Source: No video track found");
}
if (Timecodes && strcmp(Timecodes, "")) {
if (FFMS_WriteTimecodes(FFMS_GetTrackFromIndex(Index, Track), Timecodes, &E)) {
FFMS_DestroyIndex(Index);
return vsapi->setError(out, (std::string("Index: ") + E.Buffer).c_str());
}
}
VSVideoSource *vs;
try {
vs = new VSVideoSource(Source, Track, Index, FPSNum, FPSDen, Threads, SeekMode, RFFMode, Width, Height, Resizer, Format, OutputAlpha, vsapi, core);
} catch (std::exception const& e) {
FFMS_DestroyIndex(Index);
return vsapi->setError(out, e.what());
}
vsapi->createFilter(in, out, "Source", VSVideoSource::Init, VSVideoSource::GetFrame, VSVideoSource::Free, fmUnordered, nfMakeLinear, vs, core);
FFMS_DestroyIndex(Index);
}
static void VS_CC GetLogLevel(const VSMap *, VSMap *out, void *, VSCore *, const VSAPI *vsapi) {
vsapi->propSetInt(out, "level", FFMS_GetLogLevel(), paReplace);
}
static void VS_CC SetLogLevel(const VSMap *in, VSMap *out, void *, VSCore *, const VSAPI *vsapi) {
FFMS_SetLogLevel((int)vsapi->propGetInt(in, "level", 0, nullptr));
vsapi->propSetInt(out, "level", FFMS_GetLogLevel(), paReplace);
}
static void VS_CC GetVersion(const VSMap *, VSMap *out, void *, VSCore *, const VSAPI *vsapi) {
int Version = FFMS_GetVersion();
char buf[100];
sprintf(buf, "%d.%d.%d.%d", Version >> 24, (Version & 0xFF0000) >> 16, (Version & 0xFF00) >> 8, Version & 0xFF);
vsapi->propSetData(out, "version", buf, -1, paReplace);
}
VS_EXTERNAL_API(void) VapourSynthPluginInit(VSConfigPlugin configFunc, VSRegisterFunction registerFunc, VSPlugin *plugin) {
configFunc("com.vapoursynth.ffms2", "ffms2", "FFmpegSource 2 for VapourSynth", VAPOURSYNTH_API_VERSION, 1, plugin);
registerFunc("Index", "source:data;cachefile:data:opt;indextracks:int[]:opt;errorhandling:int:opt;overwrite:int:opt;", CreateIndex, nullptr, plugin);
registerFunc("Source", "source:data;track:int:opt;cache:int:opt;cachefile:data:opt;fpsnum:int:opt;fpsden:int:opt;threads:int:opt;timecodes:data:opt;seekmode:int:opt;width:int:opt;height:int:opt;resizer:data:opt;format:int:opt;alpha:int:opt;", CreateSource, nullptr, plugin);
registerFunc("GetLogLevel", "", GetLogLevel, nullptr, plugin);
registerFunc("SetLogLevel", "level:int;", SetLogLevel, nullptr, plugin);
registerFunc("Version", "", GetVersion, nullptr, plugin);
}

115
ffms2/test/Makefile Normal file
View file

@ -0,0 +1,115 @@
# Where to find user code.
USER_DIR = ..
# Points to the root of Google Test, relative to where this file is.
# Remember to tweak this if you move this file.
GTEST_DIR = $(USER_DIR)/test/googletest/googletest
# Where to find sample files
SAMPLES_DIR =
# URL to sync samples from
SAMPLES_URL =
# Flags passed to the preprocessor.
# Set Google Test's header directory as a system directory, such that
# the compiler doesn't generate warnings in Google Test headers.
CPPFLAGS += -isystem $(GTEST_DIR)/include \
-I$(USER_DIR)/include \
-D_FILE_OFFSET_BITS=64 \
-DFFMS_EXPORTS \
-D__STDC_CONSTANT_MACROS \
-DSAMPLES_DIR=$(SAMPLES_DIR)
# Flags passed to the C++ compiler.
CXXFLAGS += -g -Wall -Wextra -pthread -std=c++11 -fvisibility=hidden
# All tests produced by this Makefile. Remember to add new tests you
# created to the list.
TESTS = indexer \
hdr \
display_matrix
RUNTESTS = $(subst $() $(),-run$() $(),$(TESTS))-run
# All the sample files we need to sync
SAMPLES = test.mp4 \
hdr10tags-both.mkv \
hdr10tags-container.mkv \
hdr10tags-stream.mp4 \
qrvideo_hflip_90.mov \
qrvideo_hflip_270.mov \
qrvideo_vflip.mov
# All Google Test headers. Usually you shouldn't change this
# definition.
GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h $(GTEST_DIR)/include/gtest/internal/*.h
# House-keeping build targets.
all: $(TESTS)
run: all $(RUNTESTS)
sync:
@for i in $(SAMPLES); do \
if [ ! -f "$(SAMPLES_DIR)/$$i" ]; then \
wget -O $(SAMPLES_DIR)/$$i $(SAMPLES_URL)/$$i; \
fi \
done
clean:
rm -f $(TESTS) gtest.a gtest_main.a *.o
rm -rf .libs
# Builds gtest.a and gtest_main.a.
# Usually you shouldn't tweak such internal variables, indicated by a
# trailing _.
GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)
# For simplicity and to avoid depending on Google Test's
# implementation details, the dependencies specified below are
# conservative and not optimized. This is fine as Google Test
# compiles fast and for ordinary users its source rarely changes.
gtest-all.o: $(GTEST_SRCS_)
$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c $(GTEST_DIR)/src/gtest-all.cc
gtest_main.o: $(GTEST_SRCS_)
$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c $(GTEST_DIR)/src/gtest_main.cc
gtest.a: gtest-all.o
$(AR) $(ARFLAGS) $@ $^
gtest_main.a: gtest-all.o gtest_main.o
$(AR) $(ARFLAGS) $@ $^
tests.o: $(USER_DIR)/test/tests.cpp $(USER_DIR)/include/ffms.h $(GTEST_HEADERS)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/test/tests.cpp
hdr.o: $(USER_DIR)/test/hdr.cpp $(USER_DIR)/include/ffms.h $(GTEST_HEADERS)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/test/hdr.cpp
display_matrix.o: $(USER_DIR)/test/display_matrix.cpp $(USER_DIR)/include/ffms.h $(GTEST_HEADERS)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/test/display_matrix.cpp
indexer.o: $(USER_DIR)/test/indexer.cpp $(USER_DIR)/include/ffms.h $(GTEST_HEADERS)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/test/indexer.cpp
indexer: indexer.o tests.o gtest_main.a ../src/core/libffms2.la
../libtool --tag=CXX --mode=link $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o indexer indexer.o tests.o gtest_main.a -lavutil ../src/core/libffms2.la
indexer-run:
@./indexer
hdr: hdr.o gtest_main.a ../src/core/libffms2.la
../libtool --tag=CXX --mode=link $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o hdr hdr.o gtest_main.a -lavutil ../src/core/libffms2.la
hdr-run:
@./hdr
display_matrix: display_matrix.o gtest_main.a ../src/core/libffms2.la
../libtool --tag=CXX --mode=link $(CXX) $(CPPFLAGS) $(CXXFLAGS) -o display_matrix display_matrix.o gtest_main.a -lavutil ../src/core/libffms2.la
display_matrix-run:
@./display_matrix

16
ffms2/test/data/data.h Normal file
View file

@ -0,0 +1,16 @@
#ifndef _TEST_DATA_H
#define _TEST_DATA_H
#include <cstdint>
typedef struct TestFrameData {
int64_t PTS;
int64_t Duration;
int Width;
int Height;
const char *PixelFormat;
bool Keyframe;
uint8_t SHA256[32]; // SHA256 of the frame's decode planes
} TestFrameData;
#endif

View file

@ -0,0 +1,95 @@
// Autogenerated from test.mp4 by gendata with ffmpeg version N-91852-gf55d987bad
#ifndef _FFMS_TEST_TESTMP4DATA_H
#define _FFMS_TEST_TESTMP4DATA_H
#include "data.h"
const TestFrameData testmp4data[84] = {
{ 0, 1001, 960, 540, "yuv420p", true, { 0x70, 0x81, 0xF9, 0x06, 0xCA, 0x58, 0xCA, 0x64, 0x8D, 0x38, 0x27, 0xB9, 0x2B, 0x40, 0x0E, 0x7C, 0xA0, 0x09, 0xBB, 0x65, 0xF7, 0xD6, 0x2F, 0x58, 0xAF, 0x5D, 0xCB, 0x58, 0xCE, 0xF2, 0x0B, 0x19 } },
{ 1001, 1001, 960, 540, "yuv420p", false, { 0x10, 0x8D, 0x32, 0xDD, 0x97, 0x04, 0x92, 0xF1, 0x8A, 0x2C, 0xBE, 0xA2, 0xC5, 0x8E, 0x0B, 0x7A, 0xF9, 0xA1, 0xF7, 0x93, 0xA3, 0xA8, 0xE1, 0xB9, 0x84, 0xCC, 0xB1, 0x37, 0x53, 0x21, 0xAA, 0x26 } },
{ 2002, 1001, 960, 540, "yuv420p", false, { 0x1D, 0xD7, 0x53, 0x52, 0x95, 0x1E, 0x42, 0xA1, 0xDF, 0x51, 0x59, 0x86, 0x7F, 0xA8, 0xA6, 0xB5, 0x48, 0xD4, 0xA7, 0x0E, 0x5C, 0xF9, 0x1F, 0x7D, 0x7C, 0x2B, 0x76, 0x82, 0xDF, 0x5E, 0xDA, 0x04 } },
{ 3003, 1001, 960, 540, "yuv420p", false, { 0x79, 0xE8, 0xE9, 0xDA, 0x95, 0xB1, 0xEC, 0x3C, 0x73, 0xE2, 0x10, 0xBF, 0x5C, 0x50, 0x5F, 0x7B, 0x8D, 0x29, 0x76, 0xA2, 0x0C, 0x45, 0xEB, 0xF3, 0xE3, 0xB4, 0xE8, 0xEE, 0x51, 0x53, 0x47, 0x13 } },
{ 4004, 1001, 960, 540, "yuv420p", false, { 0x40, 0x81, 0xC5, 0xDD, 0x3B, 0xD6, 0x8C, 0xC4, 0x24, 0x7D, 0x80, 0xAF, 0xBF, 0x60, 0x66, 0x6E, 0x8C, 0x9B, 0xDD, 0xD1, 0x0F, 0xC1, 0x03, 0x2A, 0xB2, 0x03, 0x40, 0x6F, 0x1B, 0xED, 0x54, 0x90 } },
{ 5005, 1001, 960, 540, "yuv420p", false, { 0xF3, 0xBE, 0xD8, 0xBF, 0xE9, 0x17, 0xD9, 0xAA, 0x3D, 0x20, 0x85, 0x26, 0x35, 0x38, 0x3C, 0x52, 0x63, 0x10, 0x6B, 0x40, 0x1F, 0x55, 0xC7, 0x47, 0xEF, 0x0B, 0x58, 0x9A, 0xDC, 0xD6, 0x9A, 0x97 } },
{ 6006, 1001, 960, 540, "yuv420p", false, { 0x8C, 0x69, 0x01, 0x4E, 0x27, 0x10, 0xCB, 0x2E, 0x7E, 0x59, 0x4D, 0x1F, 0x78, 0x25, 0xAB, 0x1E, 0x8D, 0xED, 0x99, 0x7B, 0xF9, 0xC1, 0x5D, 0xA4, 0xC5, 0x48, 0x7B, 0xFA, 0x2E, 0xCA, 0x61, 0x29 } },
{ 7007, 1001, 960, 540, "yuv420p", false, { 0x37, 0x6F, 0xD8, 0x44, 0x0F, 0xE9, 0x39, 0x33, 0x06, 0xA7, 0x2A, 0xA7, 0xB2, 0x1D, 0x36, 0x30, 0x14, 0xDF, 0x27, 0xB0, 0xF6, 0x2A, 0xDB, 0x57, 0xEB, 0x3E, 0x61, 0xE7, 0xD0, 0xA6, 0xB4, 0x32 } },
{ 8008, 1001, 960, 540, "yuv420p", false, { 0xA2, 0xE8, 0xAD, 0x3B, 0x26, 0x5F, 0x21, 0x93, 0xC8, 0xF2, 0x88, 0x03, 0xF0, 0xAB, 0x95, 0xBB, 0x4F, 0x26, 0x87, 0x70, 0xBE, 0x52, 0x06, 0xC6, 0xB6, 0x0D, 0x5E, 0x7E, 0x4D, 0x2D, 0x1D, 0x3E } },
{ 9009, 1001, 960, 540, "yuv420p", false, { 0xA8, 0xB6, 0x7C, 0x42, 0x03, 0xA3, 0xB4, 0x26, 0x1E, 0x08, 0xC2, 0x23, 0x6D, 0xC0, 0x16, 0x45, 0x9D, 0x62, 0x42, 0x09, 0x98, 0x36, 0x4A, 0x6B, 0x24, 0xDD, 0x03, 0xB3, 0xA9, 0xCB, 0x9A, 0x88 } },
{ 10010, 1001, 960, 540, "yuv420p", false, { 0x91, 0xF2, 0xA4, 0xCA, 0x2C, 0x09, 0xCE, 0x19, 0x78, 0x30, 0x54, 0x72, 0xB1, 0x3B, 0x5D, 0x46, 0x8F, 0xEB, 0x0B, 0xE4, 0xBB, 0xFC, 0x6F, 0x4A, 0x47, 0x5F, 0xB5, 0x23, 0x61, 0x1C, 0x9C, 0x27 } },
{ 11011, 1001, 960, 540, "yuv420p", false, { 0x30, 0xE1, 0x9C, 0x0D, 0xCD, 0xB3, 0x23, 0xE9, 0xBD, 0xA2, 0x51, 0xB0, 0xAF, 0xCB, 0x4E, 0x40, 0x3B, 0x4F, 0x4B, 0x8D, 0xA0, 0xCE, 0x1F, 0x56, 0xFB, 0xB7, 0x8E, 0x4D, 0xE0, 0xCE, 0x53, 0x28 } },
{ 12012, 1001, 960, 540, "yuv420p", false, { 0x12, 0xA5, 0x45, 0x98, 0x31, 0xFF, 0xCB, 0x31, 0x7F, 0x8D, 0x99, 0xCD, 0xEC, 0x82, 0x5D, 0x11, 0x97, 0x7C, 0xE7, 0xF1, 0x13, 0x0D, 0x3D, 0x64, 0x66, 0xBD, 0xF4, 0x37, 0x65, 0xBE, 0xC7, 0xCC } },
{ 13013, 1001, 960, 540, "yuv420p", false, { 0x01, 0x68, 0x57, 0xD7, 0xF9, 0x8A, 0x7D, 0xA2, 0x45, 0x3B, 0xAE, 0x2E, 0xBA, 0x17, 0xBD, 0x32, 0x1A, 0x60, 0xD9, 0x17, 0xCB, 0x62, 0xD4, 0x4D, 0xAD, 0xA1, 0x55, 0xF6, 0xE1, 0xA3, 0x45, 0x86 } },
{ 14014, 1001, 960, 540, "yuv420p", false, { 0x63, 0x78, 0x87, 0x73, 0x35, 0x72, 0xA9, 0xCF, 0x17, 0xEB, 0x88, 0x8A, 0x11, 0x7C, 0x52, 0xFF, 0x93, 0x25, 0xBA, 0xD6, 0xA5, 0xE9, 0xC8, 0xD3, 0x06, 0x99, 0xA0, 0xC8, 0x5C, 0x93, 0xD5, 0x77 } },
{ 15015, 1001, 960, 540, "yuv420p", false, { 0xC6, 0x71, 0xFA, 0xF8, 0x1E, 0x0A, 0x28, 0x01, 0x1D, 0x6D, 0xFD, 0xB9, 0x23, 0xFE, 0x13, 0x4E, 0xD5, 0x6A, 0xEB, 0xB4, 0x5C, 0xBD, 0x53, 0x8C, 0x22, 0xD9, 0xA4, 0xD6, 0x79, 0x6F, 0xCE, 0x6B } },
{ 16016, 1001, 960, 540, "yuv420p", false, { 0x4F, 0x69, 0xF4, 0x53, 0x0D, 0xD3, 0x67, 0x81, 0xB1, 0x73, 0x14, 0x9C, 0x0E, 0x72, 0xD7, 0x39, 0xBC, 0x8E, 0xC2, 0xF4, 0x27, 0x34, 0x5A, 0xD0, 0xE4, 0xC2, 0x7A, 0xE1, 0xE3, 0xFF, 0x9B, 0xCA } },
{ 17017, 1001, 960, 540, "yuv420p", false, { 0x98, 0x35, 0xE9, 0xE6, 0x71, 0x68, 0x62, 0xED, 0xFE, 0x5E, 0x18, 0xB8, 0xD0, 0xD0, 0xFB, 0x9A, 0xF8, 0xEF, 0x7E, 0xEB, 0x1E, 0xB7, 0xBC, 0x59, 0x54, 0x21, 0x58, 0xF7, 0xB7, 0xC2, 0x6C, 0x05 } },
{ 18018, 1001, 960, 540, "yuv420p", false, { 0x0B, 0xC4, 0x89, 0xDE, 0xA3, 0x1E, 0x50, 0x12, 0x71, 0xA9, 0x91, 0x45, 0xD9, 0x4D, 0xB5, 0xAC, 0x37, 0x19, 0x91, 0x3A, 0xC6, 0xA2, 0x22, 0xE5, 0x64, 0xF5, 0x36, 0x94, 0x1E, 0x18, 0x94, 0x74 } },
{ 19019, 1001, 960, 540, "yuv420p", false, { 0x53, 0x83, 0x8B, 0x5E, 0x99, 0x2D, 0xF3, 0x6B, 0xE4, 0x2A, 0x98, 0x3B, 0x90, 0x38, 0xA0, 0x3F, 0xDA, 0x0B, 0x33, 0x3B, 0x98, 0x48, 0x71, 0xCC, 0xA5, 0xAD, 0xFB, 0x97, 0x6F, 0xC4, 0x3D, 0x58 } },
{ 20020, 1001, 960, 540, "yuv420p", false, { 0x30, 0xCE, 0x7C, 0x25, 0xF4, 0x45, 0x44, 0x6D, 0xF6, 0x33, 0xD3, 0x71, 0xFD, 0x72, 0x35, 0x39, 0xE5, 0xE4, 0xB4, 0x90, 0xA9, 0x44, 0xAF, 0x5B, 0xB2, 0x2A, 0x03, 0x06, 0xC6, 0x8D, 0xF0, 0x7B } },
{ 21021, 1001, 960, 540, "yuv420p", false, { 0x8D, 0x9F, 0xA7, 0x9E, 0xE2, 0xA4, 0x02, 0xD0, 0xA9, 0x5F, 0xCB, 0x24, 0x21, 0xDB, 0x30, 0x92, 0x6F, 0xDD, 0x7F, 0xF9, 0x8B, 0x07, 0x79, 0x16, 0x50, 0x7E, 0x65, 0x6C, 0x1C, 0x4A, 0x11, 0x4B } },
{ 22022, 1001, 960, 540, "yuv420p", false, { 0x01, 0x0B, 0xEA, 0x36, 0xDF, 0x88, 0xD2, 0xE8, 0xD0, 0xF3, 0x63, 0xBF, 0xB8, 0x14, 0xE4, 0x99, 0xB5, 0x6E, 0x08, 0xB5, 0x78, 0x6C, 0xBA, 0x56, 0xA1, 0x17, 0x91, 0x4A, 0xE5, 0x77, 0xD8, 0x51 } },
{ 23023, 1001, 960, 540, "yuv420p", false, { 0xED, 0x62, 0x86, 0x2B, 0xE8, 0x7B, 0x85, 0xFC, 0xDC, 0xC6, 0x2B, 0xC0, 0xF9, 0x37, 0xB2, 0xA9, 0x45, 0x87, 0x33, 0x3D, 0x89, 0xFE, 0x82, 0x66, 0x6E, 0xA7, 0x17, 0xF4, 0x2D, 0xAD, 0x05, 0x6F } },
{ 24024, 1001, 960, 540, "yuv420p", false, { 0x10, 0xE9, 0xB7, 0x24, 0x0B, 0x68, 0x7B, 0x0F, 0xBC, 0xEB, 0x25, 0xC4, 0xF8, 0x8B, 0xAC, 0x18, 0x26, 0x8B, 0xC0, 0x97, 0x09, 0x36, 0x6C, 0xE2, 0x49, 0xE2, 0x44, 0x86, 0xF1, 0xE6, 0x09, 0x9C } },
{ 25025, 1001, 960, 540, "yuv420p", false, { 0x78, 0xF9, 0x8E, 0xCF, 0x18, 0x3F, 0x6C, 0x11, 0x15, 0xDD, 0xCF, 0x6C, 0xCD, 0x29, 0x91, 0xAB, 0x9A, 0xD2, 0x91, 0x45, 0x78, 0x47, 0xAB, 0xEC, 0x51, 0x18, 0x25, 0x8B, 0xA1, 0xCA, 0x6A, 0x59 } },
{ 26026, 1001, 960, 540, "yuv420p", false, { 0x78, 0x26, 0x43, 0xA7, 0xFD, 0x62, 0x41, 0x25, 0x99, 0x47, 0x7A, 0x6A, 0xF9, 0xDF, 0xC8, 0x6E, 0x1E, 0x81, 0x82, 0xC3, 0x11, 0x20, 0x37, 0x9E, 0x59, 0x4C, 0x58, 0x73, 0x49, 0x78, 0xF7, 0xE3 } },
{ 27027, 1001, 960, 540, "yuv420p", false, { 0x77, 0x11, 0xA1, 0xC9, 0x93, 0x0F, 0x64, 0x2A, 0x28, 0x67, 0x2D, 0xA1, 0xA0, 0xD5, 0x4C, 0xF3, 0x24, 0xBD, 0xD9, 0x47, 0x2F, 0x0F, 0x66, 0x15, 0xF5, 0x26, 0x62, 0x5D, 0x91, 0x4F, 0x32, 0xEF } },
{ 28028, 1001, 960, 540, "yuv420p", false, { 0xF5, 0xFB, 0xDB, 0x3B, 0x37, 0x37, 0xD4, 0xF5, 0x94, 0xF4, 0x20, 0x34, 0xA7, 0x88, 0x81, 0xD8, 0xA4, 0xF8, 0x0D, 0xFE, 0x98, 0xDF, 0x75, 0x79, 0xD9, 0xAC, 0x10, 0xC7, 0x55, 0xBF, 0xDB, 0xDD } },
{ 29029, 1001, 960, 540, "yuv420p", false, { 0xE0, 0xA0, 0x54, 0xAC, 0x4E, 0x2C, 0x65, 0xF5, 0xD5, 0x00, 0x6E, 0x8C, 0x09, 0x1B, 0xB6, 0x37, 0x15, 0xAC, 0x1D, 0x56, 0x43, 0xBC, 0x99, 0xB7, 0xF5, 0xFB, 0xEA, 0x82, 0x32, 0x98, 0x3C, 0xE6 } },
{ 30030, 1001, 960, 540, "yuv420p", false, { 0xE5, 0xAF, 0xB4, 0x02, 0x08, 0x20, 0x6E, 0xC3, 0xF1, 0xA1, 0x39, 0x93, 0xE2, 0x21, 0x21, 0x6B, 0xFE, 0xC1, 0xCA, 0xE2, 0x8D, 0xF8, 0x0B, 0x60, 0xB2, 0x93, 0x3B, 0x21, 0x92, 0xB3, 0xC8, 0x59 } },
{ 31031, 1001, 960, 540, "yuv420p", false, { 0x40, 0xEA, 0xED, 0x7E, 0xC2, 0x76, 0x93, 0xC2, 0x4C, 0xA0, 0x11, 0x30, 0xF4, 0x37, 0x1C, 0xCA, 0xA1, 0xE4, 0x20, 0x4F, 0x42, 0xE0, 0x9F, 0xF6, 0x4C, 0x94, 0xE3, 0x1D, 0x00, 0xB7, 0x91, 0xAA } },
{ 32032, 1001, 960, 540, "yuv420p", false, { 0x4F, 0x94, 0xE0, 0x72, 0xD2, 0xB8, 0x92, 0x67, 0x0F, 0x95, 0x42, 0x05, 0x56, 0x85, 0x03, 0x5F, 0x3E, 0xA2, 0xD2, 0x4F, 0xE0, 0x05, 0x94, 0xC3, 0xDD, 0x0C, 0x53, 0x0A, 0x0F, 0xD3, 0x47, 0x45 } },
{ 33033, 1001, 960, 540, "yuv420p", false, { 0x63, 0xAF, 0x87, 0x28, 0x4E, 0xB0, 0x8B, 0xD8, 0xDD, 0x44, 0x2A, 0xF4, 0xAE, 0xD8, 0x07, 0x35, 0x73, 0x9A, 0xB8, 0x2C, 0x40, 0x4B, 0xDC, 0xA4, 0x0D, 0x3B, 0x39, 0x6B, 0xD7, 0x9C, 0x89, 0x35 } },
{ 34034, 1001, 960, 540, "yuv420p", false, { 0xC5, 0x21, 0x0E, 0x40, 0xD7, 0x44, 0xAF, 0x75, 0xAD, 0x49, 0x23, 0xA9, 0x79, 0xE3, 0x46, 0x54, 0xE7, 0xA5, 0xFC, 0x62, 0x54, 0x31, 0x64, 0xC4, 0xB1, 0xF4, 0x79, 0xC8, 0xBC, 0x71, 0x44, 0x62 } },
{ 35035, 1001, 960, 540, "yuv420p", false, { 0x43, 0xF7, 0x12, 0xB0, 0x20, 0xEC, 0x8C, 0xBC, 0xCD, 0xA9, 0xD8, 0xDC, 0x1A, 0xFC, 0xE7, 0x90, 0x58, 0xEC, 0x80, 0x38, 0x46, 0xA3, 0x80, 0x31, 0x9B, 0x35, 0xD5, 0x3B, 0xF1, 0x53, 0x64, 0xE5 } },
{ 36036, 1001, 960, 540, "yuv420p", false, { 0x1F, 0x8B, 0x64, 0x56, 0x96, 0x92, 0xFB, 0x7A, 0xEC, 0x16, 0x8B, 0x4B, 0xC5, 0x92, 0x90, 0x5B, 0x31, 0x89, 0xDF, 0x67, 0x85, 0x14, 0x0A, 0xC2, 0xF3, 0xE3, 0x82, 0x6A, 0x45, 0x54, 0x6A, 0x67 } },
{ 37037, 1001, 960, 540, "yuv420p", false, { 0x10, 0x31, 0xC3, 0x0F, 0x04, 0xB9, 0x5D, 0xDB, 0x2B, 0xCA, 0xAA, 0x36, 0x4C, 0x9E, 0x81, 0xD8, 0x83, 0x91, 0x83, 0xAE, 0x87, 0x87, 0x66, 0xC0, 0x87, 0x3A, 0x5C, 0x62, 0x40, 0x31, 0xEA, 0x4F } },
{ 38038, 1001, 960, 540, "yuv420p", false, { 0x7F, 0x85, 0xEB, 0x9B, 0x00, 0xCA, 0xD9, 0x1C, 0x5D, 0xAA, 0x13, 0xCA, 0x0A, 0xF2, 0xB2, 0x20, 0xA5, 0x0B, 0xEE, 0x61, 0x76, 0x7C, 0x53, 0xB2, 0xF0, 0x68, 0xA5, 0x4B, 0x7C, 0x29, 0xD0, 0x4A } },
{ 39039, 1001, 960, 540, "yuv420p", false, { 0x2C, 0xF9, 0xF5, 0xCC, 0xD2, 0xF3, 0x97, 0xB0, 0x44, 0xCE, 0xF2, 0xE7, 0x00, 0xA6, 0x58, 0x99, 0x37, 0xB6, 0x05, 0xA1, 0x04, 0x1E, 0x7A, 0x91, 0x48, 0x71, 0x03, 0x8D, 0xFD, 0x19, 0x67, 0x2B } },
{ 40040, 1001, 960, 540, "yuv420p", false, { 0xE2, 0x38, 0xDA, 0x68, 0x57, 0x2D, 0x6C, 0x25, 0xBF, 0x26, 0x5F, 0x95, 0xBC, 0xC6, 0xC8, 0x51, 0x23, 0xFF, 0x6C, 0x6A, 0x77, 0xAD, 0xC1, 0x2A, 0x29, 0x1B, 0xC2, 0xCB, 0xE0, 0x3E, 0xDF, 0xB7 } },
{ 41041, 1001, 960, 540, "yuv420p", false, { 0x72, 0xFF, 0x1D, 0x8A, 0x05, 0x82, 0x5C, 0x9F, 0x54, 0x75, 0x1F, 0x6D, 0xAE, 0x53, 0x28, 0x6E, 0x71, 0x6D, 0x9E, 0x7B, 0xB1, 0x00, 0xED, 0xF1, 0x0F, 0x43, 0x2F, 0xC1, 0xDC, 0xFE, 0xD1, 0x00 } },
{ 42042, 1001, 960, 540, "yuv420p", false, { 0xCE, 0x70, 0x01, 0xEB, 0x28, 0xD8, 0xD5, 0x8B, 0xC8, 0xEC, 0xBA, 0x34, 0x04, 0xD4, 0xA9, 0x77, 0xFD, 0xB7, 0xF4, 0x4C, 0x14, 0x39, 0x14, 0x6A, 0xC8, 0xAF, 0xCB, 0xAE, 0x88, 0x3A, 0xDB, 0x56 } },
{ 43043, 1001, 960, 540, "yuv420p", false, { 0xA9, 0x96, 0x9D, 0xEC, 0xBB, 0x3B, 0xAB, 0x6A, 0xF7, 0xC2, 0x72, 0x3A, 0x67, 0xB5, 0x0F, 0xBE, 0x45, 0x47, 0x54, 0x62, 0x56, 0xD8, 0x60, 0xEC, 0x46, 0x04, 0xB9, 0x61, 0xFF, 0xE8, 0xCA, 0xBC } },
{ 44044, 1001, 960, 540, "yuv420p", false, { 0xCA, 0x40, 0x76, 0xE9, 0x08, 0x5A, 0xF3, 0x57, 0xB9, 0x3A, 0xF5, 0x92, 0x5E, 0xB4, 0x5E, 0x22, 0x38, 0x62, 0x66, 0x00, 0x12, 0x64, 0x31, 0x6D, 0x48, 0xB0, 0x96, 0xD8, 0x03, 0xA0, 0x6B, 0xE7 } },
{ 45045, 1001, 960, 540, "yuv420p", false, { 0x71, 0x10, 0x24, 0x5B, 0xA0, 0x4C, 0xBF, 0x6E, 0x6E, 0x72, 0xC9, 0x0D, 0x43, 0x51, 0x8B, 0xFE, 0x1E, 0x2D, 0xF6, 0x44, 0x2F, 0x5B, 0x0F, 0x6A, 0xA7, 0x26, 0xB5, 0xD2, 0x48, 0x69, 0x8D, 0xEB } },
{ 46046, 1001, 960, 540, "yuv420p", false, { 0xB5, 0x8E, 0x9E, 0xA3, 0xDB, 0x51, 0xDD, 0xC9, 0xC0, 0x9C, 0xDC, 0x29, 0x6C, 0x96, 0xDF, 0x4E, 0xC1, 0xEC, 0x61, 0x42, 0xEB, 0x1E, 0x7E, 0xF3, 0x56, 0x82, 0x5C, 0xA9, 0x42, 0x83, 0x61, 0x8C } },
{ 47047, 1001, 960, 540, "yuv420p", false, { 0x4E, 0xA2, 0xC6, 0xEA, 0xA3, 0x9F, 0x97, 0x9B, 0x96, 0x6E, 0xF2, 0xFB, 0x52, 0x3A, 0x23, 0x22, 0x6A, 0x37, 0x12, 0x21, 0xF9, 0xDF, 0xA3, 0xB4, 0x37, 0xA6, 0x71, 0x75, 0x43, 0xA6, 0x44, 0xF2 } },
{ 48048, 1001, 960, 540, "yuv420p", false, { 0xE8, 0xE6, 0x7F, 0x94, 0xDA, 0x2B, 0x4A, 0xD8, 0x16, 0xC9, 0xDC, 0x2C, 0xE6, 0xF4, 0x4D, 0x6A, 0x36, 0x3E, 0xBD, 0x5D, 0xD8, 0xB3, 0x45, 0x95, 0xDC, 0x0F, 0xB7, 0x76, 0xDF, 0x7C, 0xE5, 0x30 } },
{ 49049, 1001, 960, 540, "yuv420p", false, { 0x4E, 0x84, 0x01, 0x72, 0x40, 0x7E, 0x88, 0x6E, 0x92, 0x05, 0xC8, 0x10, 0xAF, 0x99, 0x84, 0x68, 0xD7, 0x8B, 0x59, 0xBF, 0x05, 0x1D, 0x28, 0xA5, 0x1C, 0xDC, 0xBF, 0x8B, 0xDE, 0x39, 0xEE, 0x46 } },
{ 50050, 1001, 960, 540, "yuv420p", false, { 0x9F, 0xC6, 0x9E, 0xAE, 0x02, 0x75, 0xE3, 0x19, 0x1F, 0x9B, 0x49, 0x06, 0xBB, 0x7D, 0xBD, 0x00, 0xBE, 0x7C, 0x4A, 0xAB, 0x9D, 0x74, 0xF1, 0xF2, 0xCC, 0xA9, 0xC7, 0x81, 0xEF, 0x67, 0x42, 0x9E } },
{ 51051, 1001, 960, 540, "yuv420p", false, { 0xCA, 0x59, 0xBA, 0xA4, 0x4C, 0x8E, 0x26, 0xE3, 0xB1, 0x88, 0xD6, 0xD8, 0x26, 0x3E, 0x5E, 0x41, 0x2B, 0x54, 0x90, 0x9A, 0x54, 0x60, 0x89, 0xD7, 0xBB, 0x9D, 0x61, 0x3A, 0x09, 0x65, 0xEE, 0x40 } },
{ 52052, 1001, 960, 540, "yuv420p", false, { 0xA3, 0x6C, 0x49, 0x3E, 0xFC, 0xCE, 0xAD, 0x8A, 0xDC, 0xE6, 0x4E, 0x99, 0x04, 0x07, 0xDA, 0x5C, 0x96, 0xD5, 0x9E, 0xE7, 0x65, 0x75, 0xDA, 0x54, 0x65, 0xDB, 0x41, 0x8F, 0xFD, 0x36, 0x03, 0xD3 } },
{ 53053, 1001, 960, 540, "yuv420p", false, { 0x77, 0xB8, 0xFB, 0x7A, 0x61, 0x99, 0x71, 0xD7, 0x9E, 0x40, 0xF4, 0x25, 0x6E, 0x70, 0x0E, 0xE4, 0x3F, 0xC2, 0xB0, 0x8D, 0x9E, 0xF6, 0xA3, 0xAC, 0x87, 0xC2, 0xA6, 0x9F, 0x11, 0x99, 0xBC, 0xAA } },
{ 54054, 1001, 960, 540, "yuv420p", false, { 0x37, 0x58, 0xE3, 0xF0, 0x5E, 0xCE, 0xF1, 0xAB, 0xDA, 0xF2, 0xB2, 0xB2, 0xC1, 0x20, 0x09, 0x57, 0x88, 0x3B, 0xEB, 0x3E, 0xF0, 0x9F, 0xED, 0xE8, 0x17, 0x03, 0x0E, 0xAF, 0xA4, 0x32, 0xE5, 0x6B } },
{ 55055, 1001, 960, 540, "yuv420p", false, { 0xD0, 0xD8, 0x93, 0xFC, 0xAF, 0x3E, 0xCB, 0xF6, 0xF6, 0xBD, 0x29, 0xC4, 0x05, 0xA2, 0x2C, 0x9F, 0x61, 0xFA, 0x2A, 0x95, 0x6C, 0x5F, 0xE4, 0xC5, 0x00, 0xF1, 0x95, 0xF9, 0xBE, 0xC1, 0xD6, 0x8C } },
{ 56056, 1001, 960, 540, "yuv420p", false, { 0x42, 0xAC, 0xA4, 0xEC, 0x79, 0x58, 0xA1, 0xC2, 0x35, 0xAA, 0x2D, 0x30, 0x0F, 0x84, 0x7A, 0x98, 0x3C, 0x13, 0x32, 0x36, 0x10, 0x53, 0xA9, 0xCF, 0xBF, 0x67, 0x47, 0x7F, 0xF2, 0x59, 0xD0, 0xF5 } },
{ 57057, 1001, 960, 540, "yuv420p", false, { 0x84, 0x3D, 0xBA, 0x78, 0xB4, 0x52, 0x53, 0x65, 0xD6, 0xBC, 0x22, 0x89, 0x33, 0xA4, 0xB9, 0x14, 0x1C, 0x46, 0x92, 0x21, 0xAC, 0x52, 0x87, 0x13, 0x30, 0xF1, 0x0C, 0xFC, 0x21, 0x3F, 0x89, 0x7B } },
{ 58058, 1001, 960, 540, "yuv420p", false, { 0x0D, 0x5E, 0x06, 0xC6, 0x07, 0x0A, 0x9B, 0xF3, 0x9F, 0x26, 0x23, 0xA4, 0x24, 0xA7, 0x27, 0x15, 0x4F, 0x87, 0x55, 0xBC, 0x50, 0x92, 0x42, 0x6D, 0x23, 0x10, 0x57, 0xBD, 0xC4, 0x61, 0xD9, 0x91 } },
{ 59059, 1001, 960, 540, "yuv420p", false, { 0xF6, 0xB0, 0x68, 0x18, 0x65, 0x78, 0xA1, 0x00, 0x60, 0xA6, 0x78, 0x7E, 0x70, 0xDE, 0xBE, 0x61, 0x9D, 0x2A, 0x1B, 0x80, 0x12, 0xA5, 0xDB, 0x31, 0x54, 0x1B, 0xCA, 0xD5, 0x4A, 0x5F, 0xE4, 0x0C } },
{ 60060, 1001, 960, 540, "yuv420p", false, { 0x58, 0xCD, 0xB7, 0x78, 0x92, 0xBB, 0x0A, 0xE6, 0xA4, 0x27, 0xCA, 0x21, 0x4F, 0xED, 0x38, 0x12, 0x38, 0x56, 0xE6, 0x34, 0x99, 0x5C, 0x4A, 0x6E, 0xFB, 0xB5, 0x4E, 0x5B, 0x59, 0xB3, 0x32, 0x81 } },
{ 61061, 1001, 960, 540, "yuv420p", false, { 0xF7, 0x64, 0x38, 0x53, 0xC6, 0x73, 0x1D, 0xF1, 0x13, 0x67, 0x47, 0x4E, 0xBE, 0xCC, 0x73, 0xBB, 0x0C, 0x1C, 0xAD, 0x7F, 0xFD, 0xC5, 0x6B, 0xF5, 0x99, 0xE9, 0x6E, 0x3B, 0x2E, 0x14, 0x95, 0xD0 } },
{ 62062, 1001, 960, 540, "yuv420p", false, { 0xC5, 0x37, 0xEF, 0xAE, 0xD0, 0x30, 0x8B, 0x4E, 0xBA, 0x09, 0xC2, 0x7B, 0x9E, 0x01, 0x10, 0xED, 0x59, 0x37, 0x19, 0x73, 0x3D, 0x11, 0x8A, 0x86, 0x87, 0x21, 0xC9, 0x95, 0x95, 0xC6, 0x5A, 0x1E } },
{ 63063, 1001, 960, 540, "yuv420p", false, { 0xC9, 0x57, 0x6B, 0xF5, 0x04, 0xE6, 0x4C, 0x97, 0x5D, 0xFA, 0xD5, 0x24, 0xB5, 0xBE, 0x9E, 0x5A, 0xF6, 0xB4, 0x88, 0x8A, 0x7A, 0x15, 0x05, 0x72, 0xCA, 0x96, 0x6D, 0xF4, 0x18, 0xB5, 0xF5, 0xF8 } },
{ 64064, 1001, 960, 540, "yuv420p", false, { 0xDE, 0x5A, 0x39, 0xA4, 0xF1, 0x21, 0x1A, 0x4C, 0xD6, 0x83, 0x34, 0xAB, 0xF9, 0x02, 0x51, 0x6D, 0x5D, 0x46, 0x7F, 0x4D, 0xD7, 0xD5, 0x1F, 0x9C, 0xE4, 0xF0, 0xB2, 0x0A, 0x05, 0x4A, 0x04, 0xA3 } },
{ 65065, 1001, 960, 540, "yuv420p", false, { 0x85, 0x30, 0xBA, 0x26, 0x12, 0x69, 0xFA, 0xA0, 0x11, 0x7E, 0xBE, 0x41, 0xA9, 0x56, 0x75, 0xD6, 0x93, 0xAF, 0x5F, 0x65, 0x41, 0x41, 0x29, 0x6F, 0xC6, 0x34, 0xEE, 0xA7, 0x40, 0xD8, 0xE0, 0x25 } },
{ 66066, 1001, 960, 540, "yuv420p", false, { 0x39, 0x7A, 0x96, 0x4C, 0xED, 0x78, 0xD7, 0x60, 0x8A, 0x9C, 0xD7, 0x84, 0xF3, 0x9E, 0x10, 0x75, 0x75, 0x9D, 0xC7, 0x5B, 0x7E, 0xB8, 0x50, 0x8A, 0xDE, 0xC0, 0xD7, 0xC1, 0xA3, 0x94, 0xCA, 0x45 } },
{ 67067, 1001, 960, 540, "yuv420p", false, { 0xE1, 0x0A, 0xDC, 0xF6, 0xF9, 0x36, 0x5E, 0xE4, 0xF9, 0x26, 0xD7, 0xA1, 0x91, 0xA8, 0x49, 0x71, 0x76, 0x14, 0xB9, 0xA4, 0xE4, 0x14, 0x19, 0x7D, 0xB0, 0xEB, 0xAE, 0x69, 0x41, 0x38, 0x6E, 0xB2 } },
{ 68068, 1001, 960, 540, "yuv420p", false, { 0xBA, 0xD3, 0xC0, 0x58, 0xC4, 0xE2, 0xDC, 0xA0, 0x06, 0x43, 0xB7, 0xA5, 0x52, 0xA1, 0xDF, 0x94, 0xA6, 0xC2, 0xAE, 0xC8, 0x19, 0xE3, 0xBC, 0xA9, 0x7C, 0xBD, 0x65, 0x61, 0x81, 0xF7, 0xB4, 0xBF } },
{ 69069, 1001, 960, 540, "yuv420p", false, { 0xAB, 0x67, 0x91, 0xE1, 0xF6, 0x94, 0x93, 0x85, 0xB2, 0xBE, 0xFE, 0xFC, 0xBD, 0xFD, 0x6C, 0xFF, 0x4D, 0x17, 0xC5, 0x20, 0x13, 0xED, 0x48, 0xD2, 0xEE, 0x59, 0xD4, 0x49, 0xE2, 0x2C, 0x79, 0x90 } },
{ 70070, 1001, 960, 540, "yuv420p", false, { 0xEB, 0xF2, 0xA6, 0x10, 0xD5, 0xCF, 0x4B, 0x4D, 0xFA, 0x95, 0xCC, 0xD3, 0x54, 0xE9, 0x39, 0x86, 0xF4, 0x8A, 0x1C, 0xEF, 0x42, 0xD8, 0x53, 0x23, 0x7B, 0x98, 0x34, 0x78, 0xE5, 0xFA, 0x8D, 0x9E } },
{ 71071, 1001, 960, 540, "yuv420p", false, { 0xC7, 0x88, 0xFD, 0x06, 0xBE, 0x42, 0xB3, 0xDE, 0xD3, 0x66, 0x39, 0xC2, 0x57, 0x3C, 0x7C, 0x6A, 0x97, 0x5B, 0x71, 0xD1, 0x91, 0x63, 0x89, 0x12, 0x92, 0xCC, 0xBE, 0xAD, 0x5A, 0x2E, 0x75, 0x2E } },
{ 72072, 1001, 960, 540, "yuv420p", false, { 0x4D, 0x6B, 0x3C, 0x3C, 0x94, 0x28, 0xEB, 0xCA, 0xC6, 0x53, 0xB6, 0x0D, 0xA4, 0x91, 0x41, 0x68, 0xA8, 0xB9, 0x0A, 0x93, 0x2C, 0x72, 0x45, 0x49, 0xE3, 0x51, 0x27, 0x01, 0xA6, 0x13, 0x6A, 0x5A } },
{ 73073, 1001, 960, 540, "yuv420p", false, { 0x97, 0x83, 0x55, 0x3F, 0x34, 0x36, 0x1C, 0x53, 0x65, 0xFB, 0xED, 0xF7, 0x8C, 0xB8, 0x82, 0xEB, 0x74, 0x71, 0xA9, 0x58, 0xBB, 0x34, 0xD5, 0x34, 0x56, 0x88, 0x95, 0x3A, 0xE1, 0x3E, 0xB0, 0x57 } },
{ 74074, 1001, 960, 540, "yuv420p", false, { 0xA8, 0x05, 0xC6, 0x01, 0xF3, 0x58, 0x10, 0xC6, 0x60, 0x69, 0xBC, 0x62, 0xFB, 0xB5, 0x2E, 0xFE, 0xD4, 0x77, 0x3A, 0x4C, 0x70, 0xF2, 0x96, 0xFB, 0x04, 0xF9, 0xF4, 0xE1, 0xFC, 0x9C, 0xA5, 0x1A } },
{ 75075, 1001, 960, 540, "yuv420p", false, { 0x58, 0xA8, 0x80, 0x6C, 0x3E, 0x66, 0xE4, 0x13, 0x19, 0x7A, 0xAB, 0x4A, 0xA8, 0xA0, 0x95, 0xBF, 0x9B, 0xD2, 0xC6, 0x41, 0x71, 0x14, 0xB0, 0xC0, 0x58, 0x67, 0x1A, 0x7D, 0x16, 0x05, 0x35, 0xD8 } },
{ 76076, 1001, 960, 540, "yuv420p", false, { 0x68, 0x84, 0x2F, 0xF5, 0x45, 0x6D, 0x9B, 0x49, 0x02, 0xEF, 0x3B, 0x21, 0x62, 0x77, 0x5B, 0xD0, 0x1A, 0xD5, 0x28, 0x1D, 0xE5, 0x0F, 0xF9, 0x6F, 0x29, 0xFC, 0x8E, 0x72, 0xF2, 0x5D, 0x46, 0x23 } },
{ 77077, 1001, 960, 540, "yuv420p", false, { 0x41, 0x28, 0x5A, 0x38, 0x79, 0xE3, 0xD7, 0xAB, 0xCA, 0x20, 0x7D, 0x53, 0x72, 0x19, 0x46, 0xC5, 0x2A, 0xE8, 0x17, 0xE4, 0x61, 0x02, 0xFC, 0x46, 0x69, 0xE1, 0x05, 0xB1, 0x9B, 0xBE, 0xF7, 0xB9 } },
{ 78078, 1001, 960, 540, "yuv420p", false, { 0xB3, 0x9E, 0x9D, 0x13, 0x47, 0xCF, 0x43, 0xCC, 0xC7, 0xBD, 0xC9, 0xB2, 0x31, 0x35, 0xD3, 0x5C, 0x42, 0xDF, 0x42, 0x9A, 0x37, 0x6B, 0x9C, 0xB4, 0xA5, 0x54, 0x82, 0xD5, 0x9E, 0x5B, 0xBC, 0xB9 } },
{ 79079, 1001, 960, 540, "yuv420p", false, { 0xF2, 0xF4, 0x23, 0x9C, 0x7D, 0xFB, 0x76, 0x60, 0x9D, 0x2D, 0x8E, 0xD9, 0x79, 0xE5, 0x18, 0x3F, 0xF2, 0x5B, 0x5C, 0x1E, 0x77, 0xEF, 0xC6, 0x3E, 0xDD, 0x02, 0x04, 0xCC, 0x6C, 0x44, 0xEE, 0xA0 } },
{ 80080, 1001, 960, 540, "yuv420p", false, { 0xB1, 0x45, 0x63, 0x50, 0xD3, 0x3C, 0x3E, 0x74, 0x4A, 0xEB, 0x61, 0x35, 0x9A, 0x03, 0xF2, 0x14, 0x9C, 0x66, 0x36, 0x8A, 0x2C, 0x12, 0x9A, 0x8A, 0xE1, 0xF9, 0x77, 0xC9, 0xC7, 0xE6, 0xD7, 0x0A } },
{ 81081, 1001, 960, 540, "yuv420p", false, { 0x8C, 0x6B, 0xD7, 0x1B, 0xC8, 0x3E, 0xF9, 0x21, 0xA2, 0x3D, 0x43, 0xD0, 0xF8, 0x41, 0x96, 0x17, 0xED, 0x19, 0x2B, 0xC1, 0x71, 0x65, 0x04, 0x58, 0x0F, 0x7C, 0x90, 0xDF, 0x01, 0xC0, 0x19, 0x68 } },
{ 82082, 1001, 960, 540, "yuv420p", false, { 0x2F, 0x09, 0xB7, 0xAA, 0x9E, 0x42, 0x85, 0xB5, 0x0D, 0xCA, 0xE3, 0x43, 0x0E, 0x38, 0xBE, 0x59, 0x96, 0x6F, 0x92, 0x33, 0x2B, 0x20, 0xE2, 0x99, 0x3E, 0x61, 0xA7, 0xF4, 0x4E, 0xEA, 0x80, 0x34 } },
{ 83083, 1001, 960, 540, "yuv420p", false, { 0x1E, 0xCC, 0xEA, 0x17, 0x60, 0x82, 0x3A, 0x10, 0x83, 0xB3, 0x33, 0x00, 0x72, 0xB5, 0x8C, 0xF9, 0x8E, 0x27, 0xD2, 0x90, 0xDF, 0x17, 0x0C, 0xD8, 0x1F, 0x26, 0x3C, 0xBC, 0x3E, 0xC7, 0x72, 0x8D } }
};
#endif // _FFMS_TEST_TESTMP4DATA_H

View file

@ -0,0 +1,102 @@
#include <cfloat>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <ffms.h>
#include <gtest/gtest.h>
#include "tests.h"
namespace {
class DisplayMatrixTest : public ::testing::Test {
protected:
virtual void SetUp();
virtual void TearDown();
bool DoIndexing(std::string);
FFMS_Indexer* indexer;
FFMS_Index* index;
int video_track_idx;
FFMS_VideoSource* video_source;
const FFMS_VideoProperties* VP;
FFMS_ErrorInfo E;
char ErrorMsg[1024];
std::string SamplesDir;
};
void DisplayMatrixTest::SetUp() {
indexer = nullptr;
index = nullptr;
video_track_idx = -1;
video_source = nullptr;
VP = nullptr;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
SamplesDir = STRINGIFY(SAMPLES_DIR);
FFMS_Init(0,0);
}
void DisplayMatrixTest::TearDown() {
FFMS_DestroyIndex(index);
FFMS_DestroyVideoSource(video_source);
FFMS_Deinit();
}
bool DisplayMatrixTest::DoIndexing(std::string file_name) {
indexer = FFMS_CreateIndexer(file_name.c_str(), &E);
NULL_CHECK(indexer);
FFMS_TrackTypeIndexSettings(indexer, FFMS_TYPE_VIDEO, 1, 0);
index = FFMS_DoIndexing2(indexer, 0, &E);
NULL_CHECK(index);
video_track_idx = FFMS_GetFirstTrackOfType(index, FFMS_TYPE_VIDEO, &E);
EXPECT_GE(0, video_track_idx);
video_source = FFMS_CreateVideoSource(file_name.c_str(), video_track_idx, index, 1, FFMS_SEEK_NORMAL, &E);
NULL_CHECK(video_source);
VP = FFMS_GetVideoProperties(video_source); // Can't fail
return true;
}
TEST_F(DisplayMatrixTest, HFlip270) {
std::string FilePath = SamplesDir + "/qrvideo_hflip_90.mov";
ASSERT_TRUE(DoIndexing(FilePath));
ASSERT_EQ(VP->Flip, 1);
ASSERT_EQ(VP->Rotation, 90);
}
TEST_F(DisplayMatrixTest, HFlip90) {
std::string FilePath = SamplesDir + "/qrvideo_hflip_270.mov";
ASSERT_TRUE(DoIndexing(FilePath));
ASSERT_EQ(VP->Flip, 1);
ASSERT_EQ(VP->Rotation, 270);
}
TEST_F(DisplayMatrixTest, VFlip180) {
std::string FilePath = SamplesDir + "/qrvideo_vflip.mov";
ASSERT_TRUE(DoIndexing(FilePath));
ASSERT_EQ(VP->Flip, 1);
ASSERT_EQ(VP->Rotation, 180);
}
} //namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

160
ffms2/test/hdr.cpp Normal file
View file

@ -0,0 +1,160 @@
#include <cfloat>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <ffms.h>
#include <gtest/gtest.h>
#include "tests.h"
typedef struct HDR10Data {
double MasteringDisplayPrimariesX[3];
double MasteringDisplayPrimariesY[3];
double MasteringDisplayWhitePointX;
double MasteringDisplayWhitePointY;
double MasteringDisplayMinLuminance;
double MasteringDisplayMaxLuminance;
} HDR10Data;
#define TEST_DOUBLE(A, B) ((A == B) || (fabs(A - B) < DBL_EPSILON))
const HDR10Data StreamHDR10Data = {
{ 35400.0 / 50000.0, 8500.0 / 50000.0, 6550.0 / 50000.0 },
{ 14599.0 / 50000.0 , 39850.0 / 50000.0 , 2300.0 / 50000.0 },
15634.0 / 50000.0,
16450.0 / 50000.0,
10.0 / 10000.0,
10000000.0 / 10000.0
};
const HDR10Data ContainerHDR10Data {
{ 34000.0 / 50000.0, 13250.0 / 50000.0, 7500.0 / 50000.0 },
{ 16000.0 / 50000.0, 34500.0 / 50000.0, 3000.0 / 50000.0 },
15635.0 / 50000.0,
16450.0 / 50000.0,
100.0 / 10000.0,
10000000.0 / 10000.0
};
namespace {
class HDR10Test : public ::testing::Test {
protected:
virtual void SetUp();
virtual void TearDown();
bool DoIndexing(std::string);
FFMS_Indexer* indexer;
FFMS_Index* index;
int video_track_idx;
FFMS_VideoSource* video_source;
const FFMS_VideoProperties* VP;
FFMS_ErrorInfo E;
char ErrorMsg[1024];
std::string SamplesDir;
};
void HDR10Test::SetUp() {
indexer = nullptr;
index = nullptr;
video_track_idx = -1;
video_source = nullptr;
VP = nullptr;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
SamplesDir = STRINGIFY(SAMPLES_DIR);
FFMS_Init(0,0);
}
void HDR10Test::TearDown() {
FFMS_DestroyIndex(index);
FFMS_DestroyVideoSource(video_source);
FFMS_Deinit();
}
bool HDR10Test::DoIndexing(std::string file_name) {
indexer = FFMS_CreateIndexer(file_name.c_str(), &E);
NULL_CHECK(indexer);
FFMS_TrackTypeIndexSettings(indexer, FFMS_TYPE_VIDEO, 1, 0);
index = FFMS_DoIndexing2(indexer, 0, &E);
NULL_CHECK(index);
video_track_idx = FFMS_GetFirstTrackOfType(index, FFMS_TYPE_VIDEO, &E);
EXPECT_GE(0, video_track_idx);
video_source = FFMS_CreateVideoSource(file_name.c_str(), video_track_idx, index, 1, FFMS_SEEK_NORMAL, &E);
NULL_CHECK(video_source);
VP = FFMS_GetVideoProperties(video_source); // Can't fail
return true;
}
TEST_F(HDR10Test, StreamData) {
std::string FilePath = SamplesDir + "/hdr10tags-stream.mp4";
ASSERT_TRUE(DoIndexing(FilePath));
ASSERT_TRUE(!!VP->HasMasteringDisplayPrimaries);
for (int i = 0; i < 3; i++) {
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayPrimariesX[i], StreamHDR10Data.MasteringDisplayPrimariesX[i]));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayPrimariesY[i], StreamHDR10Data.MasteringDisplayPrimariesY[i]));
}
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayWhitePointX, StreamHDR10Data.MasteringDisplayWhitePointX));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayWhitePointY, StreamHDR10Data.MasteringDisplayWhitePointY));
ASSERT_TRUE(!!VP->HasMasteringDisplayLuminance);
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayMinLuminance, StreamHDR10Data.MasteringDisplayMinLuminance));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayMaxLuminance, StreamHDR10Data.MasteringDisplayMaxLuminance));
}
TEST_F(HDR10Test, ContainerData) {
std::string FilePath = SamplesDir + "/hdr10tags-container.mkv";
ASSERT_TRUE(DoIndexing(FilePath));
// Stream HDR metadata should be used.
ASSERT_TRUE(!!VP->HasMasteringDisplayPrimaries);
for (int i = 0; i < 3; i++) {
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayPrimariesX[i], ContainerHDR10Data.MasteringDisplayPrimariesX[i]));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayPrimariesY[i], ContainerHDR10Data.MasteringDisplayPrimariesY[i]));
}
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayWhitePointX, ContainerHDR10Data.MasteringDisplayWhitePointX));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayWhitePointY, ContainerHDR10Data.MasteringDisplayWhitePointY));
ASSERT_TRUE(!!VP->HasMasteringDisplayLuminance);
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayMinLuminance, ContainerHDR10Data.MasteringDisplayMinLuminance));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayMaxLuminance, ContainerHDR10Data.MasteringDisplayMaxLuminance));
}
TEST_F(HDR10Test, StreamAndContainerData) {
std::string FilePath = SamplesDir + "/hdr10tags-both.mkv";
ASSERT_TRUE(DoIndexing(FilePath));
// Stream HDR metadata should be used.
ASSERT_TRUE(!!VP->HasMasteringDisplayPrimaries);
for (int i = 0; i < 3; i++) {
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayPrimariesX[i], StreamHDR10Data.MasteringDisplayPrimariesX[i]));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayPrimariesY[i], StreamHDR10Data.MasteringDisplayPrimariesY[i]));
}
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayWhitePointX, StreamHDR10Data.MasteringDisplayWhitePointX));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayWhitePointY, StreamHDR10Data.MasteringDisplayWhitePointY));
ASSERT_TRUE(!!VP->HasMasteringDisplayLuminance);
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayMinLuminance, StreamHDR10Data.MasteringDisplayMinLuminance));
ASSERT_TRUE(TEST_DOUBLE(VP->MasteringDisplayMaxLuminance, StreamHDR10Data.MasteringDisplayMaxLuminance));
}
} //namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

142
ffms2/test/indexer.cpp Normal file
View file

@ -0,0 +1,142 @@
#include <algorithm>
#include <cstring>
#include <string>
#include <random>
#include <vector>
#include <ffms.h>
#include <gtest/gtest.h>
#include "data/test.mp4.cpp"
#include "tests.h"
namespace {
const TestDataMap TestFiles[] = {
TEST_ENTRY("test.mp4", testmp4data)
};
class IndexerTest : public ::testing::TestWithParam<TestDataMap> {
protected:
virtual void SetUp();
virtual void TearDown();
bool DoIndexing(std::string);
FFMS_Indexer* indexer;
FFMS_Index* index;
int video_track_idx;
FFMS_VideoSource* video_source;
const FFMS_VideoProperties* VP;
FFMS_ErrorInfo E;
char ErrorMsg[1024];
std::string SamplesDir;
};
void IndexerTest::SetUp() {
indexer = nullptr;
index = nullptr;
video_track_idx = -1;
video_source = nullptr;
VP = nullptr;
E.Buffer = ErrorMsg;
E.BufferSize = sizeof(ErrorMsg);
SamplesDir = STRINGIFY(SAMPLES_DIR);
FFMS_Init(0,0);
}
void IndexerTest::TearDown() {
FFMS_DestroyIndex(index);
FFMS_DestroyVideoSource(video_source);
FFMS_Deinit();
}
bool IndexerTest::DoIndexing(std::string file_name) {
indexer = FFMS_CreateIndexer(file_name.c_str(), &E);
NULL_CHECK(indexer);
FFMS_TrackTypeIndexSettings(indexer, FFMS_TYPE_VIDEO, 1, 0);
index = FFMS_DoIndexing2(indexer, 0, &E);
NULL_CHECK(index);
video_track_idx = FFMS_GetFirstTrackOfType(index, FFMS_TYPE_VIDEO, &E);
EXPECT_GE(0, video_track_idx);
video_source = FFMS_CreateVideoSource(file_name.c_str(), video_track_idx, index, 1, FFMS_SEEK_NORMAL, &E);
NULL_CHECK(video_source);
VP = FFMS_GetVideoProperties(video_source); // Can't fail
return true;
}
TEST_P(IndexerTest, ValidateFrameCount) {
TestDataMap P = GetParam();
std::string FilePath = SamplesDir + "/" + P.Filename;
ASSERT_TRUE(DoIndexing(FilePath));
ASSERT_EQ(P.TestDataLen, VP->NumFrames);
}
TEST_P(IndexerTest, ReverseAccessingFrame) {
TestDataMap P = GetParam();
std::string FilePath = SamplesDir + "/" + P.Filename;
ASSERT_TRUE(DoIndexing(FilePath));
for (int i = VP->NumFrames - 1; i > 0; i--) {
std::stringstream ss;
ss << "Testing Frame: " << i;
SCOPED_TRACE(ss.str());
FFMS_Track *track = FFMS_GetTrackFromIndex(index, video_track_idx);
const FFMS_FrameInfo *info = FFMS_GetFrameInfo(track, i);
const FFMS_Frame* frame = FFMS_GetFrame(video_source, i, &E);
ASSERT_NE(nullptr, frame);
ASSERT_TRUE(CheckFrame(frame, info, &P.TestData[i]));
}
}
TEST_P(IndexerTest, RandomAccessingFrame) {
TestDataMap P = GetParam();
std::string FilePath = SamplesDir + "/" + P.Filename;
ASSERT_TRUE(DoIndexing(FilePath));
std::vector<int> FrameNums;
for (int i = 0; i < VP->NumFrames; i++)
FrameNums.push_back(i);
std::random_device Device;
std::mt19937 Gen(Device());
std::shuffle(FrameNums.begin(), FrameNums.end(), Gen);
for (int i = 0; i < VP->NumFrames; i++) {
int num = FrameNums[i];
std::stringstream ss;
ss << "Testing Frame: " << num;
SCOPED_TRACE(ss.str());
FFMS_Track *track = FFMS_GetTrackFromIndex(index, video_track_idx);
const FFMS_FrameInfo *info = FFMS_GetFrameInfo(track, num);
const FFMS_Frame* frame = FFMS_GetFrame(video_source, num, &E);
ASSERT_NE(nullptr, frame);
ASSERT_TRUE(CheckFrame(frame, info, &P.TestData[num]));
}
}
INSTANTIATE_TEST_CASE_P(ValidateIndexer, IndexerTest, ::testing::ValuesIn(TestFiles));
} //namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

51
ffms2/test/tests.cpp Normal file
View file

@ -0,0 +1,51 @@
#include <string>
#include <cstring>
#include <ffms.h>
#include <gtest/gtest.h>
extern "C" {
#include <libavutil/mem.h>
#include <libavutil/pixdesc.h>
#include <libavutil/sha.h>
}
#include "tests.h"
bool CheckFrame(const FFMS_Frame *Frame, const FFMS_FrameInfo *info, const TestFrameData *Data) {
EQ_CHECK(info->PTS, Data->PTS);
EQ_CHECK(!!info->KeyFrame, Data->Keyframe);
EQ_CHECK(!!Frame->KeyFrame, Data->Keyframe);
EQ_CHECK(Frame->EncodedWidth, Data->Width);
EQ_CHECK(Frame->EncodedHeight, Data->Height);
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat) Frame->ConvertedPixelFormat);
NULL_CHECK(desc);
EXPECT_STREQ(desc->name, Data->PixelFormat);
if (!!strcmp(desc->name, Data->PixelFormat))
return false;
struct AVSHA *sha = av_sha_alloc();
NULL_CHECK(sha);
int ret = av_sha_init(sha, 256);
EQ_CHECK(ret, 0);
for (int i = 0; i < av_pix_fmt_count_planes((AVPixelFormat) Frame->ConvertedPixelFormat); i++) {
const int subh = i == 0 ? 0 : desc->log2_chroma_h;
const int subw = i == 0 ? 0 : desc->log2_chroma_w;
for (int y = 0; y < Frame->EncodedHeight >> subh; y++)
av_sha_update(sha, Frame->Data[i] + y * Frame->Linesize[i], Frame->EncodedWidth >> subw);
}
uint8_t digest[32];
av_sha_final(sha, &digest[0]);
av_free(sha);
bool ok;
EXPECT_TRUE((ok = !memcmp(&Data->SHA256[0], &digest[0], 32)));
return ok;
}

40
ffms2/test/tests.h Normal file
View file

@ -0,0 +1,40 @@
#ifndef _FFMS2_TESTS_H
#define _FFMS2_TESTS_H
#include <ffms.h>
#include <gtest/gtest.h>
extern "C" {
#include <libavutil/mem.h>
#include <libavutil/pixdesc.h>
#include <libavutil/sha.h>
}
#include "data/data.h"
#define NULL_CHECK(arg) do { \
EXPECT_NE(nullptr, arg); \
if (arg == nullptr) \
return false; \
} while(0)
#define EQ_CHECK(arg1,arg2) do { \
EXPECT_EQ(arg1, arg2); \
if (arg1 != arg2) \
return false; \
} while (0)
#define STRINGIFY2(x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#define TEST_ENTRY(file, data) { file, data, sizeof(data) / sizeof(*data) }
typedef struct TestDataMap {
const char *Filename;
const TestFrameData *TestData;
const size_t TestDataLen;
} TestDataMap;
bool CheckFrame(const FFMS_Frame *Frame, const FFMS_FrameInfo *info, const TestFrameData *Data);
#endif

102
ffms2/test/tools/gendata Executable file
View file

@ -0,0 +1,102 @@
#!/usr/bin/env perl
use strict;
use warnings;
my $filename = shift;
my $arrayname = shift;
my $track = shift;
my @timestamps;
my @hashes;
my @durations;
my @widths;
my @heights;
my @pixfmts;
my @keyframes;
my $ticks = 1;
my $frames = 0;
if (!defined($filename) || !defined($arrayname) || !defined($track)) {
print("Usage: gendata [filename] [arrayname] [track] > output.cpp\n");
exit(0);
}
my $version = "Unknown";
for (`ffmpeg -version 2>&1`) {
chomp;
s/^(ffmpeg version .+) Copyright.+/$1/;
$version = $_;
last;
}
print("// Autogenerated from $filename by gendata with $version\n\n");
print("#ifndef _FFMS_TEST_".uc($arrayname)."_H\n");
print("#define _FFMS_TEST_".uc($arrayname)."_H\n\n");
print("#include \"data.h\"\n\n");
for (`ffmpeg -i $filename -map $track:0 -f framehash - 2>/dev/null`) {
if (/^#/) {
if (!/^#tb/) {
next;
}
chomp;
s/^#tb \d: //;
my @tb = split('/');
$ticks = int($tb[0]);
next;
}
chomp;
s/\s//g;
my @fields = split(',');
push(@hashes, $fields[5]);
$frames++;
}
for (`ffprobe -show_frames -select_streams $track $filename 2>/dev/null`) {
chomp;
if (/^width/) {
my @w = split('=');
push(@widths, int($w[1]));
} elsif (/^height/) {
my @h = split('=');
push(@heights, int($h[1]));
} elsif (/^pix_fmt/) {
my @p = split('=');
push(@pixfmts, $p[1]);
} elsif (/^key_frame/) {
my @k = split('=');
push(@keyframes, (int($k[1]) == 1 ? "true" : "false"));
} elsif (/^pkt_pts=/) {
my @t = split('=');
push(@timestamps, int($t[1]));
} elsif (/^pkt_duration=/) {
my @d = split('=');
push(@durations, int($d[1]));
} else {
next;
}
}
print("const TestFrameData $arrayname\[$frames] = {\n");
for (my $i = 0; $i < $frames; $i++) {
print(" { $timestamps[$i], $durations[$i], $widths[$i], $heights[$i], \"$pixfmts[$i]\", $keyframes[$i], {");
my $hash = $hashes[$i];
$hash =~ s/(..)/ 0x\U$1,/g;
$hash =~ s/,$//;
print($hash);
print(" } }");
if ($i != $frames - 1) {
print(",");
}
print("\n");
}
print("};\n\n");
print("#endif // _FFMS_TEST_".uc($arrayname)."_H\n");

27
ffms2/version.sh Executable file
View file

@ -0,0 +1,27 @@
#! /bin/sh
strip_echo () {
printf '%s' "$(echo "$@" | tr -d '\n')"
}
echo_maybe () {
if test -n "$2"; then
strip_echo "$1$2"
exit 1
fi
}
# Make sure we're in an useful dir (for out-of-tree builds)
cd "$(dirname $0)"
echo_maybe '' "$(cat .version 2>/dev/null)"
echo_maybe '' "$(awk -F '[(< |)]+' '/define FFMS_VERSION/ { printf "%d.%d.%d%s", $3, $5, $7, ($9 ? sprintf(".%d", $9) : "") }' include/ffms.h)"
echo_maybe '' "$(perl -ne '/define FFMS_VERSION.*?(\d+) << 24.*?(\d+) << 16.*?(\d+) << 8.*?(\d+)/ && print "$1.$2.$3". ($4 ? ".$4" : "")' include/ffms.h)"
# All of the following break pkg-config version checking!
# But if we get to this point we can't output anything "proper" anymore so at least try to be useful
echo_maybe 'r' "$(git log HEAD~1.. 2>/dev/null | grep git-svn-id | cut -d@ -f2 | cut -d' ' -f1)"
echo_maybe 'git-r' "$(git log HEAD~1.. 2>/dev/null | sed 1q | cut -d' ' -f2 | head -c7)"
# While git returns no output when not on a git repository,
# svnversion still does, so run it last
echo_maybe 'r' "$(svnversion 2>/dev/null)"
echo_maybe '' "unknown"

356
singe/main.c Normal file
View file

@ -0,0 +1,356 @@
#include <stdio.h>
#include <SDL2/SDL.h>
#include <ffms.h>
#include "stddclmr.h"
// /home/scott/code/singe2/videotest/Stargate.m4v
// /home/scott/code/singe2/videotest/TestClip_720x480_29.97fps_2000_frames.avi
#define byte unsigned char
#define bool unsigned char
#define true 1
#define false 0
#define AUDIO_SAMPLES 1024
void die(char *fmt, ...);
int FFMS_CC indexCallBack(int64_t Current, int64_t Total, void *ICPrivate);
void say(char *fmt, ...);
__attribute__((__format__(__printf__, 1, 0)))
void die(char *fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
printf("\n");
fflush(stderr);
exit(1);
}
int FFMS_CC indexCallBack(int64_t current, int64_t total, void *ICPrivate) {
static int lastPercent = 0;
int thisPercent = 0;
(void)ICPrivate;
if ((current == 0) && (total == 0)) {
lastPercent = 0; // Reset
} else {
thisPercent = (int)((double)current / (double)total * 100.0);
if (thisPercent != lastPercent) {
lastPercent = thisPercent;
say("Indexing: %d%%", thisPercent);
}
}
return 0;
}
__attribute__((__format__(__printf__, 1, 0)))
void say(char *fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stdout, fmt, args);
va_end(args);
printf("\n");
fflush(stdout);
}
int main(int argc, char *argv[]) {
int err = 0;
int audioTrack = -1;
int videoTrack = -1;
int pixelFormats[2];
int frame = 0;
int audioSampleSize = 0;
bool running = true;
bool playing = true;
bool resetTime = false;
int64_t frameDeltaTime = 0;
int64_t lastFrameTime = 0;
int64_t timestamp = 0;
int64_t audioPosition = 0;
int64_t audioCount = 0;
Uint32 lastTickTime = 0;
char *filename = argv[1];
char errMsg[1024];
char indexName[1024];
byte *audioBuffer = NULL;
byte audioSampleBytes = 0;
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_AudioSpec audioWant;
SDL_AudioSpec audioHave;
SDL_AudioDeviceID audioDevice = 0;
FFMS_Index *index = NULL;
FFMS_Indexer *indexer = NULL;
SDL_Texture *videoTexture = NULL;
FFMS_ErrorInfo errInfo;
FFMS_AudioSource *audioSource = NULL;
FFMS_VideoSource *videoSource = NULL;
const FFMS_AudioProperties *audioProps = NULL;
const FFMS_VideoProperties *videoProps = NULL;
const FFMS_Frame *propFrame = NULL;
const FFMS_TrackTimeBase *videoTimeBase = NULL;
const FFMS_Frame *frameData = NULL;
const FFMS_FrameInfo *frameInfo = NULL;
// Did we get a filename to open?
if (argc != 2) die("Usage: %s <filename>\n", argv[0]);
// Init SDL
err = SDL_Init(SDL_INIT_EVERYTHING);
if (err != 0) die("%s", SDL_GetError());
// Create Resizable Window
window = SDL_CreateWindow(filename, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, SDL_WINDOW_RESIZABLE);
if (window == NULL) die("%s", SDL_GetError());
// Create an accelerated renderer.
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) die("%s", SDL_GetError());
// Clear screen with black
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// Start FFMS
FFMS_Init(0, 0);
errInfo.Buffer = errMsg;
errInfo.BufferSize = sizeof(errMsg);
errInfo.ErrorType = FFMS_ERROR_SUCCESS;
errInfo.SubType = FFMS_ERROR_SUCCESS;
// Index file
snprintf(indexName, 1024, "%s.index", filename);
index = FFMS_ReadIndex(indexName, &errInfo);
if (index) {
if (FFMS_IndexBelongsToFile(index, filename, &errInfo)) {
FFMS_DestroyIndex(index);
index = NULL;
say("Cached index is invalid.");
} else {
say("Loaded cached index.");
}
}
if (!index) {
say("Creating new index.");
indexer = FFMS_CreateIndexer(filename, &errInfo);
if (indexer == NULL) die("%s", errInfo.Buffer);
FFMS_TrackTypeIndexSettings(indexer, FFMS_TYPE_AUDIO, 1, 0);
FFMS_TrackTypeIndexSettings(indexer, FFMS_TYPE_VIDEO, 1, 0);
indexCallBack(0, 0, NULL);
FFMS_SetProgressCallback(indexer, indexCallBack, NULL);
index = FFMS_DoIndexing2(indexer, FFMS_IEH_ABORT, &errInfo);
if (index == NULL) die("%s", errInfo.Buffer);
if (FFMS_WriteIndex(indexName, index, &errInfo)) die("%s", errInfo.Buffer);
}
// Find video track
videoTrack = FFMS_GetFirstTrackOfType(index, FFMS_TYPE_VIDEO, &errInfo);
if (videoTrack < 0) die("%s", errInfo.Buffer);
videoSource = FFMS_CreateVideoSource(filename, videoTrack, index, 1, FFMS_SEEK_NORMAL, &errInfo);
if (videoSource == NULL) die("%s", errInfo.Buffer);
// Get video properties
videoProps = FFMS_GetVideoProperties(videoSource);
propFrame = FFMS_GetFrame(videoSource, 0, &errInfo);
if (propFrame == NULL) die("%s", errInfo.Buffer);
videoTimeBase = FFMS_GetTimeBase(FFMS_GetTrackFromVideo(videoSource));
// Set up output format
pixelFormats[0] = FFMS_GetPixFmt("bgra");
pixelFormats[1] = -1;
if (FFMS_SetOutputFormatV2(videoSource, pixelFormats, propFrame->EncodedWidth, propFrame->EncodedHeight, FFMS_RESIZER_BICUBIC, &errInfo)) die("%s", errInfo.Buffer);
// Find audio track
audioTrack = FFMS_GetFirstTrackOfType(index, FFMS_TYPE_AUDIO, &errInfo);
if (audioTrack < 0) die("%s", errInfo.Buffer);
audioSource = FFMS_CreateAudioSource(filename, audioTrack, index, FFMS_DELAY_FIRST_VIDEO_TRACK, &errInfo);
if (audioSource == NULL) die("%s", errInfo.Buffer);
// Get audio properties
audioProps = FFMS_GetAudioProperties(audioSource);
// Index is now part of audioSource & videoSource, so release this one
FFMS_DestroyIndex(index);
// Create video texture
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
videoTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_BGRA32, SDL_TEXTUREACCESS_STATIC, propFrame->EncodedWidth, propFrame->EncodedHeight);
if (videoTexture == NULL) die("%s", SDL_GetError());
SDL_RenderSetLogicalSize(renderer, propFrame->EncodedWidth, propFrame->EncodedHeight);
// Create audio format
SDL_zero(audioWant);
SDL_zero(audioHave);
audioWant.freq = audioProps->SampleRate;
switch (audioProps->SampleFormat) {
case FFMS_FMT_U8:
audioWant.format = AUDIO_U8;
audioSampleBytes = 1;
break;
case FFMS_FMT_S16:
audioWant.format = AUDIO_S16SYS;
audioSampleBytes = 2;
break;
case FFMS_FMT_S32:
audioWant.format = AUDIO_S32SYS;
audioSampleBytes = 4;
break;
case FFMS_FMT_FLT:
audioWant.format = AUDIO_F32SYS;
audioSampleBytes = 4;
break;
default:
die("Unknown audio sample format.");
break;
}
audioWant.channels = (unsigned char)audioProps->Channels;
audioWant.silence = 0;
audioWant.samples = AUDIO_SAMPLES;
audioWant.callback = NULL;
audioWant.userdata = NULL;
audioDevice = SDL_OpenAudioDevice(NULL, 0, &audioWant, &audioHave, 0);
if (audioDevice == 0) die("%s", SDL_GetError());
SDL_PauseAudioDevice(audioDevice, 0);
audioSampleSize = audioSampleBytes * audioProps->Channels;
audioBuffer = (byte *)malloc((size_t)(audioSampleSize * AUDIO_SAMPLES) * sizeof(byte));
if (!audioBuffer) die("Unable to allocate audio buffer.");
// Play It
say("Frames: %d (%dx%d) Audio Samples: %ld (%d Hz) %d Channel%s",
videoProps->NumFrames,
propFrame->EncodedWidth,
propFrame->EncodedHeight,
audioProps->NumSamples,
audioProps->SampleRate,
audioProps->Channels,
audioProps->Channels == 1 ? "" : "s"
);
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
running = false;
break;
case SDLK_SPACE:
playing = !playing;
resetTime = playing;
break;
case SDLK_RIGHT:
frame++;
resetTime = true;
break;
case SDLK_LEFT:
frame--;
resetTime = true;
break;
case SDLK_UP:
frame += 100;
resetTime = true;
break;
case SDLK_DOWN:
frame -= 100;
resetTime = true;
break;
}
if (resetTime) {
if (frame >= videoProps->NumFrames) {
frame = 0;
}
if (frame < 0) {
frame = videoProps->NumFrames - 1;
}
say("Seeking to frame %d", frame);
}
break;
case SDL_QUIT:
running = 0;
break;
}
}
// Handle video frames (and time)
if ((SDL_GetTicks() - lastTickTime >= frameDeltaTime) || resetTime) {
lastTickTime = SDL_GetTicks();
if (frameData) {
SDL_UpdateTexture(videoTexture, NULL, frameData->Data[0], frameData->Linesize[0]);
SDL_RenderCopy(renderer, videoTexture, NULL, NULL);
SDL_RenderPresent(renderer);
}
frameData = FFMS_GetFrame(videoSource, frame, &errInfo);
if (frameData == NULL) die("%s", errInfo.Buffer);
frameInfo = FFMS_GetFrameInfo(FFMS_GetTrackFromVideo(videoSource), frame);
timestamp = (int64_t)((frameInfo->PTS * videoTimeBase->Num) / (double)videoTimeBase->Den); // Convert to milliseconds
frameDeltaTime = timestamp - lastFrameTime;
lastFrameTime = timestamp;
if (playing) {
if (++frame >= videoProps->NumFrames) {
frame = 0;
timestamp = 0;
resetTime = true;
}
}
if (resetTime) {
lastTickTime = 0;
frameDeltaTime = 0;
audioPosition = (int64_t)((double)(timestamp * 0.001) * (double)audioProps->SampleRate);
SDL_ClearQueuedAudio(audioDevice);
resetTime = false;
}
}
// Handle audio samples
SDL_PauseAudioDevice(audioDevice, !playing);
if ((playing) && (SDL_GetQueuedAudioSize(audioDevice) < (Uint32)(AUDIO_SAMPLES * audioSampleSize)) && (audioPosition < audioProps->NumSamples)) {
audioCount = AUDIO_SAMPLES;
if (audioPosition + audioCount >= audioProps->NumSamples) {
audioCount = audioProps->NumSamples - audioPosition - 1;
}
//say("Requesting audio samples %ld to %ld - %d bytes (Queue is %lu)", audioPosition, audioPosition + audioCount, audioCount * audioSampleSize, SDL_GetQueuedAudioSize(audioDevice));
if (FFMS_GetAudio(audioSource, audioBuffer, audioPosition, audioCount, &errInfo)) die("%s", errInfo.Buffer);
SDL_QueueAudio(audioDevice, audioBuffer, (Uint32)(audioSampleSize * audioCount));
audioPosition += audioCount;
}
}
// Shutdown
free(audioBuffer);
FFMS_DestroyAudioSource(audioSource);
FFMS_DestroyVideoSource(videoSource);
FFMS_Deinit();
SDL_CloseAudioDevice(audioDevice);
SDL_DestroyTexture(videoTexture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

26
singe/singe.pro Normal file
View file

@ -0,0 +1,26 @@
TEMPLATE = app
CONFIG += console
CONFIG -= \
app_bundle
qt
FFMS = $$PWD/../ffms2
INCLUDEPATH += \
$$FFMS/include
HEADERS += \
stddclmr.h
SOURCES += \
main.c
# This is for testing only
QMAKE_RPATHDIR += \
$$FFMS/src/core/.libs
LIBS += \
-lSDL2 \
-L$$FFMS/src/core/.libs \
-lffms2

95
singe/stddclmr.h Normal file
View file

@ -0,0 +1,95 @@
#ifndef STDDCLMR_H
#define STDDCLMR_H
/*
Action figures sold separately. Add toner. All models over 18 years of age.
All rights reserved. Allow four to six weeks for delivery. An equal
opportunity employer. Any resemblance to actual persons, living or dead, is
unintentional and purely coincidental. Apply only to affected area. Approved
for veterans. As seen on TV. At participating locations only. Avoid contact
with mucous membranes. Avoid contact with skin. Avoid extreme temperatures
and store in a cool dry place. Batteries not included. Be sure each item is
properly endorsed. Beware of dog. Booths for two or more. Breaking seal
constitutes acceptance of agreement. Call toll free number before digging.
Caveat emptor. Check here if tax deductible. Close cover before striking
Colors may fade. Contains a substantial amount of non-tobacco ingredients.
Contents may settle during shipment. Contestants have been briefed on some
questions before the show. Copyright 1995 Joker's Wild. Disclaimer does
not cover hurricane, lightning, tornado, tsunami, volcanic eruption,
earthquake, flood, and other Acts of God, misuse, neglect, unauthorized
repair, damage from improper installation, broken antenna or marred cabinet,
incorrect line voltage, missing or altered serial numbers, sonic boom
vibrations, electromagnetic radiation from nuclear blasts, customer
adjustments that are not covered in the joke list, and incidents owing to
airplane crash, ship sinking, motor vehicle accidents, leaky roof, broken
glass, falling rocks, mud slides, forest fire, flying projectiles, or
dropping the item. Do not bend, fold, mutilate, or spindle. Do not place
near flammable or magnetic source. Do not puncture, incinerate, or store
above 120 degrees Fahrenheit. Do not stamp. Use other side for additional
listings. Do not use while operating a motor vehicle or heavy equipment. Do
not write below this line. Documents are provided "as is" without any
warranties expressed or implied. Don't quote me on anything. Don't quote me
on that. Driver does not carry cash. Drop in any mailbox. Edited for
television. Employees and their families are not eligible. Falling rock.
First pull up, then pull down. Flames redirected to /dev/null. For a
limited time only. For external use only. For off-road use only. For office
use only. For recreational use only. Do not disturb. Freshest if eaten
before date on carton. Hand wash only, tumble dry on low heat. If a rash,
redness, irritation, or swelling develops, discontinue use. If condition
persists, consult your physician. If defects are discovered, do not attempt
to fix them yourself, but return to an authorized service center. If
ingested, do not induce vomiting, if symptoms persist, consult a doctor.
Keep away from open flames and avoid inhaling fumes. Keep away from
sunlight, pets, and small children. Keep cool; process promptly. Limit
one-per-family please. Limited time offer, call now to ensure prompt
delivery. List at least two alternate dates. List each check separately by
bank number. List was current at time of printing. Lost ticket pays maximum
rate. May be too intense for some viewers. Must be 18 to enter. No Canadian
coins. No alcohol, dogs or horses. No anchovies unless otherwise specified.
No animals were harmed in the production of these documents. No money down.
No other warranty expressed or implied. No passes accepted for this
engagement. No postage necessary if mailed in the United States. No
preservatives added. No purchase necessary. No salt, MSG, artificial color
or flavor added. No shoes, no shirt, no service, no kidding. No solicitors.
No substitutions allowed. No transfers issued until the bus comes to a
complete stop. No user-serviceable parts inside. Not affiliated with the
American Red Cross. Not liable for damages due to use or misuse. Not
recommended for children. Not responsible for direct, indirect, incidental
or consequential damages resulting from any defect, error or failure to
perform. Not the Beatles. Objects in mirror may be closer than they appear.
One size fits all. Many suitcases look alike. Other copyright laws for
specific entries apply wherever noted. Other restrictions may apply. Package
sold by weight, not volume. Parental advisory - explicit lyrics. Penalty for
private use. Place stamp here. Please remain seated until the ride has come
to a complete stop. Possible penalties for early withdrawal. Post office will
not deliver without postage. Postage will be paid by addressee. Prerecorded
for this time zone. Price does not include taxes. Processed at location
stamped in code at top of carton. Quantities are limited while supplies last.
Read at your own risk. Record additional transactions on back of previous
stub. Replace with same type. Reproduction strictly prohibited. Restaurant
package, not for resale. Return to sender, no forwarding order on file,
unable to forward. Safety goggles may be required during use. Sanitized for
your protection. Sealed for your protection, do not use if the safety seal is
broken. See label for sequence. Shading within a garment may occur. Sign here
without admitting guilt. Simulated picture. Slightly enlarged to show detail.
Slightly higher west of the Rockies. Slippery when wet. Smoking these may be
hazardous to your health. Some assembly required. Some equipment shown is
optional. Some of the trademarks mentioned in this product appear for
identification purposes only. Subject to FCC approval. Subject to change
without notice. Substantial penalty for early withdrawal. Text may contain
material some readers may find objectionable, parental guidance is advised.
Text used in these documents is made from 100% recycled electrons and magnetic
particles. These documents do not reflect the thoughts or opinions of either
myself, my company, my friends, or my rabbit. This is not an offer to sell
securities. This offer is void where prohibited, taxed, or otherwise
restricted. This product is meant for educational purposes only. Times
approximate. Unix is a registered trademark of AT&T. Use only as directed. Use
only in a well-ventilated are. User assumes full liabilities. Void where
prohibited. We have sent the forms which seem right for you. You must be
present to win. You need not be present to win. Your canceled check is your
receipt. Your mileage may vary. I didn't do it. You can't prove anything.
This supersedes all previous notices.
*/
#endif // STDDCLMR_H

3
videotest/countFrames.sh Executable file
View file

@ -0,0 +1,3 @@
#!/bin/bash
ffmpeg -i "$1" -vcodec copy -f rawvideo -y /dev/null 2>&1 | tr ^M '\n' | awk '/^frame=/ {print $2}' | tail -n 1

15
videotest/makeTestFile.sh Executable file
View file

@ -0,0 +1,15 @@
#!/bin/bash
if [[ -e sg.vob ]]; then
rm sg.vob
fi
if [[ -e Stargate.m4v ]]; then
rm Stargate.m4v
fi
# Get the first 9 minutes or so of the episode
mplayer dvd://2 -dvd-device SG1_V1.ISO -chapter 1-1 -dumpstream -dumpfile sg.vob
# Convert five minutes of it & add frame count
ffmpeg -i sg.vob -ss 00:00:00 -t 00:05:00 -vf "drawtext=fontfile=Arial.ttf: text='%{frame_num}': x=(w-tw)/2: y=h-(2*lh): fontcolor=white: fontsize=20: box=1: boxcolor=black: boxborderw=5" Stargate.m4v