tizen 2.4 release accepted/tizen_2.4_mobile accepted/tizen/2.4/mobile/20151029.032716 submit/tizen_2.4/20151028.064342 tizen_2.4_mobile_release
authorjk7744.park <jk7744.park@samsung.com>
Sat, 24 Oct 2015 07:49:39 +0000 (16:49 +0900)
committerjk7744.park <jk7744.park@samsung.com>
Sat, 24 Oct 2015 07:49:39 +0000 (16:49 +0900)
164 files changed:
AUTHORS [new file with mode: 0644]
COPYING [new file with mode: 0644]
INSTALL [new file with mode: 0644]
Makefile.am [new file with mode: 0755]
PLUGINS [new file with mode: 0644]
README [new file with mode: 0644]
audioeq/Makefile.am [new file with mode: 0755]
audioeq/src/Makefile.am [new file with mode: 0755]
audioeq/src/gstaudioeq.c [new file with mode: 0755]
audioeq/src/gstaudioeq.h [new file with mode: 0644]
audiotp/Makefile.am [new file with mode: 0755]
audiotp/src/Makefile.am [new file with mode: 0755]
audiotp/src/gstaudiotp.c [new file with mode: 0644]
audiotp/src/gstaudiotp.h [new file with mode: 0755]
autogen.sh [new file with mode: 0755]
autoregen.sh [new file with mode: 0755]
common/ChangeLog [new file with mode: 0755]
common/Makefile.am [new file with mode: 0644]
common/c-to-xml.py [new file with mode: 0755]
common/check-exports [new file with mode: 0755]
common/check.mak [new file with mode: 0755]
common/coverage/coverage-report-entry.pl [new file with mode: 0755]
common/coverage/coverage-report.pl [new file with mode: 0755]
common/coverage/coverage-report.xsl [new file with mode: 0755]
common/coverage/lcov.mak [new file with mode: 0755]
common/gettext.patch [new file with mode: 0755]
common/glib-gen.mak [new file with mode: 0755]
common/gst-autogen.sh [new file with mode: 0755]
common/gst-xmlinspect.py [new file with mode: 0755]
common/gst.supp [new file with mode: 0755]
common/gstdoc-scangobj [new file with mode: 0755]
common/gtk-doc-plugins.mak [new file with mode: 0755]
common/gtk-doc.mak [new file with mode: 0755]
common/m4/Makefile.am [new file with mode: 0644]
common/m4/README [new file with mode: 0755]
common/m4/as-ac-expand.m4 [new file with mode: 0755]
common/m4/as-auto-alt.m4 [new file with mode: 0755]
common/m4/as-compiler-flag.m4 [new file with mode: 0755]
common/m4/as-compiler.m4 [new file with mode: 0755]
common/m4/as-docbook.m4 [new file with mode: 0755]
common/m4/as-gcc-inline-assembly.m4 [new file with mode: 0755]
common/m4/as-libtool-tags.m4 [new file with mode: 0755]
common/m4/as-libtool.m4 [new file with mode: 0755]
common/m4/as-python.m4 [new file with mode: 0755]
common/m4/as-scrub-include.m4 [new file with mode: 0755]
common/m4/as-version.m4 [new file with mode: 0755]
common/m4/ax_create_stdint_h.m4 [new file with mode: 0755]
common/m4/check.m4 [new file with mode: 0755]
common/m4/gettext.m4 [new file with mode: 0755]
common/m4/glib-gettext.m4 [new file with mode: 0755]
common/m4/gst-arch.m4 [new file with mode: 0755]
common/m4/gst-args.m4 [new file with mode: 0755]
common/m4/gst-check.m4 [new file with mode: 0755]
common/m4/gst-debuginfo.m4 [new file with mode: 0755]
common/m4/gst-default.m4 [new file with mode: 0755]
common/m4/gst-doc.m4 [new file with mode: 0755]
common/m4/gst-error.m4 [new file with mode: 0755]
common/m4/gst-feature.m4 [new file with mode: 0755]
common/m4/gst-function.m4 [new file with mode: 0755]
common/m4/gst-gettext.m4 [new file with mode: 0755]
common/m4/gst-glib2.m4 [new file with mode: 0755]
common/m4/gst-libxml2.m4 [new file with mode: 0755]
common/m4/gst-parser.m4 [new file with mode: 0755]
common/m4/gst-plugin-docs.m4 [new file with mode: 0755]
common/m4/gst-plugindir.m4 [new file with mode: 0755]
common/m4/gst-valgrind.m4 [new file with mode: 0755]
common/m4/gst-x11.m4 [new file with mode: 0644]
common/m4/gst.m4 [new file with mode: 0755]
common/m4/gtk-doc.m4 [new file with mode: 0755]
common/m4/iconv.m4 [new file with mode: 0755]
common/m4/isc-posix.m4 [new file with mode: 0755]
common/m4/lib-ld.m4 [new file with mode: 0755]
common/m4/lib-link.m4 [new file with mode: 0755]
common/m4/lib-prefix.m4 [new file with mode: 0755]
common/m4/libtool.m4 [new file with mode: 0644]
common/m4/ltoptions.m4 [new file with mode: 0644]
common/m4/ltsugar.m4 [new file with mode: 0644]
common/m4/ltversion.m4 [new file with mode: 0644]
common/m4/lt~obsolete.m4 [new file with mode: 0644]
common/m4/pkg.m4 [new file with mode: 0755]
common/m4/progtest.m4 [new file with mode: 0755]
common/mangle-tmpl.py [new file with mode: 0755]
common/plugins.xsl [new file with mode: 0755]
common/po.mak [new file with mode: 0755]
common/release.mak [new file with mode: 0755]
common/scangobj-merge.py [new file with mode: 0755]
common/upload.mak [new file with mode: 0755]
common/win32.mak [new file with mode: 0755]
configure.ac [new file with mode: 0755]
drmsrc/Makefile.am [new file with mode: 0755]
drmsrc/src/Makefile.am [new file with mode: 0755]
drmsrc/src/gstdrmsrc.c [new file with mode: 0755]
drmsrc/src/gstdrmsrc.h [new file with mode: 0755]
encodebin/Makefile.am [new file with mode: 0644]
encodebin/src/Makefile.am [new file with mode: 0644]
encodebin/src/gstencodebin.c [new file with mode: 0755]
encodebin/src/gstencodebin.h [new file with mode: 0644]
evaspixmapsink/Makefile.am [new file with mode: 0644]
evaspixmapsink/evaspixmapsink.c [new file with mode: 0755]
evaspixmapsink/evaspixmapsink.h [new file with mode: 0755]
evaspixmapsink/xv_types.h [new file with mode: 0644]
fimcconvert/Makefile.am [new file with mode: 0755]
fimcconvert/src/Makefile.am [new file with mode: 0755]
fimcconvert/src/fimc_drm_api.c [new file with mode: 0755]
fimcconvert/src/fimc_drm_api.h [new file with mode: 0755]
fimcconvert/src/gstfimcconvert.c [new file with mode: 0755]
fimcconvert/src/gstfimcconvert.h [new file with mode: 0755]
gst-autogen.sh [new file with mode: 0755]
gst-plugins-tizen1.0.manifest [new file with mode: 0644]
m4/Makefile.am [new file with mode: 0644]
m4/as-compiler-flag.m4 [new file with mode: 0755]
m4/as-version.m4 [new file with mode: 0755]
packaging/gst-plugins-tizen.spec [new file with mode: 0644]
pdpushsrc/Makefile.am [new file with mode: 0755]
pdpushsrc/src/Makefile.am [new file with mode: 0755]
pdpushsrc/src/gstpdpushsrc.c [new file with mode: 0755]
pdpushsrc/src/gstpdpushsrc.h [new file with mode: 0755]
toggle/Makefile.am [new file with mode: 0755]
toggle/src/Makefile.am [new file with mode: 0755]
toggle/src/gsttoggle.c [new file with mode: 0755]
toggle/src/gsttoggle.h [new file with mode: 0755]
wfdmanager/Makefile.am [new file with mode: 0755]
wfdmanager/gstwfdmanager.c [new file with mode: 0755]
wfdmanager/wfdbase/Makefile.am [new file with mode: 0755]
wfdmanager/wfdbase/gstwfdbasesrc.c [new file with mode: 0644]
wfdmanager/wfdbase/gstwfdbasesrc.h [new file with mode: 0644]
wfdmanager/wfdbase/gstwfdsinkmessage.c [new file with mode: 0755]
wfdmanager/wfdbase/gstwfdsinkmessage.h [new file with mode: 0755]
wfdmanager/wfdrtpbuffer/gstwfdrtpbuffer.c [new file with mode: 0644]
wfdmanager/wfdrtpbuffer/gstwfdrtpbuffer.h [new file with mode: 0755]
wfdmanager/wfdrtpbuffer/rtpstats.c [new file with mode: 0755]
wfdmanager/wfdrtpbuffer/rtpstats.h [new file with mode: 0755]
wfdmanager/wfdrtpbuffer/wfdrtpbuffer.c [new file with mode: 0755]
wfdmanager/wfdrtpbuffer/wfdrtpbuffer.h [new file with mode: 0755]
wfdmanager/wfdsrc/gstwfdsrc.c [new file with mode: 0755]
wfdmanager/wfdsrc/gstwfdsrc.h [new file with mode: 0755]
wfdtsdemux/Makefile.am [new file with mode: 0755]
wfdtsdemux/gstwfdh264parser.c [new file with mode: 0755]
wfdtsdemux/gstwfdh264parser.h [new file with mode: 0755]
wfdtsdemux/gstwfdts-private.h [new file with mode: 0755]
wfdtsdemux/gstwfdtsdefs.h [new file with mode: 0755]
wfdtsdemux/gstwfdtsdemux.c [new file with mode: 0755]
wfdtsdemux/gstwfdtsdesc.h [new file with mode: 0644]
wfdtsdemux/gstwfdtsdescriptor.c [new file with mode: 0755]
wfdtsdemux/gstwfdtsdescriptor.h [new file with mode: 0755]
wfdtsdemux/gstwfdtssection.c [new file with mode: 0755]
wfdtsdemux/gstwfdtssection.h [new file with mode: 0755]
wfdtsdemux/wfdnalutils.c [new file with mode: 0755]
wfdtsdemux/wfdnalutils.h [new file with mode: 0755]
wfdtsdemux/wfdpesparse.c [new file with mode: 0755]
wfdtsdemux/wfdpesparse.h [new file with mode: 0755]
wfdtsdemux/wfdtsbase.c [new file with mode: 0755]
wfdtsdemux/wfdtsbase.h [new file with mode: 0755]
wfdtsdemux/wfdtsdemux.c [new file with mode: 0755]
wfdtsdemux/wfdtsdemux.h [new file with mode: 0755]
wfdtsdemux/wfdtspacketizer.c [new file with mode: 0755]
wfdtsdemux/wfdtspacketizer.h [new file with mode: 0755]
wfdtsdemux/wfdtsparse.c [new file with mode: 0755]
wfdtsdemux/wfdtsparse.h [new file with mode: 0755]
xvimagesrc/Makefile.am [new file with mode: 0644]
xvimagesrc/src/Makefile.am [new file with mode: 0644]
xvimagesrc/src/gstxvimagesrc.c [new file with mode: 0644]
xvimagesrc/src/gstxvimagesrc.h [new file with mode: 0644]
xvimagesrc/src/xv_types.h [new file with mode: 0644]

diff --git a/AUTHORS b/AUTHORS
new file mode 100644 (file)
index 0000000..96cbfc8
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,5 @@
+JongHyuk Choi <jhchoi.choi@samsung.com>
+Seungbae Shin <seungbae.shin@samsung.com>
+Younghwan Ahn <younghwan_.an@samsung.com>
+Jeongmo Yang <jm80.yang@samsung.com>
+Sangchul Lee <sc11.lee@samsung.com>
diff --git a/COPYING b/COPYING
new file mode 100644 (file)
index 0000000..4a1f720
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,502 @@
+                 GNU LESSER GENERAL PUBLIC LICENSE
+                      Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+                 GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                           NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/INSTALL b/INSTALL
new file mode 100644 (file)
index 0000000..23e5f25
--- /dev/null
+++ b/INSTALL
@@ -0,0 +1,236 @@
+Installation Instructions
+*************************
+
+Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005 Free
+Software Foundation, Inc.
+
+This file is free documentation; the Free Software Foundation gives
+unlimited permission to copy, distribute and modify it.
+
+Basic Installation
+==================
+
+These are generic installation instructions.
+
+   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 only 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.  If you're
+     using `csh' on an old version of System V, you might need to type
+     `sh ./configure' instead to prevent `csh' from trying to execute
+     `configure' itself.
+
+     Running `configure' takes awhile.  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.
+
+  4. Type `make install' to install the programs and any data files and
+     documentation.
+
+  5. 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.
+
+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=c89 CFLAGS=-O2 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 must use a version of `make' that
+supports the `VPATH' variable, such as 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 `..'.
+
+   If you have to use a `make' that does not support the `VPATH'
+variable, you have 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.
+
+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'.
+
+   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.
+
+   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'.
+
+Optional Features
+=================
+
+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.
+
+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).  Here is a another example:
+
+     /bin/bash ./configure CONFIG_SHELL=/bin/bash
+
+Here the `CONFIG_SHELL=/bin/bash' operand causes subsequent
+configuration-related scripts to be executed by `/bin/bash'.
+
+`configure' Invocation
+======================
+
+`configure' recognizes the following options to control how it operates.
+
+`--help'
+`-h'
+     Print a summary of the options to `configure', and exit.
+
+`--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.
+
+`configure' also accepts some other, not widely useful, options.  Run
+`configure --help' for more details.
+
diff --git a/Makefile.am b/Makefile.am
new file mode 100755 (executable)
index 0000000..8b441bd
--- /dev/null
@@ -0,0 +1,90 @@
+
+ACLOCAL_AMFLAGS = -I common/m4
+
+aclocaldir = $(datadir)/aclocal
+
+SUBDIRS = common
+
+if USE_GST_TIZEN_ENCODEBIN
+SUBDIRS += encodebin
+endif
+
+if USE_GST_TIZEN_EVASPIXMAPSINK
+SUBDIRS += evaspixmapsink
+endif
+
+if USE_GST_TIZEN_XVIMAGESRC
+SUBDIRS += xvimagesrc
+endif
+
+if USE_GST_TIZEN_DRMSRC
+SUBDIRS += drmsrc
+endif
+
+if USE_GST_TIZEN_TOGGLE
+SUBDIRS += toggle
+endif
+
+if USE_GST_TIZEN_PD_PUSHSRC
+SUBDIRS += pdpushsrc
+endif
+
+if USE_GST_TIZEN_AUDIOTP
+SUBDIRS += audiotp
+endif
+
+if USE_GST_TIZEN_AUDIOEQ
+SUBDIRS += audioeq
+endif
+
+if USE_GST_TIZEN_FIMCCONVERT
+SUBDIRS += fimcconvert
+endif
+
+if USE_GST_TIZEN_WFDMANAGER
+SUBDIRS += wfdmanager
+endif
+
+if USE_GST_TIZEN_WFDTSDEMUX
+SUBDIRS += wfdtsdemux
+endif
+
+DIST_SUBDIRS = common
+
+if USE_GST_TIZEN_ENCODEBIN
+DIST_SUBDIRS += encodebin
+endif
+
+if USE_GST_TIZEN_XVIMAGESRC
+DIST_SUBDIRS += xvimagesrc
+endif
+
+if USE_GST_TIZEN_DRMSRC
+DIST_SUBDIRS += drmsrc
+endif
+
+if USE_GST_TIZEN_TOGGLE
+DIST_SUBDIRS += toggle
+endif
+
+if USE_GST_TIZEN_FIMCCONVERT
+DIST_SUBDIRS += fimcconvert
+endif
+
+if USE_GST_TIZEN_WFDMANAGER
+DIST_SUBDIRS += wfdmanager
+endif
+
+if USE_GST_TIZEN_WFDTSDEMUX
+DIST_SUBDIRS += wfdtsdemux
+endif
+
+
+EXTRA_DIST = \
+       gstreamer.spec gstreamer.spec.in \
+       configure.ac autogen.sh depcomp \
+       MAINTAINERS ABOUT-NLS RELEASE gstreamer.doap \
+       $(win32)
+
+check: check-exports
+
diff --git a/PLUGINS b/PLUGINS
new file mode 100644 (file)
index 0000000..a737f3a
--- /dev/null
+++ b/PLUGINS
@@ -0,0 +1,15 @@
+# This file is descriptions of the plugins which are included in gstreamer0.10-plugins-ext.
+# If any plugin is added to the gstreamer0.10-plugins-ext, that shoud be described in this file.
+#
+#
+
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+PLUGIN                 Registered Elements                                                             Description
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+avsysaudiosrc          avsysaudiosrc                                                   AV system audio source plugin
+avsyssink              avsysaudiosink, avsysmemsink                                    AV system audio sink plugin
+drmsrc                 drmsrc                                                          Plugin to read data from standad/DRM file
+encodebin              encodebin                                                       Extension encoder bin plugin
+evasimagesink          evasimagesink                                                   Evas video sink plugin
+toggle                 toggle                                                          Base transform plugin
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..9681276
--- /dev/null
+++ b/README
@@ -0,0 +1,12 @@
+gst-plugin is a template for writing your own GStreamer plug-in.
+
+The code is deliberately kept simple so that you quickly understand the basics
+of how to set up autotools and your source tree.
+
+This template demonstrates :
+- what to do in autogen.sh
+- how to setup configure.ac (your package name and version, GStreamer flags)
+- how to setup your source dir
+- what to put in Makefile.am
+
+More features might get added to this template later on.
diff --git a/audioeq/Makefile.am b/audioeq/Makefile.am
new file mode 100755 (executable)
index 0000000..308a09c
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src\r
diff --git a/audioeq/src/Makefile.am b/audioeq/src/Makefile.am
new file mode 100755 (executable)
index 0000000..c077e2c
--- /dev/null
@@ -0,0 +1,28 @@
+# plugindir is set in configure
+
+##############################################################################
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #
+##############################################################################
+plugin_LTLIBRARIES = libgstaudioeq.la
+
+##############################################################################
+# for the next set of variables, rename the prefix if you renamed the .la,   #
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #
+##############################################################################
+
+# sources used to compile this plug-in
+libgstaudioeq_la_SOURCES = gstaudioeq.c
+
+# flags used to compile this plugin
+# add other _CFLAGS and _LIBS as needed
+libgstaudioeq_la_CFLAGS = $(GST_CFLAGS)  $(GST_PLUGINS_BASE_CFLAGS) $(GST_BASE_CFLAGS) $(GST_CONTROLLER_CFLAGS)
+libgstaudioeq_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS) -lgstaudio-$(GST_MAJORMINOR) $(GST_BASE_LIBS) $(GST_CONTROLLER_LIBS) $(GST_LIBS) $(LIBM) -lgstbase-1.0  -lglib-2.0 -lgstcontroller-1.0
+libgstaudioeq_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+libgstequalizer_la_LIBTOOLFLAGS = --tag=disable-static
+
+# headers we need but don't want installed
+noinst_HEADERS = gstaudioeq.h
diff --git a/audioeq/src/gstaudioeq.c b/audioeq/src/gstaudioeq.c
new file mode 100755 (executable)
index 0000000..91e769d
--- /dev/null
@@ -0,0 +1,1292 @@
+/*
+ * audioeq
+ *
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Aditi Narula <aditi.n@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "gstaudioeq.h"
+#include <string.h>
+#include <math.h>
+
+GST_DEBUG_CATEGORY_STATIC (gst_audioeq_debug);
+#define GST_CAT_DEFAULT gst_audioeq_debug
+
+#define AUDIOEQ_ENABLE_DUMP
+#define AUDIOEQ_REDUCE_MEMCPY
+
+/* Filter signals and args */
+enum
+{
+       /* FILL ME */
+       LAST_SIGNAL
+};
+
+enum
+{
+       PROP_0,
+       PROP_FILTER_ACTION,
+       PROP_CUSTOM_EQ,
+       PROP_CUSTOM_EQ_NUM,
+       PROP_CUSTOM_EQ_FREQ,
+       PROP_CUSTOM_EQ_WIDTH,
+};
+
+enum FilterActionType
+{
+       FILTER_NONE,
+       FILTER_PRESET,
+       FILTER_ADVANCED_SETTING
+};
+
+enum SampleRate
+{
+       SAMPLERATE_48000Hz,
+       SAMPLERATE_44100Hz,
+       SAMPLERATE_32000Hz,
+       SAMPLERATE_24000Hz,
+       SAMPLERATE_22050Hz,
+       SAMPLERATE_16000Hz,
+       SAMPLERATE_12000Hz,
+       SAMPLERATE_11025Hz,
+       SAMPLERATE_8000Hz,
+
+       SAMPLERATE_NUM
+};
+
+#define DEFAULT_SAMPLE_SIZE                    2
+#define DEFAULT_VOLUME                                 15
+#define DEFAULT_GAIN                                   1
+#define DEFAULT_SAMPLE_RATE                    SAMPLERATE_44100Hz
+#define DEAFULT_CHANNELS                               2
+#define DEFAULT_FILTER_ACTION                  FILTER_NONE
+#define DEFAULT_CUSTOM_EQ_NUM          7
+
+static GstStaticPadTemplate sinktemplate =
+       GST_STATIC_PAD_TEMPLATE(
+               "sink",
+               GST_PAD_SINK,
+               GST_PAD_ALWAYS,
+               GST_STATIC_CAPS (
+                       "audio/x-raw, "
+                   "format = (string) " GST_AUDIO_NE(S16) ", "
+                       "channels = (int) [1,2]"
+                       )
+       );
+
+static GstStaticPadTemplate srctemplate =
+       GST_STATIC_PAD_TEMPLATE(
+               "src",
+               GST_PAD_SRC,
+               GST_PAD_ALWAYS,
+               GST_STATIC_CAPS (
+                       "audio/x-raw, "
+                   "format = (string) " GST_AUDIO_NE(S16) ", "
+                       "channels = (int) [1,2]"
+                       )
+       );
+
+static void gst_iir_equalizer_child_proxy_interface_init (gpointer g_iface,
+    gpointer iface_data);
+
+static void gst_iir_equalizer_finalize (GObject * object);
+
+static gboolean gst_iir_equalizer_setup (GstAudioFilter * filter,
+    GstAudioRingBufferSpec * fmt);
+
+G_DEFINE_TYPE_WITH_CODE(Gstaudioeq, gst_audioeq, GST_TYPE_BASE_TRANSFORM,
+                        G_IMPLEMENT_INTERFACE(GST_TYPE_CHILD_PROXY, gst_iir_equalizer_child_proxy_interface_init));
+
+static void gst_audioeq_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);
+static void gst_audioeq_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
+#ifdef AUDIOEQ_REDUCE_MEMCPY
+static GstFlowReturn gst_audioeq_transform_ip (GstBaseTransform * base, GstBuffer * buf);
+#else
+static GstFlowReturn gst_audioeq_transform (GstBaseTransform * base, GstBuffer * inbuf, GstBuffer * outbuf);
+#endif
+static gboolean gst_audioeq_set_caps (GstBaseTransform * base, GstCaps * incaps, GstCaps * outcaps);
+
+static GstStateChangeReturn
+gst_audioeq_change_state (GstElement * element, GstStateChange transition)
+{
+  GST_DEBUG ("gst_audioeq_change_state");
+       GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
+       Gstaudioeq *audioeq = GST_AUDIOEQ (element);
+
+       switch (transition) {
+       case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+               audioeq->need_update_filter = TRUE;
+               break;
+       default:
+               break;
+       }
+
+       ret = GST_ELEMENT_CLASS (gst_audioeq_parent_class)->change_state (element, transition);
+
+       if (ret == GST_STATE_CHANGE_FAILURE)
+               return ret;
+
+       switch (transition) {
+       case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+               break;
+       default:
+               break;
+       }
+
+       return ret;
+}
+
+static void
+gst_audioeq_base_init (gpointer gclass)
+{
+
+  GST_DEBUG ("gst_audioeq_base_init");
+}
+
+static void
+gst_audioeq_class_init (GstaudioeqClass * klass)
+{
+       GST_DEBUG ("gst_audioeq_class_init");
+       GObjectClass *gobject_class;
+       GstElementClass *gstelement_class;
+       GstBaseTransformClass *basetransform_class;
+
+       gobject_class = G_OBJECT_CLASS (klass);
+       gstelement_class = GST_ELEMENT_CLASS (klass);
+       basetransform_class = GST_BASE_TRANSFORM_CLASS(klass);
+
+       gobject_class->set_property = GST_DEBUG_FUNCPTR(gst_audioeq_set_property);
+       gobject_class->get_property = GST_DEBUG_FUNCPTR(gst_audioeq_get_property);
+
+       gst_element_class_add_pad_template(gstelement_class,
+               gst_static_pad_template_get (&srctemplate));
+       gst_element_class_add_pad_template(gstelement_class,
+               gst_static_pad_template_get (&sinktemplate));
+
+       gst_element_class_set_static_metadata(gstelement_class,
+               "Audio Equalizer",
+               "Filter/Effect/Audio",
+               "Set equalisation effect on audio/raw streams",
+               "Samsung Electronics <www.samsung.com>");
+       gstelement_class->change_state = GST_DEBUG_FUNCPTR(gst_audioeq_change_state);
+
+       g_object_class_install_property(gobject_class, PROP_FILTER_ACTION,
+               g_param_spec_uint("filter-action", "filter action", "(0)none (1)preset (2)advanced setting",
+               0, 2, DEFAULT_FILTER_ACTION, G_PARAM_READWRITE));
+
+       g_object_class_install_property (gobject_class, PROP_CUSTOM_EQ,
+               g_param_spec_pointer("custom-eq", "custom eq",
+               "pointer for 9 bands of EQ array", G_PARAM_READWRITE));
+
+       g_object_class_install_property(gobject_class, PROP_CUSTOM_EQ_NUM,
+               g_param_spec_uint("custom-eq-num", "custom eq num", "number of custom EQ bands",
+               0, 9, DEFAULT_CUSTOM_EQ_NUM, G_PARAM_READABLE));
+
+       g_object_class_install_property(gobject_class, PROP_CUSTOM_EQ_FREQ,
+               g_param_spec_pointer("custom-eq-freq", "custom eq freq", "pointer for EQ bands central frequency(Hz) array",
+               G_PARAM_READABLE));
+
+       g_object_class_install_property(gobject_class, PROP_CUSTOM_EQ_WIDTH,
+               g_param_spec_pointer("custom-eq-width", "custom eq width", "pointer for EQ bands width(Hz) array",
+               G_PARAM_READABLE));
+
+       gobject_class->finalize = GST_DEBUG_FUNCPTR(gst_iir_equalizer_finalize);
+
+/* It is possible to reduce memcpy by setting output same as input of AudioEq_InOutConfig */
+#ifdef AUDIOEQ_REDUCE_MEMCPY
+       basetransform_class->transform_ip = GST_DEBUG_FUNCPTR(gst_audioeq_transform_ip);
+#endif
+       basetransform_class->set_caps = GST_DEBUG_FUNCPTR(gst_audioeq_set_caps);
+}
+
+static void
+gst_audioeq_init (Gstaudioeq * audioeq)
+{
+  GST_DEBUG ("gst_audioeq_init");
+       audioeq->samplerate = DEFAULT_SAMPLE_RATE;
+       audioeq->channels = DEAFULT_CHANNELS;
+
+       audioeq->filter_action = DEFAULT_FILTER_ACTION;
+       memset(audioeq->custom_eq, 0x00, sizeof(gint) * CUSTOM_EQ_BAND_MAX);
+       audioeq->need_update_filter = TRUE;
+       audioeq->equ.bands_lock = g_mutex_new ();
+       audioeq->equ.need_new_coefficients = TRUE;
+       gst_iir_equalizer_compute_frequencies (audioeq, DEFAULT_CUSTOM_EQ_NUM);
+}
+/* equalizer implementation */
+
+static void
+gst_iir_equalizer_finalize (GObject * object)
+{
+  GST_DEBUG ("gst_iir_equalizer_finalize");
+  Gstaudioeq *audioeq = GST_AUDIOEQ(object);
+  GstIirEqualizer *equ = &audioeq->equ;
+  gint i;
+
+  for (i = 0; i < equ->freq_band_count; i++) {
+    if (equ->bands[i])
+      gst_object_unparent (GST_OBJECT (equ->bands[i]));
+    equ->bands[i] = NULL;
+  }
+  equ->freq_band_count = 0;
+
+  g_free (equ->bands);
+  g_free (equ->history);
+
+  g_mutex_free (equ->bands_lock);
+
+  G_OBJECT_CLASS (gst_audioeq_parent_class)->finalize (object);
+}
+
+#define BANDS_LOCK(equ) g_mutex_lock(equ->bands_lock)
+#define BANDS_UNLOCK(equ) g_mutex_unlock(equ->bands_lock)
+
+/* child object */
+
+enum
+{
+  PROP_GAIN = 1,
+  PROP_FREQ,
+  PROP_BANDWIDTH,
+  PROP_TYPE
+};
+
+typedef enum
+{
+  BAND_TYPE_PEAK = 0,
+  BAND_TYPE_LOW_SHELF,
+  BAND_TYPE_HIGH_SHELF
+} GstIirEqualizerBandType;
+
+#define GST_TYPE_IIR_EQUALIZER_BAND_TYPE (gst_iir_equalizer_band_type_get_type ())
+static GType
+gst_iir_equalizer_band_type_get_type (void)
+{
+  GST_DEBUG ("gst_iir_equalizer_band_type_get_type");
+  static GType gtype = 0;
+
+  if (gtype == 0) {
+    static const GEnumValue values[] = {
+      {BAND_TYPE_PEAK, "Peak filter (default for inner bands)", "peak"},
+      {BAND_TYPE_LOW_SHELF, "Low shelf filter (default for first band)",
+          "low-shelf"},
+      {BAND_TYPE_HIGH_SHELF, "High shelf filter (default for last band)",
+          "high-shelf"},
+      {0, NULL, NULL}
+    };
+
+    gtype = g_enum_register_static ("GstIirEqualizerBandType", values);
+  }
+  return gtype;
+}
+
+
+typedef struct _GstIirEqualizerBandClass GstIirEqualizerBandClass;
+
+#define GST_TYPE_IIR_EQUALIZER_BAND \
+  (gst_iir_equalizer_band_get_type())
+#define GST_IIR_EQUALIZER_BAND(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_IIR_EQUALIZER_BAND,GstIirEqualizerBand))
+#define GST_IIR_EQUALIZER_BAND_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_IIR_EQUALIZER_BAND,GstIirEqualizerBandClass))
+#define GST_IS_IIR_EQUALIZER_BAND(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_IIR_EQUALIZER_BAND))
+#define GST_IS_IIR_EQUALIZER_BAND_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_IIR_EQUALIZER_BAND))
+
+struct _GstIirEqualizerBand
+{
+  GstObject object;
+
+  /*< private > */
+  /* center frequency and gain */
+  gdouble freq;
+  gdouble gain;
+  gdouble width;
+  GstIirEqualizerBandType type;
+
+  /* second order iir filter */
+  gdouble b1, b2;               /* IIR coefficients for outputs */
+  gdouble a0, a1, a2;           /* IIR coefficients for inputs */
+};
+
+struct _GstIirEqualizerBandClass
+{
+  GstObjectClass parent_class;
+};
+
+static GType gst_iir_equalizer_band_get_type (void);
+
+static void
+gst_iir_equalizer_band_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  GST_DEBUG ("gst_iir_equalizer_band_set_property");
+  GstIirEqualizerBand *band = GST_IIR_EQUALIZER_BAND (object);
+  Gstaudioeq *audioeq = GST_AUDIOEQ (gst_object_get_parent (GST_OBJECT (band)));
+  GstIirEqualizer *equ = &audioeq->equ;
+
+  switch (prop_id) {
+    case PROP_GAIN:{
+      gdouble gain;
+
+      gain = g_value_get_double (value);
+      GST_DEBUG_OBJECT (band, "gain = %lf -> %lf", band->gain, gain);
+      if (gain != band->gain) {
+        BANDS_LOCK (equ);
+        equ->need_new_coefficients = TRUE;
+        band->gain = gain;
+        BANDS_UNLOCK (equ);
+        GST_DEBUG_OBJECT (band, "changed gain = %lf ", band->gain);
+      }
+      break;
+    }
+    case PROP_FREQ:{
+      gdouble freq;
+
+      freq = g_value_get_double (value);
+      GST_DEBUG_OBJECT (band, "freq = %lf -> %lf", band->freq, freq);
+      if (freq != band->freq) {
+        BANDS_LOCK (equ);
+        equ->need_new_coefficients = TRUE;
+        band->freq = freq;
+        BANDS_UNLOCK (equ);
+        GST_DEBUG_OBJECT (band, "changed freq = %lf ", band->freq);
+      }
+      break;
+    }
+    case PROP_BANDWIDTH:{
+      gdouble width;
+
+      width = g_value_get_double (value);
+      GST_DEBUG_OBJECT (band, "width = %lf -> %lf", band->width, width);
+      if (width != band->width) {
+        BANDS_LOCK (equ);
+        equ->need_new_coefficients = TRUE;
+        band->width = width;
+        BANDS_UNLOCK (equ);
+        GST_DEBUG_OBJECT (band, "changed width = %lf ", band->width);
+      }
+      break;
+    }
+    case PROP_TYPE:{
+      GstIirEqualizerBandType type;
+
+      type = g_value_get_enum (value);
+      GST_DEBUG_OBJECT (band, "type = %d -> %d", band->type, type);
+      if (type != band->type) {
+        BANDS_LOCK (equ);
+        equ->need_new_coefficients = TRUE;
+        band->type = type;
+        BANDS_UNLOCK (equ);
+        GST_DEBUG_OBJECT (band, "changed type = %d ", band->type);
+      }
+      break;
+    }
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+
+  gst_object_unref (audioeq);
+}
+
+static void
+gst_iir_equalizer_band_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec)
+{
+  GST_DEBUG ("gst_iir_equalizer_band_get_property");
+  GstIirEqualizerBand *band = GST_IIR_EQUALIZER_BAND (object);
+
+  switch (prop_id) {
+    case PROP_GAIN:
+      g_value_set_double (value, band->gain);
+      break;
+    case PROP_FREQ:
+      g_value_set_double (value, band->freq);
+      break;
+    case PROP_BANDWIDTH:
+      g_value_set_double (value, band->width);
+      break;
+    case PROP_TYPE:
+      g_value_set_enum (value, band->type);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_iir_equalizer_band_class_init (GstIirEqualizerBandClass * klass)
+{
+  GST_DEBUG ("gst_iir_equalizer_band_class_init");
+  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
+
+  gobject_class->set_property = gst_iir_equalizer_band_set_property;
+  gobject_class->get_property = gst_iir_equalizer_band_get_property;
+
+  g_object_class_install_property (gobject_class, PROP_GAIN,
+      g_param_spec_double ("gain", "gain",
+          "gain for the frequency band ranging from -12.0 dB to +12.0 dB",
+          -12.0, 12.0, 0.0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
+
+  g_object_class_install_property (gobject_class, PROP_FREQ,
+      g_param_spec_double ("freq", "freq",
+          "center frequency of the band",
+          0.0, 100000.0, 0.0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
+
+  g_object_class_install_property (gobject_class, PROP_BANDWIDTH,
+      g_param_spec_double ("bandwidth", "bandwidth",
+          "difference between bandedges in Hz",
+          0.0, 100000.0, 1.0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
+
+  g_object_class_install_property (gobject_class, PROP_TYPE,
+      g_param_spec_enum ("type", "Type",
+          "Filter type", GST_TYPE_IIR_EQUALIZER_BAND_TYPE,
+          BAND_TYPE_PEAK,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE));
+}
+
+static void
+gst_iir_equalizer_band_init (GstIirEqualizerBand * band,
+    GstIirEqualizerBandClass * klass)
+{
+  GST_DEBUG ("gst_iir_equalizer_band_init");
+  band->freq = 0.0;
+  band->gain = 0.0;
+  band->width = 1.0;
+  band->type = BAND_TYPE_PEAK;
+}
+
+static GType
+gst_iir_equalizer_band_get_type (void)
+{
+  GST_DEBUG ("gst_iir_equalizer_band_get_type");
+  static GType type = 0;
+
+  if (G_UNLIKELY (!type)) {
+    const GTypeInfo type_info = {
+      sizeof (GstIirEqualizerBandClass),
+      NULL,
+      NULL,
+      (GClassInitFunc) gst_iir_equalizer_band_class_init,
+      NULL,
+      NULL,
+      sizeof (GstIirEqualizerBand),
+      0,
+      (GInstanceInitFunc) gst_iir_equalizer_band_init,
+    };
+    type =
+        g_type_register_static (GST_TYPE_OBJECT, "GstIirEqualizerBand",
+        &type_info, 0);
+  }
+  return (type);
+}
+
+
+/* child proxy iface */
+static GObject *
+gst_iir_equalizer_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
+    guint index)
+{
+  GST_DEBUG ("gst_iir_equalizer_child_proxy_get_child_by_index");
+  Gstaudioeq *audioeq = GST_AUDIOEQ(child_proxy);
+  GstIirEqualizer *equ = &audioeq->equ;
+  GObject *ret;
+
+  BANDS_LOCK (equ);
+  if (G_UNLIKELY (index >= equ->freq_band_count)) {
+    BANDS_UNLOCK (equ);
+    g_return_val_if_fail (index < equ->freq_band_count, NULL);
+  }
+
+  ret = gst_object_ref (equ->bands[index]);
+  BANDS_UNLOCK (equ);
+
+  GST_LOG_OBJECT (equ, "return child[%d] %" GST_PTR_FORMAT, index, ret);
+  return ret;
+}
+
+static guint
+gst_iir_equalizer_child_proxy_get_children_count (GstChildProxy * child_proxy)
+{
+  GST_DEBUG ("gst_iir_equalizer_child_proxy_get_children_count");
+  Gstaudioeq *audioeq = GST_AUDIOEQ(child_proxy);
+  GstIirEqualizer *equ = &audioeq->equ;
+
+  GST_LOG ("we have %d children", equ->freq_band_count);
+  return equ->freq_band_count;
+}
+
+static void
+gst_iir_equalizer_child_proxy_interface_init (gpointer g_iface,
+    gpointer iface_data)
+{
+  GstChildProxyInterface *iface = g_iface;
+
+  GST_DEBUG ("initializing iface");
+
+  iface->get_child_by_index = gst_iir_equalizer_child_proxy_get_child_by_index;
+  iface->get_children_count = gst_iir_equalizer_child_proxy_get_children_count;
+}
+static void
+gst_iir_equalizer_class_init (GstIirEqualizerClass * klass)
+{
+  GST_DEBUG ("gst_iir_equalizer_class_init");
+}
+
+static void
+gst_iir_equalizer_init (GstIirEqualizer * eq, GstIirEqualizerClass * g_class)
+{
+  GST_DEBUG ("gst_iir_equalizer_init");
+  eq->bands_lock = g_mutex_new ();
+  eq->need_new_coefficients = TRUE;
+}
+
+GType
+gst_iir_equalizer_get_type (void)
+{
+  GST_DEBUG ("gst_iir_equalizer_get_type");
+  static GType type = 0;
+
+  if (G_UNLIKELY (!type)) {
+    const GTypeInfo type_info = {
+      sizeof (GstIirEqualizerClass),
+      NULL,
+      NULL,
+      (GClassInitFunc) gst_iir_equalizer_class_init,
+      NULL,
+      NULL,
+      sizeof (GstIirEqualizer),
+      0,
+      (GInstanceInitFunc) gst_iir_equalizer_init,
+    };
+    type =
+        g_type_register_static (GST_TYPE_OBJECT, "GstIirEqualizer",
+        &type_info, 0);
+  }
+  return (type);
+}
+/* Filter taken from
+ *
+ * The Equivalence of Various Methods of Computing
+ * Biquad Coefficients for Audio Parametric Equalizers
+ *
+ * by Robert Bristow-Johnson
+ *
+ * http://www.aes.org/e-lib/browse.cfm?elib=6326
+ * http://www.musicdsp.org/files/EQ-Coefficients.pdf
+ * http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
+ *
+ * The bandwidth method that we use here is the preferred
+ * one from this article transformed from octaves to frequency
+ * in Hz.
+ */
+static inline gdouble
+arg_to_scale (gdouble arg)
+{
+  GST_DEBUG ("arg_to_scale");
+  return (pow (10.0, arg / 40.0));
+}
+
+static gdouble
+calculate_omega (gdouble freq, gint rate)
+{
+  GST_DEBUG ("calculate_omega");
+  gdouble omega;
+
+  if (freq / rate >= 0.5)
+    omega = G_PI;
+  else if (freq <= 0.0)
+    omega = 0.0;
+  else
+    omega = 2.0 * G_PI * (freq / rate);
+
+  return omega;
+}
+
+static gdouble
+calculate_bw (GstIirEqualizerBand * band, gint rate)
+{
+  GST_DEBUG ("calculate_bw");
+  gdouble bw = 0.0;
+
+  if (band->width / rate >= 0.5) {
+    /* If bandwidth == 0.5 the calculation below fails as tan(G_PI/2)
+     * is undefined. So set the bandwidth to a slightly smaller value.
+     */
+    bw = G_PI - 0.00000001;
+  } else if (band->width <= 0.0) {
+    /* If bandwidth == 0 this band won't change anything so set
+     * the coefficients accordingly. The coefficient calculation
+     * below would create coefficients that for some reason amplify
+     * the band.
+     */
+    band->a0 = 1.0;
+    band->a1 = 0.0;
+    band->a2 = 0.0;
+    band->b1 = 0.0;
+    band->b2 = 0.0;
+  } else {
+    bw = 2.0 * G_PI * (band->width / rate);
+  }
+  return bw;
+}
+
+static void
+setup_peak_filter (Gstaudioeq* audioeq, GstIirEqualizerBand * band)
+{
+  GST_DEBUG ("setup_peak_filter");
+  //g_return_if_fail (GST_AUDIO_FILTER (equ)->format.rate);
+
+  {
+    gdouble gain, omega, bw;
+    gdouble alpha, alpha1, alpha2, b0;
+
+    gain = arg_to_scale (band->gain);
+    omega = calculate_omega (band->freq, audioeq->samplerate);
+    bw = calculate_bw (band, audioeq->samplerate);
+    if (bw == 0.0)
+      goto out;
+
+    alpha = tan (bw / 2.0);
+
+    alpha1 = alpha * gain;
+    alpha2 = alpha / gain;
+
+    b0 = (1.0 + alpha2);
+
+    band->a0 = (1.0 + alpha1) / b0;
+    band->a1 = (-2.0 * cos (omega)) / b0;
+    band->a2 = (1.0 - alpha1) / b0;
+    band->b1 = (2.0 * cos (omega)) / b0;
+    band->b2 = -(1.0 - alpha2) / b0;
+
+  out:
+    GST_INFO
+        ("gain = %5.1f, width= %7.2f, freq = %7.2f, a0 = %7.5g, a1 = %7.5g, a2=%7.5g b1 = %7.5g, b2 = %7.5g",
+        band->gain, band->width, band->freq, band->a0, band->a1, band->a2,
+        band->b1, band->b2);
+  }
+}
+
+static void
+setup_low_shelf_filter (Gstaudioeq* audioeq, GstIirEqualizerBand * band)
+{
+  GST_DEBUG ("setup_low_shelf_filter");
+  //g_return_if_fail (GST_AUDIO_FILTER (equ)->format.rate);
+
+  {
+    gdouble gain, omega, bw;
+    gdouble alpha, delta, b0;
+    gdouble egp, egm;
+
+    gain = arg_to_scale (band->gain);
+    omega = calculate_omega (band->freq, audioeq->samplerate);
+    bw = calculate_bw (band, audioeq->samplerate);
+    if (bw == 0.0)
+      goto out;
+
+    egm = gain - 1.0;
+    egp = gain + 1.0;
+    alpha = tan (bw / 2.0);
+
+    delta = 2.0 * sqrt (gain) * alpha;
+    b0 = egp + egm * cos (omega) + delta;
+
+    band->a0 = ((egp - egm * cos (omega) + delta) * gain) / b0;
+    band->a1 = ((egm - egp * cos (omega)) * 2.0 * gain) / b0;
+    band->a2 = ((egp - egm * cos (omega) - delta) * gain) / b0;
+    band->b1 = ((egm + egp * cos (omega)) * 2.0) / b0;
+    band->b2 = -((egp + egm * cos (omega) - delta)) / b0;
+
+
+  out:
+    GST_INFO
+        ("gain = %5.1f, width= %7.2f, freq = %7.2f, a0 = %7.5g, a1 = %7.5g, a2=%7.5g b1 = %7.5g, b2 = %7.5g",
+        band->gain, band->width, band->freq, band->a0, band->a1, band->a2,
+        band->b1, band->b2);
+  }
+}
+
+static void
+setup_high_shelf_filter (Gstaudioeq* audioeq, GstIirEqualizerBand * band)
+{
+  GST_DEBUG ("setup_high_shelf_filter");
+  {
+    gdouble gain, omega, bw;
+    gdouble alpha, delta, b0;
+    gdouble egp, egm;
+
+    gain = arg_to_scale (band->gain);
+    omega = calculate_omega (band->freq, audioeq->samplerate);
+    bw = calculate_bw (band, audioeq->samplerate);
+    if (bw == 0.0)
+      goto out;
+
+    egm = gain - 1.0;
+    egp = gain + 1.0;
+    alpha = tan (bw / 2.0);
+
+    delta = 2.0 * sqrt (gain) * alpha;
+    b0 = egp - egm * cos (omega) + delta;
+
+    band->a0 = ((egp + egm * cos (omega) + delta) * gain) / b0;
+    band->a1 = ((egm + egp * cos (omega)) * -2.0 * gain) / b0;
+    band->a2 = ((egp + egm * cos (omega) - delta) * gain) / b0;
+    band->b1 = ((egm - egp * cos (omega)) * -2.0) / b0;
+    band->b2 = -((egp - egm * cos (omega) - delta)) / b0;
+
+
+  out:
+    GST_INFO
+        ("gain = %5.1f, width= %7.2f, freq = %7.2f, a0 = %7.5g, a1 = %7.5g, a2=%7.5g b1 = %7.5g, b2 = %7.5g",
+        band->gain, band->width, band->freq, band->a0, band->a1, band->a2,
+        band->b1, band->b2);
+  }
+}
+
+/* Must be called with bands_lock and transform lock! */
+static void
+set_passthrough (Gstaudioeq* audioeq)
+{
+  GST_DEBUG ("set_passthrough");
+  GstIirEqualizer* equ=&audioeq->equ;
+  gint i;
+  gboolean passthrough = TRUE;
+
+  for (i = 0; i < equ->freq_band_count; i++) {
+    passthrough = passthrough && (equ->bands[i]->gain == 0.0);
+  }
+
+  gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (audioeq), passthrough);
+  GST_DEBUG ("Passthrough mode: %d\n", passthrough);
+}
+
+/* Must be called with bands_lock and transform lock! */
+static void
+update_coefficients (Gstaudioeq* audioeq)
+{
+  GST_DEBUG ("update_coefficients");
+  GstIirEqualizer* equ=&audioeq->equ;
+  gint i, n = equ->freq_band_count;
+
+  for (i = 0; i < n; i++) {
+    if (equ->bands[i]->type == BAND_TYPE_PEAK)
+      setup_peak_filter (audioeq, equ->bands[i]);
+    else if (equ->bands[i]->type == BAND_TYPE_LOW_SHELF)
+      setup_low_shelf_filter (audioeq, equ->bands[i]);
+    else
+      setup_high_shelf_filter (audioeq, equ->bands[i]);
+  }
+
+  equ->need_new_coefficients = FALSE;
+}
+
+/* Must be called with transform lock! */
+static void
+alloc_history (GstIirEqualizer * equ)
+{
+  GST_DEBUG ("alloc_history");
+  /* free + alloc = no memcpy */
+  g_free (equ->history);
+  equ->history =
+      g_malloc0 (equ->history_size *  GST_AUDIO_FILTER_CHANNELS(&equ->audiofilter) *
+      equ->freq_band_count);
+}
+void
+gst_audioeq_band_set_property(Gstaudioeq * audioeq)
+{
+  GST_DEBUG ("gst_audioeq_band_set_property");
+  GstIirEqualizer *equ = &audioeq->equ;
+  gshort i ;
+  for ( i = 0; i < DEFAULT_CUSTOM_EQ_NUM; i++){
+     GST_DEBUG ("gain = %lf -> %d", equ->bands[i]->gain, audioeq->custom_eq[i] );
+     if (audioeq->custom_eq[i] != equ->bands[i]->gain) {
+        equ->bands[i]->gain = audioeq->custom_eq[i];
+        GST_DEBUG("changed gain = %lf ", equ->bands[i]->gain);
+        g_object_notify (G_OBJECT (equ->bands[i]), "gain");
+     }
+  }
+}
+
+void
+gst_iir_equalizer_compute_frequencies (Gstaudioeq * audioeq, guint new_count)
+{
+  GST_DEBUG ("gst_iir_equalizer_compute_frequencies");
+
+  GstIirEqualizer *equ = &audioeq->equ;
+  guint old_count, i;
+  gdouble freq0, freq1, step;
+  gchar name[20];
+  gchar *old_name = NULL;
+  GST_DEBUG ("gst_iir_equalizer_compute_frequencies before calling equalizer object");
+  if (equ->freq_band_count == new_count)
+    return;
+
+  GST_DEBUG ("gst_iir_equalizer_compute_frequencies equalizer object");
+
+  BANDS_LOCK (equ);
+  GST_DEBUG ("gst_iir_equalizer_compute_frequencies 1");
+  if (G_UNLIKELY (equ->freq_band_count == new_count)) {
+    BANDS_UNLOCK (equ);
+    return;
+  }
+  GST_DEBUG ("gst_iir_equalizer_compute_frequencies 2");
+  old_count = equ->freq_band_count;
+  equ->freq_band_count = new_count;
+  GST_DEBUG ("bands %u -> %u", old_count, new_count);
+
+  if (old_count < new_count) {
+    /* add new bands */
+    equ->bands = g_realloc (equ->bands, sizeof (GstObject *) * new_count);
+    for (i = old_count; i < new_count; i++) {
+      equ->bands[i] = g_object_new (GST_TYPE_IIR_EQUALIZER_BAND, NULL);
+      /* otherwise they get names like 'iirequalizerband5' */
+      snprintf (name, 20, "band%u", i);
+      gst_object_set_name (GST_OBJECT (equ->bands[i]), name);
+      GST_DEBUG ("adding band[%d]=%p", i, equ->bands[i]);
+
+      gst_object_set_parent (GST_OBJECT (equ->bands[i]), GST_OBJECT (audioeq));
+      gst_child_proxy_child_added (GST_CHILD_PROXY (audioeq),
+          G_OBJECT (equ->bands[i]), name);
+    }
+  } else {
+    /* free unused bands */
+    for (i = new_count; i < old_count; i++) {
+      GST_DEBUG ("removing band[%d]=%p", i, equ->bands[i]);
+      old_name = gst_object_get_name(GST_OBJECT(equ->bands[i]));
+      gst_child_proxy_child_removed (GST_CHILD_PROXY (audioeq),
+              G_OBJECT (equ->bands[i]), old_name);
+      g_free(old_name);
+      gst_object_unparent (GST_OBJECT (equ->bands[i]));
+      equ->bands[i] = NULL;
+    }
+  }
+
+  alloc_history (equ);
+
+  /* set center frequencies and name band objects
+   * FIXME: arg! we can't change the name of parented objects :(
+   *   application should read band->freq to get the name
+   */
+
+  step = pow (HIGHEST_FREQ / LOWEST_FREQ, 1.0 / new_count);
+  freq0 = LOWEST_FREQ;
+  for (i = 0; i < new_count; i++) {
+    freq1 = freq0 * step;
+
+    if (i == 0)
+      equ->bands[i]->type = BAND_TYPE_LOW_SHELF;
+    else if (i == new_count - 1)
+      equ->bands[i]->type = BAND_TYPE_HIGH_SHELF;
+    else
+      equ->bands[i]->type = BAND_TYPE_PEAK;
+
+    equ->bands[i]->freq = freq0 + ((freq1 - freq0) / 2.0);
+    equ->bands[i]->width = freq1 - freq0;
+    GST_DEBUG ("band[%2d] = '%lf'", i, equ->bands[i]->freq);
+
+    g_object_notify (G_OBJECT (equ->bands[i]), "bandwidth");
+    g_object_notify (G_OBJECT (equ->bands[i]), "freq");
+    g_object_notify (G_OBJECT (equ->bands[i]), "type");
+
+    freq0 = freq1;
+  }
+
+  equ->need_new_coefficients = TRUE;
+
+  BANDS_UNLOCK (equ);
+}
+/* start of code that is type specific */
+
+#define CREATE_OPTIMIZED_FUNCTIONS_INT(TYPE,BIG_TYPE,MIN_VAL,MAX_VAL)   \
+typedef struct {                                                        \
+  BIG_TYPE x1, x2;          /* history of input values for a filter */  \
+  BIG_TYPE y1, y2;          /* history of output values for a filter */ \
+} SecondOrderHistory ## TYPE;                                           \
+                                                                        \
+static inline BIG_TYPE                                                  \
+one_step_ ## TYPE (GstIirEqualizerBand *filter,                         \
+    SecondOrderHistory ## TYPE *history, BIG_TYPE input)                \
+{                                                                       \
+  /* calculate output */                                                \
+  BIG_TYPE output = filter->a0 * input +                                \
+      filter->a1 * history->x1 + filter->a2 * history->x2 +             \
+      filter->b1 * history->y1 + filter->b2 * history->y2;              \
+  /* update history */                                                  \
+  history->y2 = history->y1;                                            \
+  history->y1 = output;                                                 \
+  history->x2 = history->x1;                                            \
+  history->x1 = input;                                                  \
+                                                                        \
+  return output;                                                        \
+}                                                                       \
+                                                                        \
+static const guint                                                      \
+history_size_ ## TYPE = sizeof (SecondOrderHistory ## TYPE);            \
+                                                                        \
+static void                                                             \
+gst_iir_equ_process_ ## TYPE (GstIirEqualizer *equ, guint8 *data,       \
+guint size, guint channels)                                             \
+{                                                                       \
+  guint frames = size / channels / sizeof (TYPE);                       \
+  guint i, c, f, nf = equ->freq_band_count;                             \
+  BIG_TYPE cur;                                                         \
+  GstIirEqualizerBand **filters = equ->bands;                           \
+                                                                        \
+  for (i = 0; i < frames; i++) {                                        \
+    SecondOrderHistory ## TYPE *history = equ->history;                 \
+    for (c = 0; c < channels; c++) {                                    \
+      cur = *((TYPE *) data);                                           \
+      for (f = 0; f < nf; f++) {                                        \
+        cur = one_step_ ## TYPE (filters[f], history, cur);             \
+        history++;                                                      \
+      }                                                                 \
+      cur = CLAMP (cur, MIN_VAL, MAX_VAL);                              \
+      *((TYPE *) data) = (TYPE) floor (cur);                            \
+      data += sizeof (TYPE);                                            \
+    }                                                                   \
+  }                                                                     \
+}
+
+#define CREATE_OPTIMIZED_FUNCTIONS(TYPE)                                \
+typedef struct {                                                        \
+  TYPE x1, x2;          /* history of input values for a filter */  \
+  TYPE y1, y2;          /* history of output values for a filter */ \
+} SecondOrderHistory ## TYPE;                                           \
+                                                                        \
+static inline TYPE                                                      \
+one_step_ ## TYPE (GstIirEqualizerBand *filter,                         \
+    SecondOrderHistory ## TYPE *history, TYPE input)                    \
+{                                                                       \
+  /* calculate output */                                                \
+  TYPE output = filter->a0 * input + filter->a1 * history->x1 +         \
+      filter->a2 * history->x2 + filter->b1 * history->y1 +             \
+      filter->b2 * history->y2;                                         \
+  /* update history */                                                  \
+  history->y2 = history->y1;                                            \
+  history->y1 = output;                                                 \
+  history->x2 = history->x1;                                            \
+  history->x1 = input;                                                  \
+                                                                        \
+  return output;                                                        \
+}                                                                       \
+                                                                        \
+static const guint                                                      \
+history_size_ ## TYPE = sizeof (SecondOrderHistory ## TYPE);            \
+                                                                        \
+static void                                                             \
+gst_iir_equ_process_ ## TYPE (GstIirEqualizer *equ, guint8 *data,       \
+guint size, guint channels)                                             \
+{                                                                       \
+  guint frames = size / channels / sizeof (TYPE);                       \
+  guint i, c, f, nf = equ->freq_band_count;                             \
+  TYPE cur;                                                             \
+  GstIirEqualizerBand **filters = equ->bands;                           \
+                                                                        \
+  for (i = 0; i < frames; i++) {                                        \
+    SecondOrderHistory ## TYPE *history = equ->history;                 \
+    for (c = 0; c < channels; c++) {                                    \
+      cur = *((TYPE *) data);                                           \
+      for (f = 0; f < nf; f++) {                                        \
+        cur = one_step_ ## TYPE (filters[f], history, cur);             \
+        history++;                                                      \
+      }                                                                 \
+      *((TYPE *) data) = (TYPE) cur;                                    \
+      data += sizeof (TYPE);                                            \
+    }                                                                   \
+  }                                                                     \
+}
+
+CREATE_OPTIMIZED_FUNCTIONS_INT (gint16, gfloat, -32768.0, 32767.0);
+CREATE_OPTIMIZED_FUNCTIONS (gfloat);
+CREATE_OPTIMIZED_FUNCTIONS (gdouble);
+
+#ifdef AUDIOEQ_REDUCE_MEMCPY
+static GstFlowReturn
+gst_audioeq_transform_ip (GstBaseTransform * base, GstBuffer * buf)
+{
+  GST_DEBUG ("gst_audioeq_transform_ip");
+  Gstaudioeq *audioeq = GST_AUDIOEQ(base);
+  GstIirEqualizer *equ = &audioeq->equ;
+  GstMapInfo buf_info = GST_MAP_INFO_INIT;
+
+  equ->history_size = history_size_gint16;
+  equ->process = gst_iir_equ_process_gint16;
+   g_free (equ->history);
+  equ->history = g_malloc0 (equ->history_size *  audioeq->channels * equ->freq_band_count);
+  GstClockTime timestamp;
+
+  if (G_UNLIKELY (audioeq->channels < 1 || equ->process == NULL)) {
+    GST_DEBUG ("gst_audioeq_transform_ip return GST_FLOW_NOT_NEGOTIATED;");
+    if (G_UNLIKELY (equ->process == NULL))
+    GST_DEBUG ("gst_audioeq_transform_ip equ->process ");
+    if (G_UNLIKELY (audioeq->channels < 1))
+    GST_DEBUG ("gst_audioeq_transform_ip audioeq->channels");
+    return GST_FLOW_NOT_NEGOTIATED;
+  }
+      GST_DEBUG ("gst_audioeq_transform_ip  BANDS_LOCK (equ);");
+  BANDS_LOCK (equ);
+  if (equ->need_new_coefficients) {
+    GST_DEBUG ("gst_audioeq_transform_ip  update_coefficients");
+    update_coefficients (audioeq);
+    set_passthrough (audioeq);
+  }
+  BANDS_UNLOCK (equ);
+
+  if (gst_base_transform_is_passthrough (base)) {
+    GST_DEBUG ("gst_audioeq_transform_ip gst_base_transform_is_passthrough return GST_FLOW_OK;");
+    return GST_FLOW_OK;
+  }
+  timestamp = GST_BUFFER_TIMESTAMP (buf);
+  timestamp =
+      gst_segment_to_stream_time (&base->segment, GST_FORMAT_TIME, timestamp);
+
+  if (GST_CLOCK_TIME_IS_VALID (timestamp))
+    gst_object_sync_values (GST_OBJECT (audioeq), timestamp);
+  GST_DEBUG ("  equ->process ++");
+  gst_buffer_map(buf, &buf_info, GST_MAP_READWRITE);
+  equ->process (equ, buf_info.data, buf_info.size,
+      audioeq->channels);
+  gst_buffer_unmap(buf, &buf_info);
+  GST_DEBUG ("  equ->process --");
+  GST_DEBUG ("gst_audioeq_transform_ip return GST_FLOW_OK;");
+  return GST_FLOW_OK;
+}
+#endif
+
+static gboolean
+gst_audioeq_set_caps (GstBaseTransform * base, GstCaps * incaps,
+       GstCaps * outcaps)
+{
+  GST_DEBUG ("gst_audioeq_set_caps");
+       Gstaudioeq *audioeq = GST_AUDIOEQ(base);
+       GstStructure *ins;
+       GstPad *pad;
+       gint samplerate;
+       gint channels;
+       gshort old_samplerate;
+       gshort old_channels;
+
+       pad = gst_element_get_static_pad(GST_ELEMENT(audioeq), "src");
+
+       /* forward-negotiate */
+       if(!gst_pad_set_caps(pad, incaps)) {
+               gst_object_unref(pad);
+               return FALSE;
+       }
+
+       /* negotiation succeeded, so now configure ourselves */
+       ins = gst_caps_get_structure(incaps, 0);
+
+       /* get samplerate from caps & convert */
+       old_samplerate = audioeq->samplerate;
+       old_channels = audioeq->channels;
+       gst_structure_get_int(ins, "rate", &samplerate);
+       switch (samplerate) {
+       case 48000:
+               audioeq->samplerate = SAMPLERATE_48000Hz;
+               break;
+       case 44100:
+               audioeq->samplerate = SAMPLERATE_44100Hz;
+               break;
+       case 32000:
+               audioeq->samplerate = SAMPLERATE_32000Hz;
+               break;
+       case 24000:
+               audioeq->samplerate = SAMPLERATE_24000Hz;
+               break;
+       case 22050:
+               audioeq->samplerate = SAMPLERATE_22050Hz;
+               break;
+       case 16000:
+               audioeq->samplerate = SAMPLERATE_16000Hz;
+               break;
+       case 12000:
+               audioeq->samplerate = SAMPLERATE_12000Hz;
+               break;
+       case 11025:
+               audioeq->samplerate = SAMPLERATE_11025Hz;
+               break;
+       case 8000:
+               audioeq->samplerate = SAMPLERATE_8000Hz;
+               break;
+       default:
+               if (samplerate < 8000) {
+                       audioeq->samplerate = SAMPLERATE_8000Hz;
+               } else if (samplerate > 48000) {
+                       audioeq->samplerate = SAMPLERATE_48000Hz;
+               }
+               break;
+       }
+       /* get number of channels from caps */
+       gst_structure_get_int(ins, "channels", &channels);
+       audioeq->channels = (gshort)channels;
+
+       if ((old_samplerate != audioeq->samplerate)
+               || (old_channels != audioeq->channels)) {
+               audioeq->need_update_filter = TRUE;
+       }
+
+       gst_object_unref (pad);
+
+       return TRUE;
+}
+
+static void
+gst_audioeq_set_property (GObject * object, guint prop_id,
+       const GValue * value, GParamSpec * pspec)
+{
+       GST_DEBUG ("gst_audioeq_set_property");
+       Gstaudioeq *audioeq = GST_AUDIOEQ (object);
+       GstIirEqualizer *equ = &audioeq->equ;
+       gshort *pointer;
+
+       switch (prop_id) {
+
+       case PROP_FILTER_ACTION:
+               audioeq->filter_action = g_value_get_uint(value);
+               BANDS_LOCK(equ);
+               equ->need_new_coefficients = TRUE;
+               BANDS_UNLOCK(equ);
+               break;
+
+       case PROP_CUSTOM_EQ:
+               pointer = g_value_get_pointer(value);
+               if (pointer) {
+                       memcpy(audioeq->custom_eq, pointer, sizeof(gint) * CUSTOM_EQ_BAND_MAX);
+                       if (audioeq->filter_action == FILTER_ADVANCED_SETTING) {
+                               BANDS_LOCK(equ);
+                               equ->need_new_coefficients = TRUE;
+                               gst_audioeq_band_set_property(audioeq);
+                               BANDS_UNLOCK(equ);
+                       }
+               }
+               break;
+
+       default:
+               break;
+       }
+       GST_DEBUG ("gst_audioeq_set_property need_update_filter %d", audioeq->need_update_filter);
+}
+
+static void
+gst_audioeq_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec)
+{
+GST_DEBUG ("gst_audioeq_get_property");
+
+       Gstaudioeq *audioeq = GST_AUDIOEQ (object);
+       GstIirEqualizer *equ = &audioeq->equ;
+       gshort i;
+       gdouble widtharr[DEFAULT_CUSTOM_EQ_NUM],freqarr[DEFAULT_CUSTOM_EQ_NUM];
+
+       switch (prop_id) {
+       case PROP_FILTER_ACTION:
+               g_value_set_uint(value, audioeq->filter_action);
+               break;
+
+       case PROP_CUSTOM_EQ:
+               g_value_set_pointer(value, audioeq->custom_eq);
+               break;
+
+       case PROP_CUSTOM_EQ_NUM:
+               g_value_set_uint(value, DEFAULT_CUSTOM_EQ_NUM);
+               break;
+
+       case PROP_CUSTOM_EQ_FREQ:
+               for(i=0;i<DEFAULT_CUSTOM_EQ_NUM;i++) {
+                        freqarr[i] =   equ->bands[i]->freq;
+               }
+               g_value_set_pointer(value, &freqarr);
+               break;
+
+       case PROP_CUSTOM_EQ_WIDTH:
+               for(i=0;i<DEFAULT_CUSTOM_EQ_NUM;i++) {
+                        widtharr[i] =  equ->bands[i]->width;
+               }
+               g_value_set_pointer(value, &widtharr);
+               break;
+
+       default:
+               break;
+       }
+}
+
+static gboolean
+gst_iir_equalizer_setup (GstAudioFilter * audio, GstAudioRingBufferSpec * fmt)
+{
+GST_DEBUG ("gst_iir_equalizer_setup");
+  GstIirEqualizer *equ = GST_IIR_EQUALIZER (audio);
+
+  switch (fmt->type) {
+    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_RAW:
+      switch (fmt->info.finfo->width) {
+        case 16:
+          equ->history_size = history_size_gint16;
+          equ->process = gst_iir_equ_process_gint16;
+          break;
+        case 32:
+          equ->history_size = history_size_gfloat;
+          equ->process = gst_iir_equ_process_gfloat;
+          break;
+        case 64:
+          equ->history_size = history_size_gdouble;
+          equ->process = gst_iir_equ_process_gdouble;
+          break;
+        default:
+          return FALSE;
+      }
+      break;
+    default:
+      return FALSE;
+  }
+
+  alloc_history (equ);
+  return TRUE;
+}
+
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+    GST_DEBUG_CATEGORY_INIT(gst_audioeq_debug, "audioeq", 0, "Audio Equalizer Plugin");
+       GST_DEBUG ("audioeq plugin_init ");
+       return gst_element_register(plugin, "audioeq", GST_RANK_NONE, GST_TYPE_AUDIOEQ);
+}
+
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+       GST_VERSION_MINOR,
+       audioeq,
+       "Audio Equalizer Plugin",
+       plugin_init,
+       VERSION,
+       "LGPL",
+       "gst-plugins-ext",
+       "https://www.tizen.org/")
diff --git a/audioeq/src/gstaudioeq.h b/audioeq/src/gstaudioeq.h
new file mode 100644 (file)
index 0000000..2b698e0
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * audioeq
+ *
+ * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Aditi Narula <aditi.n@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+
+#ifndef __GST_AUDIOEQ_H__
+#define __GST_AUDIOEQ_H__
+
+#include <stdio.h>
+#include <gst/gst.h>
+#include <gst/base/gstbasetransform.h>
+#include <gst/audio/gstaudiofilter.h>
+#include <gst/audio/gstaudioringbuffer.h>
+#include <gst/controller/controller.h>
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_AUDIOEQ \
+       (gst_audioeq_get_type())
+#define GST_AUDIOEQ(obj) \
+       (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIOEQ,Gstaudioeq))
+#define GST_audioeq_CLASS(klass) \
+       (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_AUDIOEQ,GstaudioeqClass))
+#define GST_IS_AUDIOEQ(obj) \
+       (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIOEQ))
+#define GST_IS_AUDIOEQ_CLASS(klass) \
+       (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_AUDIOEQ))
+#define GST_TYPE_IIR_EQUALIZER \
+  (gst_iir_equalizer_get_type())
+#define GST_IIR_EQUALIZER(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_IIR_EQUALIZER,GstIirEqualizer))
+#define GST_IIR_EQUALIZER_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_IIR_EQUALIZER,GstIirEqualizerClass))
+#define GST_IS_IIR_EQUALIZER(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_IIR_EQUALIZER))
+#define GST_IS_IIR_EQUALIZER_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_IIR_EQUALIZER))
+
+typedef struct _Gstaudioeq Gstaudioeq;
+typedef struct _GstaudioeqClass GstaudioeqClass;
+typedef struct _GstIirEqualizer GstIirEqualizer;
+typedef struct _GstIirEqualizerClass GstIirEqualizerClass;
+typedef struct _GstIirEqualizerBand GstIirEqualizerBand;
+
+#define CUSTOM_EQ_BAND_MAX                             9
+
+#define LOWEST_FREQ (20.0)
+#define HIGHEST_FREQ (20000.0)
+
+typedef void (*ProcessFunc) (GstIirEqualizer * eq, guint8 * data, guint size,
+    guint channels);
+
+struct _GstIirEqualizer
+{
+  GstAudioFilter audiofilter;
+
+  /*< private >*/
+
+  GMutex *bands_lock;
+  GstIirEqualizerBand **bands;
+
+  /* properties */
+  guint freq_band_count;
+  /* for each band and channel */
+  gpointer history;
+  guint history_size;
+
+  gboolean need_new_coefficients;
+
+  ProcessFunc process;
+};
+
+struct _GstIirEqualizerClass
+{
+  GstAudioFilterClass audiofilter_class;
+};
+
+
+
+struct _Gstaudioeq
+{
+       GstBaseTransform element;
+
+       guint           samplerate;
+       guint           channels;
+
+       /* properties */
+       guint           filter_action;
+       gint                    custom_eq[CUSTOM_EQ_BAND_MAX];
+       gboolean                need_update_filter;
+       GstIirEqualizer equ;
+};
+
+struct _GstaudioeqClass
+{
+       GstAudioFilterClass parent_class;
+};
+
+void gst_iir_equalizer_compute_frequencies (Gstaudioeq * audioeq, guint new_count);
+
+GType gst_iir_equalizer_get_type(void);
+
+GType gst_audioeq_get_type (void);
+
+G_END_DECLS
+
+#endif /* __GST_AUDIOEQ_H__ */
+
diff --git a/audiotp/Makefile.am b/audiotp/Makefile.am
new file mode 100755 (executable)
index 0000000..308a09c
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src\r
diff --git a/audiotp/src/Makefile.am b/audiotp/src/Makefile.am
new file mode 100755 (executable)
index 0000000..436666c
--- /dev/null
@@ -0,0 +1,26 @@
+# plugindir is set in configure
+
+##############################################################################
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #
+##############################################################################
+plugin_LTLIBRARIES = libgstaudiotp.la
+
+##############################################################################
+# for the next set of variables, rename the prefix if you renamed the .la,   #
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #
+##############################################################################
+
+# sources used to compile this plug-in
+libgstaudiotp_la_SOURCES = gstaudiotp.c
+
+# flags used to compile this plugin
+# add other _CFLAGS and _LIBS as needed
+libgstaudiotp_la_CFLAGS = $(GST_CFLAGS)  $(GST_PLUGINS_BASE_CFLAGS) $(GST_BASE_CFLAGS)
+libgstaudiotp_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS)  $(GST_BASE_LIBS)
+libgstaudiotp_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gstaudiotp.h
\ No newline at end of file
diff --git a/audiotp/src/gstaudiotp.c b/audiotp/src/gstaudiotp.c
new file mode 100644 (file)
index 0000000..c5b3879
--- /dev/null
@@ -0,0 +1,559 @@
+/*
+ * audiotp
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "gstaudiotp.h"
+#include <gst/audio/audio-format.h>
+
+/*** GSTREAMER PROTOTYPES *****************************************************/
+
+#define STATIC_CAPS \
+GST_STATIC_CAPS ( \
+        GST_AUDIO_CAPS_MAKE(GST_AUDIO_FORMATS_ALL)  \
+)
+
+/* Element sink pad template */
+static GstStaticPadTemplate gst_audiotp_sink_template = GST_STATIC_PAD_TEMPLATE (
+ "sink",
+ GST_PAD_SINK,
+ GST_PAD_ALWAYS,
+ STATIC_CAPS);
+
+/* Element Source Pad template */
+static GstStaticPadTemplate gst_audiotp_src_template = GST_STATIC_PAD_TEMPLATE (
+ "src",
+ GST_PAD_SRC,
+ GST_PAD_ALWAYS,
+ STATIC_CAPS);
+
+
+////////////////////////////////////////////////////////
+//        Gstreamer Base Prototype                    //
+////////////////////////////////////////////////////////
+
+GST_DEBUG_CATEGORY_STATIC(gst_audiotp_debug);
+#define GST_CAT_DEFAULT gst_audiotp_debug
+#define _do_init(bla) \
+ GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, "audiotp", 0, "Audio trickplay plugin"); \
+ GST_DEBUG("audiotp is registered");
+
+G_DEFINE_TYPE_WITH_CODE(Gstaudiotp, gst_audiotp, GST_TYPE_ELEMENT, _do_init(G_TYPE_INVALID));
+
+static void gst_audiotp_base_init(gpointer klass);
+static void gst_audiotp_class_init(GstaudiotpClass *klass);
+static void gst_audiotp_init(Gstaudiotp *dec);
+static GstFlowReturn gst_audiotp_chain(GstPad *pad, GstObject *parent, GstBuffer *buf);
+static GstStateChangeReturn gst_audiotp_change_state(GstElement *element, GstStateChange transition);
+static void gst_audiotp_finalize(GObject *object);
+static gboolean gst_audiotp_sink_event (GstPad *pad, GstObject *parent, GstEvent *event);
+static GstFlowReturn gst_audiotp_push_silent_frame (Gstaudiotp *audiotp, GstBuffer *MetaDataBuf);
+
+
+
+////////////////////////////////////////////////////////
+//        Gstreamer Base Functions                    //
+////////////////////////////////////////////////////////
+
+/**
+ **
+ **  Description: The element details and pad templates are registered with the plugin
+ **  In Params    : @ gclass instance of Element class
+ **  return    : None
+ **  Comments    : 1. Adding templates of source and sink pad to element
+ **           2. Setting element class deatils to element
+ **
+ */
+static void
+gst_audiotp_base_init(gpointer klass)
+{
+}
+
+
+/**
+ **
+ **  Description: Initialization of the Element Class
+ **  In Param    : @ gclass instance of Element class
+ **  return    : None
+ **  Comments    : 1. Overwriting base class virtual functions
+ **                2. Installing the properties of the element
+ **
+ */
+static void
+gst_audiotp_class_init(GstaudiotpClass *klass)
+{
+  GstElementClass *gstelement_class = GST_ELEMENT_CLASS(klass);
+  GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
+
+  gobject_class->finalize = gst_audiotp_finalize;
+  gst_element_class_add_pad_template(gstelement_class, gst_static_pad_template_get(&gst_audiotp_sink_template));
+  gst_element_class_add_pad_template(gstelement_class, gst_static_pad_template_get(&gst_audiotp_src_template));
+  gst_element_class_set_static_metadata(gstelement_class, "Audio timestamp reversal plugin",
+                                                "Utility/Audio",
+                                                "Reverses audio timestamps for reverse playback",
+                                                "Samsung Electronics <www.samsung.com>");
+  gstelement_class->change_state = GST_DEBUG_FUNCPTR(gst_audiotp_change_state);
+}
+
+
+/**
+ **
+ **  Description: Initialization of the Element instance
+ **  In Params    : @ audio tp element instance
+ **           @ gclass instance of Element class
+ **  return    : None
+ **  Comments    : 1. Creating new source & sink pads using templates
+ **           2. Setting the callback functions to the pads
+ **          3. Local data initialization.
+ **
+ */
+static void
+gst_audiotp_init(Gstaudiotp *audiotp)
+{
+
+  audiotp->sinkpad = gst_pad_new_from_static_template(&gst_audiotp_sink_template, "sink");
+  audiotp->srcpad = gst_pad_new_from_static_template(&gst_audiotp_src_template, "src");
+
+  gst_pad_set_chain_function (audiotp->sinkpad, GST_DEBUG_FUNCPTR(gst_audiotp_chain));
+  gst_pad_set_event_function (audiotp->sinkpad, GST_DEBUG_FUNCPTR(gst_audiotp_sink_event));
+
+  gst_pad_use_fixed_caps(audiotp->srcpad);
+
+  gst_element_add_pad(GST_ELEMENT(audiotp), audiotp->sinkpad);
+  gst_element_add_pad(GST_ELEMENT(audiotp), audiotp->srcpad);
+
+  audiotp->reverse = g_queue_new ();
+  audiotp->head_prev = GST_CLOCK_TIME_NONE;
+  audiotp->tail_prev = GST_CLOCK_TIME_NONE;
+
+}
+
+
+/**
+ **
+ **  Description: Finalization of the Element instance (object)
+ **  In Params    : @ audiotp element instance in the form of GObject
+ **  return    : None
+ **  Comments    : 1. Local data Deinitialization.
+ **
+ **
+ */
+static void
+gst_audiotp_finalize(GObject *object)
+{
+  Gstaudiotp *audiotp = GST_AUDIOTP(object);
+
+  while (!g_queue_is_empty (audiotp->reverse)) {
+    GstMiniObject *data = g_queue_pop_head (audiotp->reverse);
+    gst_mini_object_unref (data);
+  }
+  /* freeing dealy queue */
+  g_queue_free(audiotp->reverse);
+  audiotp->reverse = NULL;
+
+  G_OBJECT_CLASS(gst_audiotp_parent_class)->finalize(object);
+}
+
+
+/**
+ **
+ **  Description: Callback function when the element's state gets changed
+ **  In Params    : @ audiotp plugin element
+ **          @ type of state change
+ **  return    : status of the state change processing
+ **  Comments    :
+ **
+ **
+ */
+static GstStateChangeReturn
+gst_audiotp_change_state(GstElement *element, GstStateChange transition)
+{
+  GstStateChangeReturn res = GST_FLOW_ERROR;
+
+  switch (transition) {
+    case GST_STATE_CHANGE_NULL_TO_READY:
+      break;
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      break;
+    default:
+      break;
+  }
+
+  res = GST_ELEMENT_CLASS(gst_audiotp_parent_class)->change_state(element, transition);
+  if ( res != GST_STATE_CHANGE_SUCCESS ) {
+    GST_ERROR ("change state error in parent class\n");
+    return GST_STATE_CHANGE_FAILURE;
+  }
+
+  switch (transition) {
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      break;
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      break;
+    default:
+      break;
+  }
+
+  return res;
+}
+
+
+/**
+ **
+ **  Description: Callback function when sinkpad gets an event
+ **  In Params    : @ Sinkpad on which the event arrives
+ **          @ event type
+ **  return    : TRUE/FALSE on success/failure of the event processing.
+ **  Comments    : 1. Process the event and push it to the source pad.
+ **
+ **
+ */
+static gboolean
+gst_audiotp_sink_event (GstPad *pad, GstObject *parent, GstEvent *event)
+{
+  Gstaudiotp *audiotp = NULL;
+  gboolean res = FALSE;
+
+  audiotp = GST_AUDIOTP(parent);
+
+  switch (GST_EVENT_TYPE(event)) {
+    /* Arrives whenever there is a jump in the normal playback. Ex:SEEK */
+    case GST_EVENT_SEGMENT: {
+      const GstSegment *segment = NULL;
+
+      GST_INFO_OBJECT (audiotp, "GST_EVENT_NEWSEGMENT");
+      gst_event_parse_segment(event, &segment);
+
+      if (segment->format != GST_FORMAT_TIME) {
+        GST_ERROR("Format is not supported\n");
+        res = gst_pad_push_event(audiotp->srcpad, event);
+        goto done;
+      }
+
+      GST_INFO_OBJECT (audiotp, "rate: %0.3f, arate: %0.3f\n", segment->rate, segment->applied_rate);
+      GST_INFO_OBJECT (audiotp, "start : %" GST_TIME_FORMAT, GST_TIME_ARGS(segment->start));
+      GST_INFO_OBJECT (audiotp, "stop  : %" GST_TIME_FORMAT, GST_TIME_ARGS(segment->stop));
+      GST_INFO_OBJECT (audiotp, "time  : %" GST_TIME_FORMAT, GST_TIME_ARGS(segment->time));
+
+      /* If we receive new_segment without FLUSH events, then we will push all the frame in queue */
+      while (!g_queue_is_empty (audiotp->reverse)) {
+           GstBuffer *MetaDataBuf;
+        GstFlowReturn ret = GST_FLOW_OK;
+               if(audiotp->is_reversed)
+          MetaDataBuf = g_queue_pop_head (audiotp->reverse);
+               else
+                 MetaDataBuf = g_queue_pop_tail (audiotp->reverse);
+        ret = gst_audiotp_push_silent_frame (audiotp, MetaDataBuf);
+        if (GST_FLOW_OK != ret)
+        {
+           GST_WARNING_OBJECT (audiotp, "pad_push returned = %s", gst_flow_get_name (ret));
+        }
+      }
+      gst_segment_copy_into(segment, &audiotp->segment);
+      res = gst_pad_push_event(audiotp->srcpad, event);
+      break;
+    }
+
+    /* Indication of the end of the stream */
+    case GST_EVENT_EOS: {
+      /* queue all buffer timestamps till we receive next discontinuity */
+      while (!g_queue_is_empty (audiotp->reverse)) {
+           GstBuffer *MetaDataBuf;
+        GstFlowReturn ret = GST_FLOW_OK;
+               if(audiotp->is_reversed)
+          MetaDataBuf = g_queue_pop_head (audiotp->reverse);
+               else
+                 MetaDataBuf = g_queue_pop_tail (audiotp->reverse);
+        ret = gst_audiotp_push_silent_frame (audiotp, MetaDataBuf);
+        if (GST_FLOW_OK != ret) {
+          GST_WARNING_OBJECT (audiotp, "pad_push returned = %s", gst_flow_get_name (ret));
+        }
+      }
+
+      res = gst_pad_push_event(audiotp->srcpad, event);
+      break;
+    }
+
+    /* Indication of the SEEK operation start */
+    case GST_EVENT_FLUSH_START: {
+      GST_INFO_OBJECT (audiotp, "GST_EVENT_FLUSH_START");
+      res = gst_pad_push_event(audiotp->srcpad, event);
+      break;
+    }
+
+    /* Indication of the SEEK operation stop */
+    case GST_EVENT_FLUSH_STOP: {
+      GST_INFO_OBJECT (audiotp, "GST_EVENT_FLUSH_STOP");
+      /* make sure that we empty the queue */
+      while (!g_queue_is_empty (audiotp->reverse)) {
+        GST_DEBUG_OBJECT (audiotp, "Flushing buffers in reverse queue....");
+        gst_buffer_unref(g_queue_pop_head (audiotp->reverse));
+      }
+
+      res = gst_pad_push_event(audiotp->srcpad, event);
+      break;
+    }
+
+    default: {
+      res = gst_pad_push_event(audiotp->srcpad, event);
+      break;
+    }
+  }
+
+  done:
+    return res;
+}
+
+
+/**
+ **
+ **  Description: Callback function when sinkpad gets a buffer (from the previous element)
+ **  In Params    : @ Sinkpad on which the buffer arrives
+ **          @ input buffer
+ **  return    : status of the buffer processing.
+ **  Comments    : 1. Handle the buffer discontinuity ( in terms of tmestamp)
+ **          2. Push or pop buffer based on discontinuity.
+ **
+ **
+ */
+static GstFlowReturn
+gst_audiotp_chain(GstPad *pad, GstObject *parent, GstBuffer *buf)
+{
+  Gstaudiotp *audiotp = GST_AUDIOTP(parent);
+  GstFlowReturn ret = GST_FLOW_OK;
+
+  if(buf == NULL) {
+    ret = GST_FLOW_ERROR;
+       goto error_exit;
+  }
+
+  GST_LOG_OBJECT (audiotp, "Input buffer : ts =%" GST_TIME_FORMAT ", dur=%" GST_TIME_FORMAT ", size=%d %s",
+         GST_TIME_ARGS(GST_BUFFER_TIMESTAMP(buf)),
+         GST_TIME_ARGS(GST_BUFFER_DURATION(buf)),
+         gst_buffer_get_size(buf), GST_BUFFER_IS_DISCONT (buf) ? " - discont" :"");
+
+  if (audiotp->segment.rate < 0.0) {
+    goto send_reverse;
+  }
+
+
+  /* Push the input data to the next element */
+  ret = gst_pad_push(audiotp->srcpad, buf);
+  if (ret != GST_FLOW_OK ) {
+   GST_WARNING("failed to push buffer %p. reason: %s", buf, gst_flow_get_name (ret));
+   buf = NULL;
+   goto error_exit;
+  }
+  return ret;
+
+send_reverse:
+  {
+    GstBuffer *MetaDataBuf = NULL;
+    GstClockTime headbuf_ts = GST_CLOCK_TIME_NONE;
+       GstClockTime tailbuf_ts = GST_CLOCK_TIME_NONE;
+
+    /* Discont buffers is mostly due to seek, when buffers of seeked timestamp gets pushed */
+    if (GST_BUFFER_IS_DISCONT(buf)) {
+      if(!g_queue_is_empty (audiotp->reverse)) {
+        GstBuffer *headbuf = (GstBuffer*) (audiotp->reverse->head->data);
+        GstBuffer *tailbuf = (GstBuffer*) (audiotp->reverse->tail->data);
+
+        headbuf_ts = GST_BUFFER_TIMESTAMP(headbuf);
+               tailbuf_ts = GST_BUFFER_TIMESTAMP(tailbuf);
+
+        GST_DEBUG_OBJECT(audiotp,"Headbuf ts =%" GST_TIME_FORMAT ", TailBuf ts =%" GST_TIME_FORMAT "",
+            GST_TIME_ARGS(GST_BUFFER_TIMESTAMP(headbuf)),
+            GST_TIME_ARGS(GST_BUFFER_TIMESTAMP(tailbuf)));
+
+        /* Check if the decoder is already having the reversal logic */
+        if(GST_BUFFER_TIMESTAMP(headbuf) > GST_BUFFER_TIMESTAMP(tailbuf)) {
+          GST_INFO_OBJECT (audiotp, "Buffers arrived in reverse order, audiotp NO NEED to reverse...");
+          audiotp->is_reversed = TRUE;
+        } else {
+          GST_INFO_OBJECT (audiotp, "Buffers arrived in forward order, audiotp NEED to reverse...");
+          audiotp->is_reversed = FALSE;
+        }
+      }
+
+      while (!g_queue_is_empty (audiotp->reverse)) {
+
+        if(audiotp->is_reversed)
+          MetaDataBuf = g_queue_pop_head (audiotp->reverse);
+        else
+          MetaDataBuf = g_queue_pop_tail (audiotp->reverse);
+
+        if (NULL == MetaDataBuf) {
+          GST_ERROR_OBJECT (audiotp, "NULL pointer...");
+          ret = GST_FLOW_ERROR;
+          goto error_exit;
+        }
+
+          /* If buffers arrive in forward order, compare the MetaDatabuf with
+               * previous head buffer timestamp.
+               * If buffers arrive in reverse order, compare the MetaDataBuf with
+               * previous tail buffer timestamp */
+        if((GST_BUFFER_TIMESTAMP(MetaDataBuf) < audiotp->head_prev && !audiotp->is_reversed)
+                               || (GST_BUFFER_TIMESTAMP(MetaDataBuf) < audiotp->tail_prev && audiotp->is_reversed)) {
+          ret = gst_audiotp_push_silent_frame (audiotp, MetaDataBuf);
+          if (MetaDataBuf) {
+            gst_buffer_unref (MetaDataBuf);
+            MetaDataBuf = NULL;
+          }
+
+          if (GST_FLOW_OK != ret) {
+            GST_WARNING_OBJECT (audiotp, "pad_push returned = %s", gst_flow_get_name (ret));
+            if (buf) {
+              gst_buffer_unref (buf);
+              buf = NULL;
+            }
+            return ret;
+          }
+        } else {
+          GST_DEBUG_OBJECT(audiotp, "Dropping the buffer out of segment with time-stamp %"GST_TIME_FORMAT,
+            GST_TIME_ARGS(GST_BUFFER_TIMESTAMP(MetaDataBuf)));
+          if (MetaDataBuf) {
+            gst_buffer_unref (MetaDataBuf);
+            MetaDataBuf = NULL;
+          }
+        }
+      }
+
+      audiotp->head_prev = headbuf_ts;
+         audiotp->tail_prev = tailbuf_ts;
+    }
+
+    MetaDataBuf = gst_buffer_new ();
+    if (NULL == MetaDataBuf) {
+      GST_ERROR_OBJECT (audiotp, "Failed to create memory...");
+      ret = GST_FLOW_ERROR;
+      goto error_exit;
+    }
+
+    /* copy buffer timestamps & FLAGS to metadata buffer */
+    gst_buffer_copy_into (MetaDataBuf, buf, GST_BUFFER_COPY_TIMESTAMPS | GST_BUFFER_COPY_FLAGS, 0, 0);
+    gst_buffer_set_size(MetaDataBuf, gst_buffer_get_size(buf));
+    GST_DEBUG_OBJECT (audiotp, "Pushing into reverse queue data of size: %d", gst_buffer_get_size(MetaDataBuf));
+
+    /* queue all buffer timestamps till we receive next discontinuity */
+    g_queue_push_tail (audiotp->reverse, MetaDataBuf);
+    if (buf) {
+      gst_buffer_unref (buf);
+      buf = NULL;
+    }
+    return GST_FLOW_OK;
+  }
+
+#if 0
+/* May be useful in future */
+send_dummy:
+  {
+
+    /* Resetting the buffer data to zero */
+    memset(GST_BUFFER_DATA(buf), 0, GST_BUFFER_SIZE(buf));
+    gst_buffer_set_caps(buf, GST_PAD_CAPS(audiotp->srcpad));
+
+    ret = gst_pad_push(audiotp->srcpad, buf);
+    if (ret != GST_FLOW_OK) {
+     GST_ERROR("Failed to push buffer. reason: %s\n", gst_flow_get_name(ret));
+     buf = NULL;
+     goto error_exit;
+    }
+    return GST_FLOW_OK;
+  }
+#endif
+
+error_exit:
+
+  GST_WARNING_OBJECT(audiotp, "Returning from audiotp's chain with reason - %s", gst_flow_get_name (ret));
+  if (buf) {
+   gst_buffer_unref (buf);
+   buf = NULL;
+  }
+  return ret;
+}
+
+
+static GstFlowReturn
+gst_audiotp_push_silent_frame (Gstaudiotp *audiotp, GstBuffer *MetaDataBuf)
+{
+
+  GstBuffer *out = NULL;
+  GstMapInfo out_info = GST_MAP_INFO_INIT;
+  GstFlowReturn ret = GST_FLOW_OK;
+
+  out = gst_buffer_new_and_alloc(gst_buffer_get_size(MetaDataBuf));
+  if(out == NULL) {
+    GST_ERROR_OBJECT (audiotp, "Failed to allocate memory...");
+    return GST_FLOW_ERROR;
+  }
+
+  /* Memset the data of the out buffer so that silent frame is sent */
+  gst_buffer_map(out, &out_info, GST_MAP_WRITE);
+  memset(out_info.data, 0, out_info.maxsize);
+  gst_buffer_unmap(out, &out_info);
+
+  gst_buffer_copy_into(out, MetaDataBuf, GST_BUFFER_COPY_FLAGS, 0, 0);
+  GST_BUFFER_OFFSET (out) = GST_BUFFER_OFFSET_END (out) = 0;
+  gst_buffer_set_size(out, gst_buffer_get_size(MetaDataBuf));
+  GST_BUFFER_TIMESTAMP(out) = GST_BUFFER_TIMESTAMP(MetaDataBuf);
+  GST_BUFFER_DURATION(out) = GST_BUFFER_DURATION(MetaDataBuf);
+
+  GST_LOG_OBJECT(audiotp, "Out buffer ts =%" GST_TIME_FORMAT ", dur=%" GST_TIME_FORMAT ", size=%d",
+       GST_TIME_ARGS(GST_BUFFER_TIMESTAMP(out)),
+       GST_TIME_ARGS(GST_BUFFER_DURATION(out)),
+       gst_buffer_get_size(out));
+
+  ret = gst_pad_push(audiotp->srcpad, out);
+  if (ret != GST_FLOW_OK) {
+    GST_ERROR_OBJECT (audiotp, "Failed to push buffer. reason: %s\n", gst_flow_get_name(ret));
+    out = NULL;
+  }
+
+  return ret;
+}
+
+static gboolean
+gst_audiotp_plugin_init (GstPlugin *plugin)
+{
+  if (!gst_element_register (plugin, "audiotp", GST_RANK_PRIMARY, gst_audiotp_get_type())) {
+    return FALSE;
+  }
+  return TRUE;
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+                   GST_VERSION_MINOR,
+                   audiotp,
+                   "Audio trickplay plugin",
+                   gst_audiotp_plugin_init,
+                   VERSION,
+                   "LGPL",
+                   "Samsung Electronics Co",
+                   "http://www.samsung.com")
diff --git a/audiotp/src/gstaudiotp.h b/audiotp/src/gstaudiotp.h
new file mode 100755 (executable)
index 0000000..0b3dc92
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * audiotp
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifndef __GST_AUDIOTP_H__
+#define __GST_AUDIOTP_H__
+
+#include <gst/gst.h>
+#include <stdlib.h>
+#include <string.h>
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_AUDIOTP             (gst_audiotp_get_type())
+#define GST_AUDIOTP(obj)             (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIOTP,Gstaudiotp))
+#define GST_AUDIOTP_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_AUDIOTP,GstaudiotpClass))
+#define GST_AUDIOTP_GET_CLASS(klass) (G_TYPE_INSTANCE_GET_CLASS((klass),GST_TYPE_AUDIOTP,GstaudiotpClass))
+#define GST_IS_AUDIOTP(obj)          (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIOTP))
+#define GST_IS_AUDIOTP_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_AUDIOTP))
+#define GST_AUDIOTP_CAST(obj)        ((Gstaudiotp *)(obj))
+
+typedef struct _Gstaudiotp Gstaudiotp;
+typedef struct _GstaudiotpClass GstaudiotpClass;
+
+struct _Gstaudiotp
+{
+  GstElement element;
+  GstPad *sinkpad;
+  GstPad *srcpad;
+  GQueue *reverse; /* used in reverse trickplay */
+  GstSegment segment;
+
+  /* Flag to indicate the new buffer recieved is discountinued in
+  its time-stamp */
+  gboolean discont;
+  gboolean is_reversed;
+  GstClockTime head_prev;
+  GstClockTime tail_prev;
+};
+
+struct _GstaudiotpClass
+{
+  GstElementClass parent_class;
+};
+
+GType gst_audiotp_get_type (void);
+
+G_END_DECLS
+
+#endif /* __GST_AUDIOTP_H__ */
\ No newline at end of file
diff --git a/autogen.sh b/autogen.sh
new file mode 100755 (executable)
index 0000000..d4c6d40
--- /dev/null
@@ -0,0 +1,12 @@
+#!/bin/sh
+# you can either set the environment variables AUTOCONF and AUTOMAKE
+# to the right versions, or leave them unset and get the RedHat 7.3 defaults
+
+aclocal -I m4 -I common/m4
+libtoolize --copy --force
+autoheader
+autoconf
+automake --add-missing --copy --foreign
+
+echo "Now type 'make' to compile $package."
+
diff --git a/autoregen.sh b/autoregen.sh
new file mode 100755 (executable)
index 0000000..c67a299
--- /dev/null
@@ -0,0 +1,2 @@
+#!/bin/sh
+./autogen.sh  $@
diff --git a/common/ChangeLog b/common/ChangeLog
new file mode 100755 (executable)
index 0000000..72f093a
--- /dev/null
@@ -0,0 +1,1343 @@
+2008-03-07  Edward Hervey  <edward.hervey@collabora.co.uk>
+
+       * m4/gtk-doc.m4: (GTK_DOC_CHECK): 
+       The previous commit to this file by Stefan Kost mentionned checking for
+       SED, but NOT checking for gtkdoc-check (wth is that doing there ??).
+       Therefore, removing the check for gtkdoc-check
+
+2008-03-03  David Schleef  <ds@schleef.org>
+
+       * m4/ax_create_stdint_h.m4: Oops, checked in the wrong copy of
+         this file.  (Update from upstream)
+
+2008-03-03  David Schleef  <ds@schleef.org>
+
+       * m4/ax_create_stdint_h.m4:  Update from upstream.  Fixes a bug
+         compiling with MSVC.
+
+2008-03-03  Edward Hervey  <edward.hervey@collabora.co.uk>
+
+       * m4/pkg.m4:
+       Allow override of pkg-config results, as proposed by configure --help.
+       This is in fact just a backport from upstream pkg.m4.
+       Fixes #518892
+
+2008-03-03  Peter Kjellerstedt  <pkj@axis.com>
+
+       * ChangeLog:
+       Changelog surgery of my previous commit to add bugzilla reference.
+       * m4/gst-args.m4:
+       Add AG_GST_CHECK_PLUGIN and AG_GST_DISABLE_PLUGIN to make it easier
+       to include and exclude plug-ins without external references, i.e.,
+       plug-ins listed in GST_PLUGINS_SELECTED. (#498222)
+
+2008-03-03  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add another glibc suppression.
+
+2008-02-29  Peter Kjellerstedt  <pkj@axis.com>
+
+       * m4/gst-feature.m4:
+       Make the comment before defines generated via AG_GST_CHECK_FEATURE
+       look nicer. (#498222)
+
+2008-02-26  Jan Schmidt  <jan.schmidt@sun.com>
+
+       * m4/Makefile.am:
+       * m4/as-gcc-inline-assembly.m4:
+       Add Dave Schleef's GCC inline assembly detection macro
+       for using in gst-plugins-good in the goom 2k4 plugin.
+
+2008-02-25  Andy Wingo  <wingo@pobox.com>
+
+       * gst-autogen.sh: Instead of only passing certain arguments to
+       configure, pass anything that we didn't handle. Much friendlier.
+       Fixes #34412.
+
+2008-02-23  Jan Schmidt  <Jan.Schmidt@sun.com>
+
+       * m4/gst-error.m4:
+       Store the detected compiler flags into ERROR_CFLAGS rather than
+       ERROR_CXXFLAGS, and use the macro that checks the C compiler, not
+       the C++ one.
+
+2008-02-23  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * m4/gst-error.m4:
+         Reflow checks for additional warning flags so they're not
+         nested, which fixes the result reporting in the configure
+         output.
+
+2008-02-22  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * m4/as-compiler-flag.m4:
+         Add AS_CXX_COMPILER_FLAG
+
+       * m4/gst-error.m4:
+         Add AG_GST_SET_ERROR_CXXFLAGS (Forte bits need testing)
+
+2008-02-22  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * gtk-doc-plugins.mak:
+         Add 'check-inspected-versions' target; this helps identify
+         files that should have been removed or where the version
+         number should (ideally) be updated before a release
+         (which doesn't happen automatically if the releaser doesn't
+         build that plugin locally). Not adding at a distcheck hook
+         yet though, because it's not really that important and would
+         probably also be a problem on buildbots.
+
+2008-02-22  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add even more glibc 2.7 suppressions.
+
+2008-02-22  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add another suppression for GLib caching some values after
+       the first call.
+
+2008-02-12  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       Patch by:
+         Tim Mooney <mooney at dogbert dot cc dot ndsu dot nodak dot edu>
+
+       * m4/gst-error.m4:
+       Use no%E_MACRO_REDEFINED on Solaris to prevent compiler warnings.
+       Fixes bug #515905.
+
+2008-02-11  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add a few more glibc 2.7 suppressions to make the avisubtitle unit
+       test valgrind clean. Fixes bug #515703.
+
+2008-02-08  Stefan Kost  <ensonic@users.sf.net>
+
+       * ChangeLog:
+         Changelog surgery for last commit.
+
+2008-02-08  Stefan Kost  <ensonic@users.sf.net>
+
+       * m4/gtk-doc.m4:
+         Conditionally check for SED. Also sync a bit with upstream macro.
+
+2008-02-08  Stefan Kost  <ensonic@users.sf.net>
+
+       * gtk-doc-plugins.mak:
+       * gtk-doc.mak:
+         Use '$(SED)' instead of 'sed'. Don't use -i for in-place as its gnu
+         only, move to a temp file instead.
+
+2008-02-06  Stefan Kost  <ensonic@users.sf.net>
+
+       * gtk-doc-plugins.mak:
+       * gtk-doc.mak:
+        As our docs are versioned, we need to patch the index.sgml file to have
+        correct paths there, unless we also want to fork gtk-doc's xsl (which
+        we don't). This hopefully fixes xrefs between modules.
+
+2008-02-02  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * m4/gst-feature.m4:
+       Use printf instead of echo as "echo -e" isn't POSIX and doesn't work
+       with strict POSIX shells like tcsh or dash and also not every platform
+       has a /bin/echo that supports it.
+
+2008-01-24  Stefan Kost  <ensonic@users.sf.net>
+
+       * ChangeLog:
+         ChangeLog surgery.
+
+       * gstdoc-scangobj:
+         Sync the object scanner with gtk-doc fixes. Update args and hierarchy
+         files.
+
+2008-01-20  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * check.mak:
+       * coverage/lcov.mak:
+       * gtk-doc-plugins.mak:
+       * release.mak:
+       Use $(MAKE) instead of make to fix the build if GNU make is called
+       something else on the system.
+       
+       * m4/as-docbook.m4:
+       Fix path for docbook.xsl if we have no /etc/xml/catalog and add a
+       docbook-xsl search path for FreeBSD.
+
+2008-01-18  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add a suppression for a glibc bug:
+       http://valgrind.org/docs/manual/faq.html#faq.exit_errors>
+
+2008-01-18  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add some more glibc 2.7 suppressions and make the GLib suppressions
+       for the home/tmp/etc directory caching a bit more generic.
+
+2008-01-18  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * gst.supp:
+       Add some glibc 2.7 supressions as found on Debian/unstable.
+
+2008-01-14  Jan Schmidt  <jan.schmidt@sun.com>
+
+       * download-translations:
+       Apparently I have problems with leaving things commented out when
+       I edit shell scripts.
+
+2008-01-12  Jan Schmidt  <Jan.Schmidt@sun.com>
+
+       * download-translations:
+       Remove bash-isms
+
+2008-01-12  Jan Schmidt  <Jan.Schmidt@sun.com>
+
+       * check-exports:
+       Restore the cleanup rm of our tmp file which I didn't mean to leave 
+       commented out.
+
+2008-01-12  Jan Schmidt  <Jan.Schmidt@sun.com>
+
+       * check-exports:
+         Fixes to make check-export work on both Solaris and Linux
+
+       * m4/gst-error.m4:
+         Disable extra warning category (argument mismatch) as an error
+         on Forte, as it prevents the libcheck fail_if macros from compiling.
+
+       * win32.mak:
+         Substitute the GStreamer version so things will keep working in 0.11
+
+2008-01-11  Tim-Philipp Müller  <tim at centricular dot net>
+
+       Patch by: Peter Kjellerstedt <pkj axis com>
+
+       * m4/gst-glib2.m4:
+       * m4/gst-libxml2.m4:
+         Improve/fix output from configure if either glib-2.0 or
+         libxml2 are not installed (#498222).
+
+2008-01-09  Stefan Kost  <ensonic@users.sf.net>
+
+       * coverage/lcov.mak:
+         Update coverage make-rules: use them conditionaly, use libtool mode
+         and use lcov to cleanup.
+
+2007-12-18  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * glib-gen.mak:
+         Also use #include "header" instead of #include <header> for the
+         headers that were used to generate the source files for the same
+         reason as below.
+
+         Remove whitespace before #include.
+
+2007-12-18  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * glib-gen.mak:
+         Use #include "header" instead of #include <header> for the generated
+         enum C files as the file will always be in the same directory and
+         some compilers seem to be a bit strict about that unless . is added
+         to the include path.
+
+         Include all headers that were used to generate the source files in
+         the C file as they're used there.
+
+2007-12-17  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * win32.mak: (win32), (win32defs), (win32crlf):
+         Make check for CR LF in Visual C++ 6.0 project files
+         work, based on patch by David Schleef (#496722, #393626).
+       
+2007-12-17  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * Makefile.am:
+         Don't forget to dist the new win32.mak.
+
+2007-12-17  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * win32.mak: (win32), (win32defs):
+         Move common win32 Makefile foo into this new file.
+
+2007-12-15  Stefan Kost  <ensonic@users.sf.net>
+
+       * gtk-doc-plugins.mak:
+       * gtk-doc.mak:
+         We should have never forked this that much :/.
+
+2007-12-13  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * check-exports:
+         Fix build on the ppc64 build bot.
+
+2007-12-13  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * check-exports:
+         Suppress more unintentional exports (too much hassle to rename them,
+         since the win32 project files would need changing too).
+
+2007-12-12  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * Makefile.am:
+         check-exports should be disted.
+
+2007-12-12  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * check-exports:
+         Add quick'n'dirty script to check the exported symbols of a library
+         against the symbols in the corresponding .def file (#493983). Based
+         on script by Ole André Vadla RavnÃ¥s.
+
+2007-11-06  Jan Schmidt  <jan.schmidt@sun.com>
+
+       * gtk-doc-plugins.mak:
+       Fix distcheck by making sure the types files are treated like the
+       other gtkdoc-scangobj generated files.
+
+2007-09-21  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * m4/gst-args.m4:
+         Let the AG_GST_ARG_ENABLE_EXPERIMENTAL macro default to disable
+         building of experimental plugins. Nobody uses it yet and the
+         --enable--experimental stuff from gst-plugins-good defaults to
+         disable too.
+
+2007-09-06  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * gtk-doc-plugins.mak:
+         Just use the normal 'check' target and avoid a circular
+         dependency.
+
+2007-09-06  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * gtk-doc-plugins.mak:
+         Add rule to error out if .hierarchy file contains tabs.
+
+2007-08-20  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * download-translations:
+       * po.mak:
+         If there are new languages, they need to be added to po/LINGUAS.
+
+2007-08-20  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * download-translations:
+       * po.mak:
+         Fix up 'download-po' a bit, so that we find new translations
+         for languages that aren't in our po/LINGUAS file yet too.
+
+2007-07-16  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * gst.supp:
+       Add a suppression for GLib caching the tmp dir seen on an
+       Ubuntu Feisty system.
+
+2007-07-13  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * m4/gst-feature.m4:
+       If we want to use 'echo -e', call /bin/echo instead of the shell's
+       since -e is a bash extension, and our /bin/sh might not be being
+       provided by bash.
+
+2007-07-01  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * po.mak:
+         Translation project has moved.  Also, no idea how this used to
+         work given that we weren't downloading a .po file.
+
+2007-06-25  Stefan Kost  <ensonic@users.sf.net>
+
+       * gst-xmlinspect.py:
+       * plugins.xsl:
+         Also extract element caps for plugin-docs. Fixes parts of #117692.
+
+2007-06-21  Tim-Philipp Müller  <tim at centricular dot net>
+
+       Patch by: Andreas Schwab
+
+       * m4/gst-feature.m4:
+         Fix quoting (#449493).
+
+2007-06-10  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * m4/gst-parser.m4:
+       Only generate the parser if bison >= 1.875 _and_ flex >= 2.5.31 is
+       installed and use pre-generated sources otherwise. Fixes bug #444820.
+
+2007-05-11  Michael Smith <msmith@fluendo.com>
+
+       * gst.supp:
+         Suppression variant for our good friend the TLS leak, this time for
+         Ubuntu Feisty/x86.
+
+2007-05-09  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * gtk-doc-plugins.mak:
+         Fix make distcheck again; change some spaces to tabs in makefile.
+
+2007-04-29  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc-plugins.mak (-module):
+         Error out when the html build step gives warnings, so they get
+         fixed properly.
+
+2007-04-23  Stefan Kost  <ensonic@users.sf.net>
+
+       * m4/gst-feature.m4:
+         Add macro AG_GST_PARSE_SUBSYSTEM_DISABLES that checks the defines in
+         the configuration header and AC_DEFINES the setings.
+
+2007-04-19  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       Patch by: Vincent Torri <vtorri at univ-evry dot fr>
+
+       * m4/gst-parser.m4:
+       Put the AC_MSG_RESULT output in brackets to get it properly written to
+       the terminal.
+
+2007-04-18  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * m4/gst-parser.m4:
+       Check for flex >= 2.5.31 and set GENERATE_PARSER if we have at least
+       that version. Otherwise use pre-generated parser sources as we can't
+       raise the required flex version. HAVE_MT_SAVE_FLEX is obsolete now
+       as we use a new enough flex version anyway. First part of #349180
+
+2007-04-10  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         Allow pre-setting the GST(PB)_TOOLS/PLUGINS_DIR variables to help
+         builds against older GStreamer.
+
+2007-03-25  Sebastian Dröge  <slomo@circular-chaos.org>
+
+       * m4/gst-parser.m4:
+       Fix the flex version check. It ignored the micro version before.
+
+2007-03-09  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * check.mak:
+       Use the same timeout when generating valgrind suppressions as 
+       running the valgrind test.
+
+       * gst.supp:
+       Add some more suppressions and stuff.
+
+2007-03-08  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * check.mak:
+       Make sure GSlice is disabled when building suppressions too.
+
+       * gst.supp:
+       Add around *850* lines of suppressions for one-time initialisations
+       inside libasound and gconf/bonobo/ORBit. I feel so dirty.
+
+2007-03-07  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * gst.supp:
+       add a suppression for this GConf flup on the FC5 buildbot.
+
+2007-03-06  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * gst.supp:
+       Make the suppression a little more generic, to catch the FC5 
+       backtrace too.
+
+2007-03-06  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * gst.supp:
+       Add a suppression for libcdio 0.76. It leaks an internal struct
+       when the CD-ROM device is not accessible.
+
+2007-02-28  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-arch.m4:
+         Move a line that was in the wrong macro
+
+2007-02-28  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst.m4:
+         Add
+       * m4/gst-arch.m4:
+       * m4/gst-args.m4:
+       * m4/gst-check.m4:
+       * m4/gst-debuginfo.m4:
+       * m4/gst-default.m4:
+       * m4/gst-doc.m4:
+       * m4/gst-error.m4:
+       * m4/gst-feature.m4:
+       * m4/gst-function.m4:
+       * m4/gst-gettext.m4:
+       * m4/gst-glib2.m4:
+       * m4/gst-libxml2.m4:
+       * m4/gst-parser.m4:
+       * m4/gst-plugin-docs.m4:
+       * m4/gst-plugindir.m4:
+       * m4/gst-valgrind.m4:
+       * m4/gst-x11.m4:
+         Convert all macros to use AG_GST style so we can properly warn
+         when they're missing if configure.ac calls AG_GST_INIT
+         Will require update in all GStreamer modules.
+
+2007-02-11  Stefan Kost  <ensonic@users.sf.net>
+
+       * m4/gst-args.m4:
+         Remove 'enable' from configure switch description as this leads to 
+         confusing lines like "disable enable builing ...".
+       * m4/gst-feature.m4:
+         Fix comment to sound less horrible.
+
+2007-02-07  Tim-Philipp Müller  <tim at centricular dot net>
+
+       Patch by: Will Newton  <will.newton gmail com>
+
+       * m4/gst-check.m4:
+         Use $PKG_CONFIG rather than pkg-config directly, the one in our path
+         might not be the one we want, like when cross-compiling. Also, other
+         macros such as PKG_CHECK_MODULES use $PKG_CONFIG, so we should
+         probably too just for consistency. Fixes #405288.
+
+2007-01-08  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * m4/gst-parser.m4:
+         Need to use double square brackets again so m4 doesn't remove them
+         (fixes #378931).
+
+       * m4/gst-args.m4:
+         Use double square brackets here as well, for the same reason.
+
+2007-01-05  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * m4/gst-parser.m4:
+         Use 'sed' rather than 'tr' to strip trailing letters from version
+         numbers, since 'tr' might not be available and we know sed is
+         (#378931).
+
+2006-10-21  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * check.mak:
+         Increase default timeout under valgrind, 60 is just too short and
+         some tests take a bit longer these days and not everyone has a
+         beefy machine.
+
+2006-09-29  Michael Smith  <msmith@fluendo.com>
+
+       * gst.supp:
+         More suppressions for edgy. 
+
+2006-09-28  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * m4/gst-glib2.m4:
+       Use gmodule-no-export-2.0.pc instead of gmodule-2.0.pc - we neither
+       want nor need --export-dynamic (which ends up making us export a bunch
+       of unneeded symbols)
+
+2006-09-14  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * gst.supp:
+         Some suppressions for the more recent ld.so in ubuntu edgy.
+
+2006-08-23  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * gst.supp:
+         Shorten function trail so the suppression works on
+         my ubuntu dapper system with core cvs as well.
+
+2006-07-28  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * gst.supp:
+       Extra suppressions from my Ubuntu x86_64 machine
+
+2006-07-24  Tim-Philipp Müller  <tim at centricular dot net>
+
+       Patch by: Frederic Peters <fpeters at entrouvert com>
+
+       * m4/gst-parser.m4:
+         Need to double square brackets in .m4 files. Should fix bison
+         version detection with version numbers like 1.23a (#348354).
+
+2006-07-24  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * check.mak:
+       Valgrind fails to find tests written in tests/check/ directly (rather
+       than a subdir) - because valgrind gets run with a filename that
+       doesn't contain a relative path, it goes searching /usr/bin instead.
+       Run with ./.... to make things work either way.
+
+       * gtk-doc-plugins.mak:
+       Add $(top_builddir)/src as a place to look for plugins
+       when building too, since that's where gst-template keeps things
+
+2006-07-23  Stefan Kost  <ensonic@users.sf.net>
+
+       Patch by: Frederic Peters <fpeters@entrouvert.com>
+
+       * m4/gst-parser.m4:
+         Fix bison detection (#348354)
+
+2006-07-21  Stefan Kost  <ensonic@users.sf.net>
+
+       * m4/gst-parser.m4:
+         check for bison and flex
+
+2006-07-13  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-plugin-docs.m4:
+         remove the configure argument for enabling plugin doc build;
+         having gtk-doc enabled and pyxml present is enough of a trigger
+
+2006-07-03  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * coverage/lcov.mak:
+         fix up rules to work with gst-python as well
+         run "make lcov" to test and generate the reports
+         run "make lcov-reset" to redo it after that
+
+2006-07-02  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * Makefile.am:
+       * check.mak:
+         add an inspect target that inspects every element feature,
+         so we can have that added for coverage
+       * coverage/lcov.mak:
+         add support for lcov
+
+2006-07-02  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-args.m4:
+         when building with gcov, reset CFLAGS and friends to O0
+
+2006-07-02  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-args.m4:
+         Find the gcov that matches the gcc version
+         Only allow gcov if we use gcc
+
+2006-07-02  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * Makefile.am:
+       * coverage/coverage-report-entry.pl:
+       * coverage/coverage-report.pl:
+       * coverage/coverage-report.xsl:
+         copy coverage reporting files from dbus
+
+2006-07-01  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-args.m4:
+         libtool strips gcov's -f flags, so libgcov does not get
+         linked in.  Setting GCOV_LIBS with -lgcov fixes libtool's
+         stripping
+         also show what pkg-config-path we set
+
+2006-06-22  Tim-Philipp Müller  <tim at centricular dot net>
+
+       Patch by: Peter Kjellerstedt <pkj at axis com>
+
+       * m4/gst-feature.m4:
+         Show list of plugins without external dependencies that
+         will not be built as well (#344136).
+
+2006-06-15  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * m4/gst-plugin-docs.m4:
+         add GST_PLUGIN_DOCS, which checks for everything needed
+         to build the plugin docs (namely gtk-doc and pyxml); also
+         adds a new --enable-plugin-docs configure switch; will
+         set ENABLE_PLUGIN_DOCS conditional for use in Makefile.am
+         files (see #344039).
+
+2006-06-11  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         add GST_PKG_CHECK_MODULES, which in the normal case of checking
+         for a dependency lib for a plug-in only needs two arguments
+         to do the right thing.
+       * m4/gst-feature.m4:
+         clean up output a little of feature checking; also deal with
+         non-plug-in feature checks
+       * m4/Makefile.am:
+       * m4/gst-gstreamer.m4:
+         remove this file; it's a useless check
+
+2006-06-06  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-arch.m4:
+         add PPC64 so we can have separate structure sizes for it
+
+2006-06-05  Edward Hervey  <edward@fluendo.com>
+
+       * gtk-doc.mak:
+       Check for the proper .devhelp2 file to remove.
+
+2006-05-31  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc.mak:
+         allow a magic variable to suppress errors from docbuilding
+
+2006-05-30  Thomas Vander Stichele  <thomas (at) apestaart (dot) org>
+
+       * gtk-doc.mak:
+         error out if gtkdoc-mktmpl finds unused declarations
+
+2006-05-28  Edward Hervey  <edward@fluendo.com>
+
+       * gst.supp:
+       Reverting previous commit.  That's good to know, Edward, but why ?
+       
+2006-05-28  Edward Hervey  <edward@fluendo.com>
+
+       * gst.supp:
+       Added suppresion for memleak in g_option_context_parse on fc5-64
+
+2006-05-19  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         set GSTPB_PLUGINS_DIR just like GST_PLUGINS_DIR
+
+2006-05-18  Tim-Philipp Müller  <tim at centricular dot net>
+
+       * check.mak:
+         Fix 'make help' in check directories, it should be
+         'valgrind.gen-suppressions' not 'valgrind-gen-suppressions'
+         (not changing target to match help string on purpose to keep
+         scripts etc. functional).
+
+2006-05-18  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       Patch by: Peter Kjellerstedt
+
+       * m4/gst-arch.m4:
+         add support for CRIS and CRISv32.
+
+2006-05-17  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * m4/gst-args.m4:
+       Fix the macros for command-line supplied package and origin names
+       so they don't end up being configure as "" (Fixes #341479)
+
+2006-05-14  Jan Schmidt <thaytan@mad.scientist.com>
+
+       * gtk-doc.mak:
+       Add uninstall rule to remove .devhelp2 files.
+
+2006-05-09  Edward Hervey  <edward@fluendo.com>
+
+       * gst.supp: 
+         Add suppression for GSlice version of
+         g_type_init calloc leak
+
+2006-04-05  Michael Smith  <msmith@fluendo.com>
+
+       * gst.supp:
+         Delete a bogus suppression for the registry code.
+         Generalise a suppression for a glib bug (see #337404)
+
+2006-04-04  Michael Smith <msmith@fluendo.com>
+
+       * gst.supp:
+         Add a leak suppression: the existing glibc-doesn't-free-TLS one
+         wasn't triggering here.
+
+2006-04-04  Michael Smith <msmith@fluendo.com>
+
+       * gst.supp:
+         Add some minimally-neccesary suppressions for my x86/dapper system.
+
+2006-04-01  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * plugins.xsl:
+         Do not display an origin link if origin does not start with http
+         See #323798
+
+2006-04-01  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-args.m4:
+       * m4/gst-feature.m4:
+         add more macros
+       * m4/gst-x11.m4:
+         X11-related checks
+
+2006-04-01  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/as-version.m4:
+         newer version
+       * m4/gst-args.m4:
+       * m4/gst-doc.m4:
+         update and add other macros to be shared across projects
+
+2006-03-24  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst.supp:
+         add a suppression for g_parse_debug_string
+
+2006-03-23  Stefan Kost  <ensonic@users.sf.net>
+
+       * gstdoc-scangobj:
+         sync fully with gtkdoc-0.15
+
+2006-03-23  Stefan Kost  <ensonic@users.sf.net>
+
+       * gstdoc-scangobj:
+       * gtk-doc.mak:
+         sync a little with gtk-doc mainline
+
+2006-03-17  Wim Taymans  <wim@fluendo.com>
+
+       * gst.supp:
+         add another clone suppression
+         change all glibc suppressions to match 2.3.*
+
+2006-03-09  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/check.m4:
+         fix test so it actually works when the normal check is used
+         over debian's/ubuntu's
+
+2006-03-08  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * check.mak:
+       Set G_SLICE=always-malloc when valgrinding tests
+       (closes #333272)
+
+2006-02-21  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * m4/gst-glib2.m4:
+       Fix debug output when the GLib version prerequisite is not found
+
+2006-02-13  Andy Wingo  <wingo@pobox.com>
+
+       * m4/check.m4: Hack around Debian/Ubuntu's broken installation of
+       the PIC version of check as libcheck_pic.a. Should work with
+       cross-compilation too. Grr.
+
+2006-02-06  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-default.m4:
+         switch to auto* sinks for defaults
+
+2006-02-02  Wim Taymans  <wim@fluendo.com>
+
+       * check.mak:
+         add a .valgrind.gen-suppressions target to aid in generating
+         suppressions
+       * gst.supp:
+         add more repressions from my debian glibc as of today
+
+2006-02-02  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc-plugins.mak:
+         only add srcdir/gst if it exists
+
+2006-01-30  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * release.mak:
+         don't complain about disted enums in win32
+
+2006-01-20  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         AC_SUBST CFLAGS and LIBS
+         do a non-command because something is stripping out our AC_SUBST
+
+2006-01-20  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-args.m4:
+       * m4/gst-valgrind.m4:
+         properly give a "no" result manually when providing a
+         not-found action to fix configure output
+
+2006-01-20  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/pkg.m4:
+         update with a more recent version
+
+2006-01-07  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gettext.patch:
+         make Makefile depend on LINGUAS, so rebuilds work when adding
+         a language
+
+2006-01-03  Michael Smith  <msmith@fluendo.com>
+
+       * check.mak:
+         Clarify error message from valgrind test runs.
+
+2005-12-16  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-arch.m4:
+         define HOST_CPU
+
+2005-11-29  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         add a valgrind-forever target for tests
+
+2005-11-28  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         when a "make test.check" run fails, make it rerun the test with       
+         at least debug level 2
+
+2005-11-14  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/Makefile.am:
+       * m4/gst-check.m4:
+         fix check for base plugins
+       * m4/gst-default.m4:
+         add m4 to set default elements
+
+2005-10-18  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         check for tools correctly
+
+2005-10-18  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc.mak:
+         only enable breaking on new API when make distcheck passes,
+         not before
+
+2005-10-18  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         Resurrect Julien's dead body and wipe his mind clean
+
+2005-10-18  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-check.m4:
+         Kill Julien
+
+2005-10-17  Julien MOUTTE  <julien@moutte.net>
+
+       * m4/gst-check.m4: I know Thomas will kill me but this 
+       ifelse statement seems incorrect as it is always setting
+       required to "yes". With this one it seems to work. Fixes
+       build of gst-plugins-base on my setup where gstreamer-check
+       is definitely not present/required.
+
+2005-10-18  Stefan Kost  <ensonic@users.sf.net>
+
+       * gtk-doc.mak:
+         make build break on new api that has not been added to the
+         sections file
+
+2005-10-17  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-glib2.m4:
+       * m4/Makefile.am:
+       * m4/gst-check.m4:
+         add macro for easy checks for GStreamer libs
+
+2005-10-16  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-glib2.m4:
+         update, warn in error cases
+
+2005-10-16  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-error.m4:
+         add GST_SET_DEFAULT_LEVEL
+
+2005-10-16  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/Makefile.am:
+       * m4/gst-gettext.m4:
+         remove the AM_GNU_GETTEXT* calls, they need to be in configure.ac
+       * m4/gst-glib2.m4:
+         clean up and re-use in core soon
+       * m4/gst-plugindir.m4:
+         macro to set up PLUGINDIR and plugindir define/var
+
+2005-10-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/Makefile.am:
+       * m4/gst-gettext.m4:
+         add macro for setting up gettext
+
+2005-10-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-args.m4:
+         add some .m4's for argument checking that can be shared among modules
+
+2005-10-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/as-libtool.m4:
+         set _LT_LDFLAGS
+       * m4/gst-libxml2.m4:
+         document
+
+2005-10-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-arch.m4:
+         indent a little
+         add AC_REQUIRE
+       * m4/gst-error.m4:
+         clean up
+
+2005-10-12  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst-autogen.sh:
+         update version detection expression to catch stuff like
+         Libtool (libtool15) 1.5.0
+
+2005-10-11  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst.supp:
+         commit 6 new suppressions related to g_module_open; can these
+         really not be folded into one ?
+
+2005-10-11  Edward Hervey  <edward@fluendo.com>
+
+       * gst.supp: 
+       made the <g_type_init calloc 2> suppression more generic
+       Added pthread memleak suppresions
+       Added nss_parse_* memleak suppresion (used by g_option_context_parse)
+
+2005-10-11  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         be more strict, more leak resolution
+       * gst.supp:
+         clean up the g_type_init suppressions
+
+2005-10-07  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/Makefile.am:
+       * m4/gst-valgrind.m4:
+         put the valgrind detection in an .m4
+
+2005-09-29  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         add some more targets, like "help", but also more intensive tests
+
+2005-09-23  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc.mak:
+         make certain doc warnings fatal so people maintain docs again
+
+2005-09-23  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * Makefile.am:
+       * gtk-doc-plugins.mak:
+       * scangobj-merge.py:
+         merge additions from the .signals.new and .args.new file in
+         the original ones, only updating if necessary
+
+2005-09-23  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst-xmlinspect.py:
+       * gstdoc-scangobj:
+       * gtk-doc-plugins.mak:
+         fix properly for new API; make update in plugins dir now works
+
+2005-09-20  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst-xmlinspect.py:
+       * gstdoc-scangobj:
+         some fixes for new API
+       * gtk-doc-plugins.mak:
+         set environment properly
+
+2005-09-17  David Schleef  <ds@schleef.org>
+
+       * gtk-doc-plugins.mak: Use new environment variables.
+
+2005-09-16  Michael Smith <msmith@fluendo.com>
+
+       * gstdoc-scangobj:
+         Make the scanobj code reflect registry/plugin API changes
+
+2005-09-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc-plugins.mak:
+         split out scanobj step (which will be run by doc maintainer)
+         from scan step (which will be run on every build)
+         clean up some of the commands for make distcheck
+
+2005-09-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc-plugins.mak:
+       * mangle-tmpl.py:
+         first stab at reorganizing the plugins build so we can maintain
+         element docs
+
+2005-09-14  David Schleef  <ds@schleef.org>
+
+       * as-libtool.mak: Remove
+       * m4/as-libtool.m4: The libtool bug that this worked around has
+         been fixed.
+       * m4/as-version.m4: Don't define GST_RELEASE, since it causes
+         config.h to be regenerated needlessly, and we don't use it.
+
+2005-09-14  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc-plugins.mak:
+         error out on inspect failure
+
+2005-09-14  Michael Smith <msmith@fluendo.com>
+
+       * glib-gen.mak:
+         Don't call glib-mkenums with arguments that confuse/break MinGW,
+         fixes 316155.
+
+2005-09-03  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gtk-doc-plugins.mak:
+       * gtk-doc.mak:
+       * m4/gst-doc.m4:
+         separate out gtk-doc and docbook stuff
+         have two separate --enable configure flags
+
+2005-08-26  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         add a .gdb target; rebuild registry for each target, otherwise
+         a code rebuild always triggers a reg rebuild, and it's just too
+         annoying
+       * gstdoc-scangobj:
+
+2005-08-21  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         separate out REGISTRY_ENVIRONMENT; we want to use that from
+         our valgrind runs, but we also want TESTS_ENVIRONMENT to contain
+         everything that the first test, gst-register, needs
+
+2005-08-21  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         parse output of valgrind and check for definitely lost, and error
+         out; somehow I was led to believe valgrind returns non-zero for
+         leaks, but I can't make it do that, so let's parse
+
+2005-08-20  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * check.mak:
+         for some weird reason valgrind does not report actual memleaks
+         if GST_PLUGIN_PATH is set to anything but the core gstreamer dir
+         while valgrind is running.  Since the registry is going to go
+         anyway, I don't want to waste any more time on this; I just run
+         valgrind without GST_PLUGIN_PATH set.  Since the registry loading
+         doesn't check if GST_PLUGIN_PATH got changed as a reason to rebuild
+         the registry, that's actually fine.
+
+2005-08-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * mangle-tmpl.py:
+         keep original Long_Description; only insert an include if it's
+         not already the first line in there
+       * plugins.xsl:
+         output more information for plugins, including an origin hyperlink
+
+2005-08-15  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst-xmlinspect.py:
+         a first stab at inspecting plugins and outputting an xml description
+       * gtk-doc-plugins.mak:
+         a gtk-doc using snippet for plugins documentation
+       * plugins.xsl:
+         a stylesheet to convert gst-xmlinspect.py output to docbook output
+         for inclusion in the gtk-doc stuff
+
+2005-07-20  Ronald S. Bultje  <rbultje@ronald.bitfreak.net>
+
+       * m4/gst-doc.m4:
+         s/pdf/eps/ in test for whether we output EPS images (#309379).
+
+2005-07-18  Andy Wingo  <wingo@pobox.com>
+
+       * m4/as-libtool-tags.m4: Ooh, backported from libtool 1.6. Much
+       better. Thanks, Paolo Bonzini!
+       
+       * m4/Makefile.am (EXTRA_DIST): 
+       * m4/as-libtool-tags.m4: New file, tries to disable some CXX and
+       fortran checks.
+
+2005-07-08  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-error.m4:
+         add macro to set ERROR_CFLAGS
+
+2005-06-30  Jan Schmidt  <thaytan@mad.scientist.com>
+
+       * gst-autogen.sh:
+         Remove the old autoregen.sh if it exists before recreating it,
+         to prevent confusing any shell process that might be reading it
+         currently.
+
+2005-06-29  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gtk-doc.m4:
+         added
+
+2005-06-03  Stefan Kost  <ensonic@users.sf.net>
+
+       * gst-autogen.sh: create autoregen.sh *before* shifting the options
+
+2005-05-17  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst-autogen.sh: only update autoregen.sh on actual runs
+
+2005-03-11  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/check.m4: m4 from the check unit test suite
+
+2004-12-14  David Schleef  <ds@schleef.org>
+
+       * m4/gst-arch.m4: remove MMX stuff, since it doesn't work and
+       isn't needed anywhere
+
+2004-12-08  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * gst-autogen.sh:
+         allow failure command to be run so we can clean upfrom autopoint
+
+2004-09-03  Zeeshan Ali Khattak <zeenix@gmail.com>
+       * m4/gst-feature.m4: Trying to correct the GST_CHECK_CONFIGPROG macro
+
+2004-07-21  Benjamin Otte  <otte@gnome.org>
+
+       * m4/.cvsignore: exciting updates for libtool m4 files
+
+2004-07-12  David Schleef  <ds@schleef.org>
+
+       * m4/as-objc.m4:  Add a macro to test for objective C
+
+2004-06-12  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-feature.m4:
+         not all of them support --plugin-libs, so redirect stderr
+
+2004-06-12  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/as-scrub-include.m4:
+         sync with upstream to 0.1.4.  Fixes #132440
+
+2004-06-07  Benjamin Otte  <otte@gnome.org>
+
+       * m4/gst-feature.m4:
+         write a big marker into configure output when checking next plugin
+         to allow easier parsing of why plugins are(n't) built.
+
+2004-06-01  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/as-compiler-flag.m4:
+       * m4/as-compiler.m4:
+       * m4/as-libtool.m4:
+       * m4/as-version.m4:
+         sync with upstream, change sticky options to -ko
+
+2004-05-24  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/as-scrub-include.m4: synced with upstream
+
+2004-05-03  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * po.mak:
+          snippet for updating .po files
+
+2004-03-18  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * Makefile.am:
+       * m4/Makefile.am:
+          integrate these with the dist
+
+2004-03-17  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * release.mak: add a release target
+
+2004-03-09  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       patch by: Stephane Loeuillet
+
+       * m4/ax_create_stdint_h.m4:
+          use head -n instead of head - (#136500)
+
+2004-03-05  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-doc.m4: don't build PS without dvips binary
+
+2004-02-22   Julio M. Merino Vidal <jmmv@menta.net>
+
+       reviewed by: Benjamin Otte  <otte@gnome.org>
+
+       * m4/as-docbook.m4:
+         don't use == operator with test(1) (fixes #135115)
+
+2004-02-16  Thomas Vander Stichele  <thomas at apestaart dot org>
+       * common/m4/gst-arch.m4: x86_64 is x86 too (clue from Fedora 2 test)
+
+2004-02-13  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-feature.m4:
+          remove AM_CONDITIONAL for the subsystem since automake 1.6.x
+          requires that call be in configure.ac
+
+2004-02-13  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-libxml2.m4:
+          take required version as argument, and default to 2.4.9 if not
+          specified
+
+2004-02-12  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/gst-feature.m4:
+          rename and fix up GST_CHECK_DISABLE_SUBSYSTEM
+
+2004-02-11  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * common/m4/as-ac-expand.m4:
+       * common/m4/as-auto-alt.m4:
+       * common/m4/as-compiler-flag.m4:
+       * common/m4/as-compiler.m4:
+       * common/m4/as-docbook.m4:
+       * common/m4/as-libtool.m4:
+       * common/m4/as-scrub-include.m4:
+       * common/m4/as-version.m4:
+       * common/m4/glib-gettext.m4:
+       * common/m4/gst-arch.m4:
+       * common/m4/gst-debuginfo.m4:
+       * common/m4/gst-doc.m4:
+       * common/m4/gst-feature.m4:
+       * common/m4/gst-function.m4:
+       * common/m4/gst-glib2.m4:
+       * common/m4/gst-gstreamer.m4:
+       * common/m4/gst-libxml2.m4:
+       * common/m4/gst-makecontext.m4:
+       * common/m4/gst-mcsc.m4:
+       * common/m4/pkg.m4:
+          fix underquoted macros as reported by automake 1.8.x (#133800)
+
+2004-02-11  Johan Dahlin  <johan@gnome.org>
+
+       * gst-autogen.sh: Use A-Z instead of A-z in sed expression to
+       avoid a warning
+
+2004-02-05  Thomas Vander Stichele  <thomas (at) apestaart (dot) org>
+
+       * m4/gst-doc.m4:
+          we use --output-format=xml and --ingnore-files options to
+          gtkdoc-mkdb, which got added between 0.9 and 1.0
+
+2004-02-04  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+       * m4/as-libtool.m4: remove AM_PROG_LIBTOOL so it can move back
+          to configure.ac to shut up libtoolize
+
+2004-02-03  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+        * glib-gen.mak: added; used to generate enums and marshal code
+
+2004-01-13  Thomas Vander Stichele  <thomas at apestaart dot org>
+
+        * gettext.patch: added; used by autogen.sh to make sure
+          GETTEXT_PACKAGE is understood from po/Makefile.in.in -> po/Makefile.in
+
diff --git a/common/Makefile.am b/common/Makefile.am
new file mode 100644 (file)
index 0000000..cac4ff5
--- /dev/null
@@ -0,0 +1,16 @@
+SUBDIRS = m4
+
+EXTRA_DIST = \
+       ChangeLog \
+       gettext.patch \
+       glib-gen.mak gtk-doc.mak upload.mak release.mak win32.mak \
+       gst-autogen.sh \
+       check-exports \
+       c-to-xml.py gst-xmlinspect.py mangle-tmpl.py scangobj-merge.py \
+       gtk-doc-plugins.mak \
+       plugins.xsl gstdoc-scangobj \
+       gst.supp check.mak \
+       coverage/lcov.mak \
+       coverage/coverage-report.pl \
+       coverage/coverage-report.xsl \
+       coverage/coverage-report-entry.pl
diff --git a/common/c-to-xml.py b/common/c-to-xml.py
new file mode 100755 (executable)
index 0000000..8448fd2
--- /dev/null
@@ -0,0 +1,34 @@
+# -*- Mode: Python -*-
+# vi:si:et:sw=4:sts=4:ts=4
+
+"""
+Convert a C program to valid XML to be included in docbook
+"""
+
+import sys
+import os
+from xml.sax import saxutils
+
+def main():
+    if len(sys.argv) == 1:
+        sys.stderr.write("Please specify a source file to convert")
+        sys.exit(1)
+    source = sys.argv[1]
+
+    if not os.path.exists(source):
+        sys.stderr.write("%s does not exist.\n" % source)
+        sys.exit(1)
+
+    content = open(source, "r").read()
+
+    # print header
+    print '<?xml version="1.0"?>'
+    print '<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">'
+    print
+    print '<programlisting>'
+
+    # print content
+    print saxutils.escape(content).encode('UTF-8')
+    print '</programlisting>'
+        
+main()
diff --git a/common/check-exports b/common/check-exports
new file mode 100755 (executable)
index 0000000..16df41f
--- /dev/null
@@ -0,0 +1,71 @@
+#!/bin/sh
+# check-exports
+#
+# quick'n'dirty script that retrieves the list of exported symbols of a given
+# library using 'nm', and compares that against the list of symbols-to-export
+# of our win32/common/libfoo.def files.
+
+if [ $# -ne 2 ]; then
+       echo "Usage: $0 library.def library.so"
+       exit 1
+fi
+
+def_path="$1"
+def_name="$(basename $def_path)"
+lib_path="$2"
+
+lib_result="`mktemp /tmp/defname.XXXXXX`"
+
+LC_ALL=C
+export LC_ALL
+
+# On Solaris, add -p to get the correct output format
+NMARGS=
+if nm -V 2>&1 |grep Solaris > /dev/null; then
+  NMARGS=-p
+fi
+
+# FIXME 0.11: in 0.11, we should change the export filter to only export
+# _gst_foo, but not __gst_foo (we can't change this now, since we added
+# __gst_debug_min and __gst_debug_enabled at some point and need to keep
+# ABI compatibility).  So below we special-case some symbols that shouldn't
+# really be exported, either because we're too lazy to rename them to something
+# that's not exported (like the _gst_parse_* stuff) or because we had them in
+# public headers at some point although they shouldn't be and so we need to
+# keep them exported now (like _gst_debug_init, 
+# __gst_element_factory_add_interface or
+# __gst_element_factory_add_static_pad_template).  We suppress them here to
+# make sure they're at least not exported in the windows msvc build (they
+# were never in the .def file, so they never got exported).
+# _end is special cased because for some reason it is reported as an exported
+# BSS symbol, unlike on linux where it's a local absolute symbol.
+nm $NMARGS $lib_path | awk \
+       '{
+               if ($3 !~ /^_gst_parse_yy/ && \
+                   $3 !~ /^_gst_[a-z]*_init/ && \
+                   $3 !~ /^_gst_parse_launch/ && \
+                   $3 !~ /^__gst_element_details_/ && \
+                   $3 !~ /^__gst_element_factory_add_/ && \
+                   $3 !~ /^gst_interfaces_marshal/ && \
+                   $3 ~ /^[_]*(gst_|Gst|GST_).*/)
+               {
+                       if ($2 ~ /^[BSDG]$/)
+                               print "\t" $3 " DATA"
+                       else if ($2 == "T")
+                               print "\t" $3
+               }
+        }' | sort | awk '{ if (NR == 1) print "EXPORTS"; print $0; }' \
+       > $lib_result
+
+diffoutput=`diff -u $def_path $lib_result`
+
+rm $lib_result
+
+if test "x$diffoutput" = "x"; then
+  exit 0;
+else
+  echo -n "$diffoutput" >&2
+  echo >&2
+  exit 1;
+fi
+
diff --git a/common/check.mak b/common/check.mak
new file mode 100755 (executable)
index 0000000..d31569f
--- /dev/null
@@ -0,0 +1,149 @@
+clean-local-check:
+       for i in `find . -name ".libs" -type d`; do \
+         rm -rf $$i; \
+       done
+
+if HAVE_VALGRIND
+# hangs spectacularly on some machines, so let's not do this by default yet
+check-valgrind:
+       $(MAKE) valgrind
+else
+check-valgrind:
+       @true
+endif
+
+LOOPS = 10
+
+# run any given test by running make test.check
+# if the test fails, run it again at at least debug level 2
+%.check: %
+       @$(TESTS_ENVIRONMENT)                                   \
+       CK_DEFAULT_TIMEOUT=20                                   \
+       $* ||                                                   \
+       $(TESTS_ENVIRONMENT)                                    \
+       GST_DEBUG=$$GST_DEBUG,*:2                               \
+       CK_DEFAULT_TIMEOUT=20                                   \
+       $*
+
+# run any given test in a loop
+%.torture: %
+       @for i in `seq 1 $(LOOPS)`; do                          \
+       $(TESTS_ENVIRONMENT)                                    \
+       CK_DEFAULT_TIMEOUT=20                                   \
+       $*; done
+
+# run any given test in an infinite loop
+%.forever: %
+       @while true; do                                         \
+       $(TESTS_ENVIRONMENT)                                    \
+       CK_DEFAULT_TIMEOUT=20                                   \
+       $* || break; done
+
+# valgrind any given test by running make test.valgrind
+%.valgrind: %
+       $(TESTS_ENVIRONMENT)                                    \
+       CK_DEFAULT_TIMEOUT=360                                  \
+       G_SLICE=always-malloc                                   \
+       libtool --mode=execute                                  \
+       $(VALGRIND_PATH) -q                                     \
+       $(foreach s,$(SUPPRESSIONS),--suppressions=$(s))        \
+       --tool=memcheck --leak-check=full --trace-children=yes  \
+       --leak-resolution=high --num-callers=20                 \
+       ./$* 2>&1 | tee valgrind.log
+       @if grep "==" valgrind.log > /dev/null 2>&1; then       \
+           rm valgrind.log;                                    \
+           exit 1;                                             \
+       fi
+       @rm valgrind.log
+       
+# valgrind any given test and generate suppressions for it
+%.valgrind.gen-suppressions: %
+       $(TESTS_ENVIRONMENT)                                    \
+       CK_DEFAULT_TIMEOUT=360                                  \
+       G_SLICE=always-malloc                                   \
+       libtool --mode=execute                                  \
+       $(VALGRIND_PATH) -q                                     \
+       $(foreach s,$(SUPPRESSIONS),--suppressions=$(s))        \
+       --tool=memcheck --leak-check=full --trace-children=yes  \
+       --leak-resolution=high --num-callers=20                 \
+       --gen-suppressions=all                                  \
+       ./$* 2>&1 | tee suppressions.log
+       
+# valgrind any given test until failure by running make test.valgrind-forever
+%.valgrind-forever: %
+       @while $(MAKE) $*.valgrind; do                          \
+         true; done
+
+# gdb any given test by running make test.gdb
+%.gdb: %
+       $(TESTS_ENVIRONMENT)                                    \
+       CK_FORK=no                                              \
+       libtool --mode=execute                                  \
+       gdb $*
+
+# torture tests
+torture: $(TESTS)
+       -rm test-registry.xml
+       @echo "Torturing tests ..."
+       for i in `seq 1 $(LOOPS)`; do                           \
+               $(MAKE) check ||                                        \
+               (echo "Failure after $$i runs"; exit 1) ||      \
+               exit 1;                                         \
+       done
+       @banner="All $(LOOPS) loops passed";                    \
+       dashes=`echo "$$banner" | sed s/./=/g`;                 \
+       echo $$dashes; echo $$banner; echo $$dashes
+
+# forever tests
+forever: $(TESTS)
+       -rm test-registry.xml
+       @echo "Forever tests ..."
+       while true; do                                          \
+               $(MAKE) check ||                                        \
+               (echo "Failure"; exit 1) ||                     \
+               exit 1;                                         \
+       done
+
+# valgrind all tests
+valgrind: $(TESTS)
+       @echo "Valgrinding tests ..."
+       @failed=0;                                                      \
+       for t in $(filter-out $(VALGRIND_TESTS_DISABLE),$(TESTS)); do   \
+               $(MAKE) $$t.valgrind;                                   \
+               if test "$$?" -ne 0; then                               \
+                        echo "Valgrind error for test $$t";            \
+                       failed=`expr $$failed + 1`;                     \
+                       whicht="$$whicht $$t";                          \
+                fi;                                                    \
+       done;                                                           \
+       if test "$$failed" -ne 0; then                                  \
+               echo "$$failed tests had leaks or errors under valgrind:";      \
+               echo "$$whicht";                                        \
+               false;                                                  \
+       fi
+
+# inspect every plugin feature
+GST_INSPECT = $(GST_TOOLS_DIR)/gst-inspect-$(GST_MAJORMINOR)
+inspect:
+       @echo "Inspecting features ..."
+       for e in `$(TESTS_ENVIRONMENT) $(GST_INSPECT) | head -n -2      \
+         | cut -d: -f2`;                                               \
+         do echo Inspecting $$e;                                       \
+            $(GST_INSPECT) $$e > /dev/null 2>&1; done
+
+help:
+       @echo "make check                         -- run all checks"
+       @echo "make torture                       -- run all checks $(LOOPS) times"
+       @echo "make (dir)/(test).check            -- run the given check once"
+       @echo "make (dir)/(test).forever          -- run the given check forever"
+       @echo "make (dir)/(test).torture          -- run the given check $(LOOPS) times"
+       @echo
+       @echo "make (dir)/(test).gdb              -- start up gdb for the given test"
+       @echo
+       @echo "make valgrind                      -- valgrind all tests"
+       @echo "make (dir)/(test).valgrind         -- valgrind the given test"
+       @echo "make (dir)/(test).valgrind-forever -- valgrind the given test forever"
+       @echo "make (dir)/(test).valgrind.gen-suppressions -- generate suppressions"
+       @echo "                                               and save to suppressions.log"
+       @echo "make inspect                       -- inspect all plugin features"
+
diff --git a/common/coverage/coverage-report-entry.pl b/common/coverage/coverage-report-entry.pl
new file mode 100755 (executable)
index 0000000..8f653af
--- /dev/null
@@ -0,0 +1,70 @@
+#!/usr/bin/perl
+#
+# Copyright (C) 2006 Daniel Berrange
+#
+# 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 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+print <<EOF;
+<html>
+<head>
+<title>Coverage report for $ARGV[0]</title>
+<style type="text/css">
+          span.perfect {
+            background: rgb(0,255,0);
+          }
+          span.terrible {
+            background: rgb(255,0,0);
+          }
+</style>
+</head>
+<body>
+<h1>Coverage report for $ARGV[0]</h1>
+
+<pre>
+EOF
+
+
+while (<>) {
+    s/&/&amp;/g;
+    s/</&lt;/g;
+    s/>/&gt;/g;
+
+    if (/^\s*function (\S+) called (\d+) returned \d+% blocks executed \d+%/) {
+       my $class = $2 > 0 ? "perfect" : "terrible";
+       $_ = "<span class=\"$class\" id=\"" . $1 . "\">$_</span>";
+    } elsif (/^\s*branch\s+\d+\s+taken\s+(\d+)%\s+.*$/) {
+       my $class = $1 > 0 ? "perfect" : "terrible";
+       $_ = "<span class=\"$class\">$_</span>";
+    } elsif (/^\s*branch\s+\d+\s+never executed.*$/) {
+       my $class = "terrible";
+       $_ = "<span class=\"$class\">$_</span>";
+    } elsif (/^\s*call\s+\d+\s+never executed.*$/) {
+       my $class = "terrible";
+       $_ = "<span class=\"$class\">$_</span>";
+    } elsif (/^\s*call\s+\d+\s+returned\s+(\d+)%.*$/) {
+       my $class = $1 > 0 ? "perfect" : "terrible";
+       $_ = "<span class=\"$class\">$_</span>";
+    }
+    
+
+    print;
+}
+
+print <<EOF;
+</pre>
+</body>
+</html>
+EOF
diff --git a/common/coverage/coverage-report.pl b/common/coverage/coverage-report.pl
new file mode 100755 (executable)
index 0000000..046bc37
--- /dev/null
@@ -0,0 +1,125 @@
+#!/usr/bin/perl
+#
+# Copyright (C) 2006 Daniel Berrange
+#
+# 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 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+use warnings;
+use strict;
+
+my %coverage = ( functions => {}, files => {} );
+
+my %filemap;
+
+my $type;
+my $name;
+
+my @functions;
+
+while (<>) {
+    if (/^Function '(.*)'\s*$/) {
+       $type = "function";
+       $name = $1;
+       $coverage{$type}->{$name} = {};
+       push @functions, $name;
+    } elsif (/^File '(.*?)'\s*$/) {
+       $type = "file";
+       $name = $1;
+       $coverage{$type}->{$name} = {};
+       
+       foreach my $func (@functions) {
+           $coverage{"function"}->{$func}->{file} = $name;
+       }
+       @functions = ();
+    } elsif (/^Lines executed:(.*)%\s*of\s*(\d+)\s*$/) {
+       $coverage{$type}->{$name}->{lines} = $2;
+       $coverage{$type}->{$name}->{linesCoverage} = $1;
+    } elsif (/^Branches executed:(.*)%\s*of\s*(\d+)\s*$/) {
+       $coverage{$type}->{$name}->{branches} = $2;
+       $coverage{$type}->{$name}->{branchesCoverage} = $1;
+    } elsif (/^Taken at least once:(.*)%\s*of\s*(\d+)\s*$/) {
+       $coverage{$type}->{$name}->{conds} = $2;
+       $coverage{$type}->{$name}->{condsCoverage} = $1;
+    } elsif (/^Calls executed:(.*)%\s*of\s*(\d+)\s*$/) {
+       $coverage{$type}->{$name}->{calls} = $2;
+       $coverage{$type}->{$name}->{callsCoverage} = $1;
+    } elsif (/^No branches$/) {
+       $coverage{$type}->{$name}->{branches} = 0;
+       $coverage{$type}->{$name}->{branchesCoverage} = "100.00";
+       $coverage{$type}->{$name}->{conds} = 0;
+       $coverage{$type}->{$name}->{condsCoverage} = "100.00";
+    } elsif (/^No calls$/) {
+       $coverage{$type}->{$name}->{calls} = 0;
+       $coverage{$type}->{$name}->{callsCoverage} = "100.00";
+    } elsif (/^\s*(.*):creating '(.*)'\s*$/) {
+       $filemap{$1} = $2;
+    } elsif (/^\s*$/) {
+       # nada
+    } else {
+       warn "Shit [$_]\n";
+    }
+}
+
+my %summary;
+foreach my $type ("function", "file") {
+    $summary{$type} = {};
+    foreach my $m ("lines", "branches", "conds", "calls") {
+       my $totalGot = 0;
+       my $totalMiss = 0;
+       my $count = 0;
+       foreach my $func (keys %{$coverage{function}}) {
+           $count++;
+           my $got = $coverage{function}->{$func}->{$m};
+           $totalGot += $got;
+           my $miss = $got * $coverage{function}->{$func}->{$m ."Coverage"} / 100;
+           $totalMiss += $miss;
+       }
+       $summary{$type}->{$m} = sprintf("%d", $totalGot);
+       $summary{$type}->{$m . "Coverage"} = sprintf("%.2f", $totalMiss / $totalGot * 100);
+    }
+}
+
+
+
+print "<coverage>\n";
+
+foreach my $type ("function", "file") {
+    printf "<%ss>\n", $type;
+    foreach my $name (sort { $a cmp $b } keys %{$coverage{$type}}) {
+       my $rec = $coverage{$type}->{$name};
+       printf "  <entry name=\"%s\" details=\"%s\">\n", $name, ($type eq "file" ? $filemap{$name} : $filemap{$rec->{file}});
+       printf "    <lines count=\"%s\" coverage=\"%s\"/>\n", $rec->{lines}, $rec->{linesCoverage};
+       if (exists $rec->{branches}) {
+           printf "    <branches count=\"%s\" coverage=\"%s\"/>\n", $rec->{branches}, $rec->{branchesCoverage};
+       }
+       if (exists $rec->{conds}) {
+           printf "    <conditions count=\"%s\" coverage=\"%s\"/>\n", $rec->{conds}, $rec->{condsCoverage};
+       }
+       if (exists $rec->{calls}) {
+           printf "    <calls count=\"%s\" coverage=\"%s\"/>\n", $rec->{calls}, $rec->{callsCoverage};
+       }
+       print  "  </entry>\n";
+    }
+    
+    printf "  <summary>\n";
+    printf "    <lines count=\"%s\" coverage=\"%s\"/>\n", $summary{$type}->{lines}, $summary{$type}->{linesCoverage};
+    printf "    <branches count=\"%s\" coverage=\"%s\"/>\n", $summary{$type}->{branches}, $summary{$type}->{branchesCoverage};
+    printf "    <conditions count=\"%s\" coverage=\"%s\"/>\n", $summary{$type}->{conds}, $summary{$type}->{condsCoverage};
+    printf "    <calls count=\"%s\" coverage=\"%s\"/>\n", $summary{$type}->{calls}, $summary{$type}->{callsCoverage};
+    printf  "  </summary>\n";
+    printf "</%ss>\n", $type;
+}
+
+print "</coverage>\n";
diff --git a/common/coverage/coverage-report.xsl b/common/coverage/coverage-report.xsl
new file mode 100755 (executable)
index 0000000..b19ebb6
--- /dev/null
@@ -0,0 +1,235 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<!--\r
+#\r
+# Copyright (C) 2006 Daniel Berrange\r
+#\r
+# This program is free software; you can redistribute it and/or modify\r
+# it under the terms of the GNU General Public License as published by\r
+# the Free Software Foundation; either version 2 of the License, or\r
+# (at your option) any later version.\r
+#\r
+# This program is distributed in the hope that it will be useful,\r
+# but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+# GNU General Public License for more details.\r
+#\r
+# You should have received a copy of the GNU General Public License\r
+# along with this program; if not, write to the Free Software\r
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+-->\r
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"\r
+                version="1.0">\r
+\r
+  <xsl:output method="html"/>\r
+\r
+  <xsl:template match="coverage">\r
+    <html>\r
+      <head>\r
+        <title>Coverage report</title>\r
+        <style type="text/css">\r
+          tbody tr.odd td.label {\r
+            border-top: 1px solid rgb(128,128,128);\r
+            border-bottom: 1px solid rgb(128,128,128);\r
+          }\r
+          tbody tr.odd td.label {\r
+            background: rgb(200,200,200);\r
+          }\r
+          \r
+          thead, tfoot {\r
+            background: rgb(60,60,60);\r
+            color: white;\r
+            font-weight: bold;\r
+          }\r
+\r
+          tr td.perfect {\r
+            background: rgb(0,255,0);\r
+            color: black;\r
+          }\r
+          tr td.excellant {\r
+            background: rgb(140,255,140);\r
+            color: black;\r
+          }\r
+          tr td.good {\r
+            background: rgb(160,255,0);\r
+            color: black;\r
+          }\r
+          tr td.poor {\r
+            background: rgb(255,160,0);\r
+            color: black;\r
+          }\r
+          tr td.bad {\r
+            background: rgb(255,140,140);\r
+            color: black;\r
+          }\r
+          tr td.terrible {\r
+            background: rgb(255,0,0);\r
+            color: black;\r
+          }\r
+        </style>\r
+      </head>\r
+      <body>\r
+        <h1>Coverage report</h1>\r
+        <xsl:apply-templates/>\r
+      </body>\r
+    </html>\r
+  </xsl:template>\r
+\r
+  <xsl:template match="functions">\r
+    <h2>Function coverage</h2>\r
+    <xsl:call-template name="content">\r
+      <xsl:with-param name="type" select="'function'"/>\r
+    </xsl:call-template>\r
+  </xsl:template>\r
+  \r
+\r
+  <xsl:template match="files">\r
+    <h2>File coverage</h2>\r
+    <xsl:call-template name="content">\r
+      <xsl:with-param name="type" select="'file'"/>\r
+    </xsl:call-template>\r
+  </xsl:template>\r
+\r
+  <xsl:template name="content">\r
+    <xsl:param name="type"/>\r
+    <table>\r
+      <thead>\r
+        <tr>\r
+          <th>Name</th>\r
+          <th>Lines</th>\r
+          <th>Branches</th>\r
+          <th>Conditions</th>\r
+          <th>Calls</th>\r
+        </tr>\r
+      </thead>\r
+      <tbody>\r
+        <xsl:for-each select="entry">\r
+          <xsl:call-template name="entry">\r
+            <xsl:with-param name="type" select="$type"/>\r
+            <xsl:with-param name="class">\r
+              <xsl:choose>\r
+                <xsl:when test="position() mod 2">\r
+                  <xsl:text>odd</xsl:text>\r
+                </xsl:when>\r
+                <xsl:otherwise>\r
+                  <xsl:text>even</xsl:text>\r
+                </xsl:otherwise>\r
+              </xsl:choose>\r
+            </xsl:with-param>\r
+          </xsl:call-template>\r
+        </xsl:for-each>\r
+      </tbody>\r
+      <tfoot>\r
+        <xsl:for-each select="summary">\r
+          <xsl:call-template name="entry">\r
+            <xsl:with-param name="type" select="'summary'"/>\r
+            <xsl:with-param name="class">\r
+              <xsl:choose>\r
+                <xsl:when test="position() mod 2">\r
+                  <xsl:text>odd</xsl:text>\r
+                </xsl:when>\r
+                <xsl:otherwise>\r
+                  <xsl:text>even</xsl:text>\r
+                </xsl:otherwise>\r
+              </xsl:choose>\r
+            </xsl:with-param>\r
+          </xsl:call-template>\r
+        </xsl:for-each>\r
+      </tfoot>\r
+    </table>\r
+  </xsl:template>\r
+  \r
+  <xsl:template name="entry">\r
+    <xsl:param name="type"/>\r
+    <xsl:param name="class"/>\r
+    <tr class="{$class}">\r
+      <xsl:choose>\r
+        <xsl:when test="$type = 'function'">\r
+          <td class="label"><a href="{@details}.html#{@name}"><xsl:value-of select="@name"/></a></td>\r
+        </xsl:when>\r
+        <xsl:when test="$type = 'file'">\r
+          <td class="label"><a href="{@details}.html"><xsl:value-of select="@name"/></a></td>\r
+        </xsl:when>\r
+        <xsl:otherwise>\r
+          <td class="label">Summary</td>\r
+        </xsl:otherwise>\r
+      </xsl:choose>\r
+\r
+      <xsl:if test="count(lines)">\r
+        <xsl:apply-templates select="lines"/>\r
+      </xsl:if>\r
+      <xsl:if test="not(count(lines))">\r
+        <xsl:call-template name="missing"/>\r
+      </xsl:if>\r
+\r
+      <xsl:if test="count(branches)">\r
+        <xsl:apply-templates select="branches"/>\r
+      </xsl:if>\r
+      <xsl:if test="not(count(branches))">\r
+        <xsl:call-template name="missing"/>\r
+      </xsl:if>\r
+\r
+      <xsl:if test="count(conditions)">\r
+        <xsl:apply-templates select="conditions"/>\r
+      </xsl:if>\r
+      <xsl:if test="not(count(conditions))">\r
+        <xsl:call-template name="missing"/>\r
+      </xsl:if>\r
+\r
+      <xsl:if test="count(calls)">\r
+        <xsl:apply-templates select="calls"/>\r
+      </xsl:if>\r
+      <xsl:if test="not(count(calls))">\r
+        <xsl:call-template name="missing"/>\r
+      </xsl:if>\r
+\r
+    </tr>\r
+  </xsl:template>\r
+  \r
+  <xsl:template match="lines">\r
+    <xsl:call-template name="row"/>\r
+  </xsl:template>\r
+\r
+  <xsl:template match="branches">\r
+    <xsl:call-template name="row"/>\r
+  </xsl:template>\r
+\r
+  <xsl:template match="conditions">\r
+    <xsl:call-template name="row"/>\r
+  </xsl:template>\r
+\r
+  <xsl:template match="calls">\r
+    <xsl:call-template name="row"/>\r
+  </xsl:template>\r
+\r
+  <xsl:template name="missing">\r
+    <td></td>\r
+  </xsl:template>\r
+\r
+  <xsl:template name="row">\r
+    <xsl:variable name="quality">\r
+      <xsl:choose>\r
+        <xsl:when test="@coverage = 100">\r
+          <xsl:text>perfect</xsl:text>\r
+        </xsl:when>\r
+        <xsl:when test="@coverage >= 80.0">\r
+          <xsl:text>excellant</xsl:text>\r
+        </xsl:when>\r
+        <xsl:when test="@coverage >= 60.0">\r
+          <xsl:text>good</xsl:text>\r
+        </xsl:when>\r
+        <xsl:when test="@coverage >= 40.0">\r
+          <xsl:text>poor</xsl:text>\r
+        </xsl:when>\r
+        <xsl:when test="@coverage >= 20.0">\r
+          <xsl:text>bad</xsl:text>\r
+        </xsl:when>\r
+        <xsl:otherwise>\r
+          <xsl:text>terrible</xsl:text>\r
+        </xsl:otherwise>\r
+      </xsl:choose>\r
+    </xsl:variable>\r
+    \r
+    <td class="{$quality}"><xsl:value-of select="@coverage"/>% of <xsl:value-of select="@count"/></td>\r
+  </xsl:template>\r
+\r
+</xsl:stylesheet>\r
diff --git a/common/coverage/lcov.mak b/common/coverage/lcov.mak
new file mode 100755 (executable)
index 0000000..0ca9456
--- /dev/null
@@ -0,0 +1,42 @@
+## .PHONY so it always rebuilds it
+.PHONY: lcov-reset lcov lcov-run lcov-report lcov-upload
+
+# run lcov from scratch, always
+lcov-reset:
+       $(MAKE) lcov-run
+       $(MAKE) lcov-report
+
+# run lcov from scratch if the dir is not there
+lcov:
+       $(MAKE) lcov-reset
+
+if GST_GCOV_ENABLED
+# reset run coverage tests
+lcov-run:
+       @-rm -rf lcov
+       lcov --directory . --zerocounters
+       -if test -d tests/check; then $(MAKE) -C tests/check inspect; fi
+       -$(MAKE) check
+
+# generate report based on current coverage data
+lcov-report:
+       mkdir lcov
+       lcov --compat-libtool --directory . --capture --output-file lcov/lcov.info
+       lcov -l lcov/lcov.info | grep -v "`cd $(top_srcdir) && pwd`" | cut -d: -f1 > lcov/remove
+       lcov -l lcov/lcov.info | grep "tests/check/" | cut -d: -f1 >> lcov/remove
+       lcov -r lcov/lcov.info `cat lcov/remove` > lcov/lcov.cleaned.info
+       rm lcov/remove
+       mv lcov/lcov.cleaned.info lcov/lcov.info
+       genhtml -t "$(PACKAGE_STRING)" -o lcov --num-spaces 2 lcov/lcov.info
+
+lcov-upload: lcov
+       rsync -rvz -e ssh --delete lcov/* gstreamer.freedesktop.org:/srv/gstreamer.freedesktop.org/www/data/coverage/lcov/$(PACKAGE)
+
+else
+lcov-run:
+       echo "Need to reconfigure with --enable-gcov"
+
+lcov-report:
+       echo "Need to reconfigure with --enable-gcov"
+endif
+
diff --git a/common/gettext.patch b/common/gettext.patch
new file mode 100755 (executable)
index 0000000..659718e
--- /dev/null
@@ -0,0 +1,23 @@
+--- po/Makefile.in.in.orig     2006-01-07 12:03:45.000000000 +0100
++++ po/Makefile.in.in  2006-01-07 12:04:23.000000000 +0100
+@@ -11,6 +11,9 @@
+ PACKAGE = @PACKAGE@
+ VERSION = @VERSION@
++# thomas: add GETTEXT_PACKAGE substitution as used in Makevars
++GETTEXT_PACKAGE = @GETTEXT_PACKAGE@
++
+ SHELL = /bin/sh
+ @SET_MAKE@
+@@ -305,7 +308,9 @@
+ update-gmo: Makefile $(GMOFILES)
+       @:
+-Makefile: Makefile.in.in $(top_builddir)/config.status POTFILES.in
++# thomas: add LINGUAS as a dependency so that the Makefile gets rebuilt
++# properly when we add languages
++Makefile: Makefile.in.in $(top_builddir)/config.status POTFILES.in LINGUAS
+       cd $(top_builddir) \
+         && CONFIG_FILES=$(subdir)/$@.in CONFIG_HEADERS= \
+              $(SHELL) ./config.status
diff --git a/common/glib-gen.mak b/common/glib-gen.mak
new file mode 100755 (executable)
index 0000000..f9027da
--- /dev/null
@@ -0,0 +1,44 @@
+# these are the variables your Makefile.am should set
+# the example is based on the colorbalance interface
+
+#glib_enum_headers=$(colorbalance_headers)
+#glib_enum_define=GST_COLOR_BALANCE
+#glib_enum_prefix=gst_color_balance
+
+enum_headers=$(foreach h,$(glib_enum_headers),\n\#include \"$(h)\")
+
+# these are all the rules generating the relevant files
+%-marshal.h: %-marshal.list
+       glib-genmarshal --header --prefix=$(glib_enum_prefix)_marshal $^ > $*-marshal.h.tmp
+       mv $*-marshal.h.tmp $*-marshal.h
+
+%-marshal.c: %-marshal.list
+       echo "#include \"$*-marshal.h\"" >> $*-marshal.c.tmp
+       glib-genmarshal --body --prefix=$(glib_enum_prefix)_marshal $^ >> $*-marshal.c.tmp
+       mv $*-marshal.c.tmp $*-marshal.c
+
+%-enumtypes.h: $(glib_enum_headers)
+       glib-mkenums \
+       --fhead "#ifndef __$(glib_enum_define)_ENUM_TYPES_H__\n#define __$(glib_enum_define)_ENUM_TYPES_H__\n\n#include <glib-object.h>\n\nG_BEGIN_DECLS\n" \
+       --fprod "\n/* enumerations from \"@filename@\" */\n" \
+       --vhead "GType @enum_name@_get_type (void);\n#define GST_TYPE_@ENUMSHORT@ (@enum_name@_get_type())\n"         \
+       --ftail "G_END_DECLS\n\n#endif /* __$(glib_enum_define)_ENUM_TYPES_H__ */" \
+       $^ > $@
+
+%-enumtypes.c: $(glib_enum_headers)
+       @if test "x$(glib_enum_headers)" == "x"; then echo "ERROR: glib_enum_headers is empty, please fix Makefile"; exit 1; fi
+       glib-mkenums \
+       --fhead "#include \"$*-enumtypes.h\"\n$(enum_headers)" \
+       --fprod "\n/* enumerations from \"@filename@\" */" \
+       --vhead "GType\n@enum_name@_get_type (void)\n{\n  static GType etype = 0;\n  if (etype == 0) {\n    static const G@Type@Value values[] = {"     \
+       --vprod "      { @VALUENAME@, \"@VALUENAME@\", \"@valuenick@\" }," \
+       --vtail "      { 0, NULL, NULL }\n    };\n    etype = g_@type@_register_static (\"@EnumName@\", values);\n  }\n  return etype;\n}\n" \
+       $^ > $@
+
+# a hack rule to make sure .Plo files exist because they get include'd
+# from Makefile's
+.deps/%-marshal.Plo:
+       touch $@
+
+.deps/%-enumtypes.Plo:
+       touch $@
diff --git a/common/gst-autogen.sh b/common/gst-autogen.sh
new file mode 100755 (executable)
index 0000000..ae60f7e
--- /dev/null
@@ -0,0 +1,294 @@
+# a silly hack that generates autoregen.sh but it's handy
+# Remove the old autoregen.sh first to create a new file,
+# as the current one may be being read by the shell executing
+# this script.
+if [ -f "autoregen.sh" ]; then
+  rm autoregen.sh
+fi
+echo "#!/bin/sh" > autoregen.sh
+echo "./autogen.sh $@ \$@" >> autoregen.sh
+chmod +x autoregen.sh
+
+# helper functions for autogen.sh
+
+debug ()
+# print out a debug message if DEBUG is a defined variable
+{
+  if test ! -z "$DEBUG"
+  then
+    echo "DEBUG: $1"
+  fi
+}
+
+version_check ()
+# check the version of a package
+# first argument : package name (executable)
+# second argument : optional path where to look for it instead
+# third argument : source download url
+# rest of arguments : major, minor, micro version
+# all consecutive ones : suggestions for binaries to use
+# (if not specified in second argument)
+{
+  PACKAGE=$1
+  PKG_PATH=$2
+  URL=$3
+  MAJOR=$4
+  MINOR=$5
+  MICRO=$6
+
+  # for backwards compatibility, we let PKG_PATH=PACKAGE when PKG_PATH null
+  if test -z "$PKG_PATH"; then PKG_PATH=$PACKAGE; fi
+  debug "major $MAJOR minor $MINOR micro $MICRO"
+  VERSION=$MAJOR
+  if test ! -z "$MINOR"; then VERSION=$VERSION.$MINOR; else MINOR=0; fi
+  if test ! -z "$MICRO"; then VERSION=$VERSION.$MICRO; else MICRO=0; fi
+
+  debug "major $MAJOR minor $MINOR micro $MICRO"
+  
+  for SUGGESTION in $PKG_PATH; do 
+    COMMAND="$SUGGESTION"
+
+    # don't check if asked not to
+    test -z "$NOCHECK" && {
+      echo -n "  checking for $COMMAND >= $VERSION ... "
+    } || {
+      # we set a var with the same name as the package, but stripped of
+      # unwanted chars
+      VAR=`echo $PACKAGE | sed 's/-//g'`
+      debug "setting $VAR"
+      eval $VAR="$COMMAND"
+      return 0
+    }
+
+    debug "checking version with $COMMAND"
+    ($COMMAND --version) < /dev/null > /dev/null 2>&1 || 
+    {
+      echo "not found."
+      continue
+    }
+    # strip everything that's not a digit, then use cut to get the first field
+    pkg_version=`$COMMAND --version|head -n 1|sed 's/^.*)[^0-9]*//'|cut -d' ' -f1`
+    debug "pkg_version $pkg_version"
+    # remove any non-digit characters from the version numbers to permit numeric
+    # comparison
+    pkg_major=`echo $pkg_version | cut -d. -f1 | sed s/[a-zA-Z\-].*//g`
+    pkg_minor=`echo $pkg_version | cut -d. -f2 | sed s/[a-zA-Z\-].*//g`
+    pkg_micro=`echo $pkg_version | cut -d. -f3 | sed s/[a-zA-Z\-].*//g`
+    test -z "$pkg_major" && pkg_major=0
+    test -z "$pkg_minor" && pkg_minor=0
+    test -z "$pkg_micro" && pkg_micro=0
+    debug "found major $pkg_major minor $pkg_minor micro $pkg_micro"
+
+    #start checking the version
+    debug "version check"
+
+    # reset check
+    WRONG=
+
+    if [ ! "$pkg_major" -gt "$MAJOR" ]; then
+      debug "major: $pkg_major <= $MAJOR"
+      if [ "$pkg_major" -lt "$MAJOR" ]; then
+        debug "major: $pkg_major < $MAJOR"
+        WRONG=1
+      elif [ ! "$pkg_minor" -gt "$MINOR" ]; then
+        debug "minor: $pkg_minor <= $MINOR"
+        if [ "$pkg_minor" -lt "$MINOR" ]; then
+          debug "minor: $pkg_minor < $MINOR"
+          WRONG=1
+        elif [ "$pkg_micro" -lt "$MICRO" ]; then
+          debug "micro: $pkg_micro < $MICRO"
+         WRONG=1
+        fi
+      fi
+    fi
+
+    if test ! -z "$WRONG"; then
+      echo "found $pkg_version, not ok !"
+      continue
+    else
+      echo "found $pkg_version, ok."
+      # we set a var with the same name as the package, but stripped of
+      # unwanted chars
+      VAR=`echo $PACKAGE | sed 's/-//g'`
+      debug "setting $VAR"
+      eval $VAR="$COMMAND"
+      return 0
+    fi
+  done
+
+  echo "not found !"
+  echo "You must have $PACKAGE installed to compile $package."
+  echo "Download the appropriate package for your distribution,"
+  echo "or get the source tarball at $URL"
+  return 1;
+}
+
+aclocal_check ()
+{
+  # normally aclocal is part of automake
+  # so we expect it to be in the same place as automake
+  # so if a different automake is supplied, we need to adapt as well
+  # so how's about replacing automake with aclocal in the set var,
+  # and saving that in $aclocal ?
+  # note, this will fail if the actual automake isn't called automake*
+  # or if part of the path before it contains it
+  if [ -z "$automake" ]; then
+    echo "Error: no automake variable set !"
+    return 1
+  else
+    aclocal=`echo $automake | sed s/automake/aclocal/`
+    debug "aclocal: $aclocal"
+    if [ "$aclocal" != "aclocal" ];
+    then
+      CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-aclocal=$aclocal"
+    fi
+    if [ ! -x `which $aclocal` ]; then
+      echo "Error: cannot execute $aclocal !"
+      return 1
+    fi
+  fi
+}
+
+autoheader_check ()
+{
+  # same here - autoheader is part of autoconf
+  # use the same voodoo
+  if [ -z "$autoconf" ]; then
+    echo "Error: no autoconf variable set !"
+    return 1
+  else
+    autoheader=`echo $autoconf | sed s/autoconf/autoheader/`
+    debug "autoheader: $autoheader"
+    if [ "$autoheader" != "autoheader" ];
+    then
+      CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-autoheader=$autoheader"
+    fi
+    if [ ! -x `which $autoheader` ]; then
+      echo "Error: cannot execute $autoheader !"
+      return 1
+    fi
+  fi
+
+}
+autoconf_2_52d_check ()
+{
+  # autoconf 2.52d has a weird issue involving a yes:no error
+  # so don't allow it's use
+  test -z "$NOCHECK" && {
+    ac_version=`$autoconf --version|head -n 1|sed 's/^[a-zA-Z\.\ ()]*//;s/ .*$//'`
+    if test "$ac_version" = "2.52d"; then
+      echo "autoconf 2.52d has an issue with our current build."
+      echo "We don't know who's to blame however.  So until we do, get a"
+      echo "regular version.  RPM's of a working version are on the gstreamer site."
+      exit 1
+    fi
+  }
+  return 0
+}
+
+die_check ()
+{
+  # call with $DIE
+  # if set to 1, we need to print something helpful then die
+  DIE=$1
+  if test "x$DIE" = "x1";
+  then
+    echo
+    echo "- Please get the right tools before proceeding."
+    echo "- Alternatively, if you're sure we're wrong, run with --nocheck."
+    exit 1
+  fi
+}
+
+autogen_options ()
+{
+  if test "x$1" = "x"; then
+    return 0
+  fi
+
+  while test "x$1" != "x" ; do
+    optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
+    case "$1" in
+      --noconfigure)
+          NOCONFIGURE=defined
+         AUTOGEN_EXT_OPT="$AUTOGEN_EXT_OPT --noconfigure"
+          echo "+ configure run disabled"
+          shift
+          ;;
+      --nocheck)
+         AUTOGEN_EXT_OPT="$AUTOGEN_EXT_OPT --nocheck"
+          NOCHECK=defined
+          echo "+ autotools version check disabled"
+          shift
+          ;;
+      --debug)
+          DEBUG=defined
+         AUTOGEN_EXT_OPT="$AUTOGEN_EXT_OPT --debug"
+          echo "+ debug output enabled"
+          shift
+          ;;
+      -h|--help)
+          echo "autogen.sh (autogen options) -- (configure options)"
+          echo "autogen.sh help options: "
+          echo " --noconfigure            don't run the configure script"
+          echo " --nocheck                don't do version checks"
+          echo " --debug                  debug the autogen process"
+          echo
+          echo " --with-autoconf PATH     use autoconf in PATH"
+          echo " --with-automake PATH     use automake in PATH"
+          echo
+          echo "Any argument either not in the above list or after a '--' will be "
+          echo "passed to ./configure."
+         exit 1
+          ;;
+      --with-automake=*)
+          AUTOMAKE=$optarg
+          echo "+ using alternate automake in $optarg"
+         CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-automake=$AUTOMAKE"
+          shift
+          ;;
+      --with-autoconf=*)
+          AUTOCONF=$optarg
+          echo "+ using alternate autoconf in $optarg"
+         CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-autoconf=$AUTOCONF"
+          shift
+          ;;
+      --) shift ; break ;;
+      *)
+          echo "+ passing argument $1 to configure"
+         CONFIGURE_EXT_OPT="$CONFIGURE_EXT_OPT $1"
+          shift
+          ;;
+    esac
+  done
+
+  for arg do CONFIGURE_EXT_OPT="$CONFIGURE_EXT_OPT $arg"; done
+  if test ! -z "$CONFIGURE_EXT_OPT"
+  then
+    echo "+ options passed to configure: $CONFIGURE_EXT_OPT"
+  fi
+}
+
+toplevel_check ()
+{
+  srcfile=$1
+  test -f $srcfile || {
+        echo "You must run this script in the top-level $package directory"
+        exit 1
+  }
+}
+
+
+tool_run ()
+{
+  tool=$1
+  options=$2
+  run_if_fail=$3
+  echo "+ running $tool $options..."
+  $tool $options || {
+    echo
+    echo $tool failed
+    eval $run_if_fail
+    exit 1
+  }
+}
diff --git a/common/gst-xmlinspect.py b/common/gst-xmlinspect.py
new file mode 100755 (executable)
index 0000000..4a1a5c7
--- /dev/null
@@ -0,0 +1,168 @@
+# -*- Mode: Python -*-
+# vi:si:et:sw=4:sts=4:ts=4
+
+"""
+examine all plugins and elements and output xml documentation for them
+used as part of the plugin documentation build
+"""
+
+import sys
+import os
+import pygst
+pygst.require('1.0')
+import gst
+
+INDENT_SIZE = 2
+
+# all templates
+
+PAD_TEMPLATE = """<caps>
+  <name>%(name)s</name>
+  <direction>%(direction)s</direction>
+  <presence>%(presence)s</presence>
+  <details>%(details)s</details>
+</caps>"""
+
+ELEMENT_TEMPLATE = """<element>
+  <name>%(name)s</name>
+  <longname>%(longname)s</longname>
+  <class>%(class)s</class>
+  <description>%(description)s</description>
+  <author>%(author)s</author>
+  <pads>
+%(pads)s
+  </pads>
+</element>"""
+
+PLUGIN_TEMPLATE = """<plugin>
+  <name>%(name)s</name>
+  <description>%(description)s</description>
+  <filename>%(filename)s</filename>
+  <basename>%(basename)s</basename>
+  <version>%(version)s</version>
+  <license>%(license)s</license>
+  <source>%(source)s</source>
+  <package>%(package)s</package>
+  <origin>%(origin)s</origin>
+  <elements>
+%(elements)s
+  </elements>
+</plugin>"""
+
+def xmlencode(line):
+    """
+    Replace &, <, and >
+    """
+    line = "&amp;".join(line.split("&"))
+    line = "&lt;".join(line.split("<"))
+    line = "&gt;".join(line.split(">"))
+    return line
+
+def get_offset(indent):
+    return " " * INDENT_SIZE * indent
+
+def output_pad_template(pt, indent=0):
+    print  "PAD TEMPLATE", pt.name_template
+    paddir = ("unknown","source","sink")
+    padpres = ("always","sometimes","request")
+    
+    d = {
+      'name':        xmlencode(pt.name_template),
+      'direction':   xmlencode(paddir[pt.direction]),
+      'presence':    xmlencode(padpres[pt.presence]),
+      'details':     xmlencode(pt.static_caps.string),
+    }
+    block = PAD_TEMPLATE % d
+
+    offset = get_offset(indent)
+    return offset + ("\n" + offset).join(block.split("\n"))
+    
+def output_element_factory(elf, indent=0):
+    print  "ELEMENT", elf.get_name()
+
+    padsoutput = []
+    padtemplates = elf.get_static_pad_templates()
+    for padtemplate in padtemplates:
+        padsoutput.append(output_pad_template(padtemplate, indent))
+
+    d = {
+        'name':        xmlencode(elf.get_name()),
+        'longname':    xmlencode(elf.get_longname()),
+        'class':       xmlencode(elf.get_klass()),
+        'description': xmlencode(elf.get_description()),
+        'author':      xmlencode(elf.get_author()),
+        'pads': "\n".join(padsoutput),
+    }
+    block = ELEMENT_TEMPLATE % d
+
+    offset = get_offset(indent)
+    return offset + ("\n" + offset).join(block.split("\n"))
+
+def output_plugin(plugin, indent=0):
+    print "PLUGIN", plugin.get_name()
+    version = plugin.get_version()
+    
+    elements = {}
+    gst.debug('getting features for plugin %s' % plugin.get_name())
+    registry = gst.registry_get_default()
+    features = registry.get_feature_list_by_plugin(plugin.get_name())
+    gst.debug('plugin %s has %d features' % (plugin.get_name(), len(features)))
+    for feature in features:
+        if isinstance(feature, gst.ElementFactory):
+            elements[feature.get_name()] = feature
+    #gst.debug("got features")
+        
+    elementsoutput = []
+    keys = elements.keys()
+    keys.sort()
+    for name in keys:
+        feature = elements[name]
+        elementsoutput.append(output_element_factory(feature, indent + 2))
+
+    filename = plugin.get_filename()
+    basename = filename
+    if basename:
+        basename = os.path.basename(basename)
+    d = {
+        'name':        xmlencode(plugin.get_name()),
+        'description': xmlencode(plugin.get_description()),
+        'filename':    filename,
+        'basename':    basename,
+        'version':     version,
+        'license':     xmlencode(plugin.get_license()),
+        'source':      xmlencode(plugin.get_source()),
+        'package':     xmlencode(plugin.get_package()),
+        'origin':      xmlencode(plugin.get_origin()),
+        'elements': "\n".join(elementsoutput),
+    }
+    block = PLUGIN_TEMPLATE % d
+    
+    offset = get_offset(indent)
+    return offset + ("\n" + offset).join(block.split("\n"))
+
+def main():
+    if len(sys.argv) == 1:
+        sys.stderr.write("Please specify a source module to inspect")
+        sys.exit(1)
+    source = sys.argv[1]
+
+    if len(sys.argv) > 2:
+        os.chdir(sys.argv[2])
+
+    registry = gst.registry_get_default()
+    all = registry.get_plugin_list()
+    for plugin in all:
+        gst.debug("inspecting plugin %s from source %s" % (
+            plugin.get_name(), plugin.get_source()))
+        # this skips gstcoreelements, with bin and pipeline
+        if plugin.get_filename() is None:
+            continue
+        if plugin.get_source() != source:
+            continue
+
+        filename = "plugin-%s.xml" % plugin.get_name()
+        handle = open(filename, "w")
+        handle.write(output_plugin(plugin))
+        handle.close()
+
+main()
diff --git a/common/gst.supp b/common/gst.supp
new file mode 100755 (executable)
index 0000000..9b2a3a2
--- /dev/null
@@ -0,0 +1,1988 @@
+### this file contains suppressions for valgrind when running
+### the gstreamer unit tests
+### it might be useful for wider use as well
+
+### syscall suppressions
+
+{
+   <clone on Wim's Debian>
+   Memcheck:Param
+   clone(parent_tidptr)
+   fun:clone
+   fun:clone
+}
+
+{
+   <clone on Wim's Debian>
+   Memcheck:Param
+   clone(child_tidptr)
+   fun:clone
+   fun:clone
+}
+
+{
+   <clone on Wim's Debian>
+   Memcheck:Param
+   clone(tlsinfo)
+   fun:clone
+   fun:clone
+}
+
+### glibc suppressions
+
+{
+   <conditional jump on wim's debian 2/2/06>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+   fun:gst_plugin_load_file
+}
+
+# glibc does not deallocate thread-local storage
+
+{
+   <tls>
+   Memcheck:Leak
+   fun:calloc
+   fun:_dl_allocate_tls
+   fun:pthread_create@@*
+}
+
+# I get an extra stack entry on x86/dapper
+{
+   <tls>
+   Memcheck:Leak
+   fun:calloc
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_allocate_tls
+   fun:pthread_create@@*
+}
+
+
+{
+   <pthread strstr>
+   Memcheck:Cond
+   fun:strstr
+   fun:__pthread_initialize_minimal
+   obj:/lib/libpthread-*.so
+   obj:/lib/libpthread-*.so
+   fun:call_init
+   fun:_dl_init
+   obj:/lib/ld-*.so
+}
+
+# a thread-related free problem in glibc from Edgard
+{
+   __libc_freeres_rw_acess
+   Memcheck:Addr4
+   obj:*
+   obj:*
+   obj:*
+   obj:*
+   obj:*
+   fun:__libc_freeres
+}
+
+{
+   <a conditional jump on wim's debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+}
+
+# g_module_open-related problems
+{
+   <started showing up on fc4-quick>
+   Memcheck:Addr2
+   fun:memcpy
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+   fun:gst_plugin_load_file
+   fun:gst_registry_scan_path_level
+   fun:gst_registry_scan_path_level
+   fun:gst_registry_scan_path_level
+   fun:init_post
+   fun:g_option_context_parse
+   fun:gst_init_check
+   fun:gst_init
+   fun:gst_check_init
+   fun:main
+}
+
+{
+   <started showing up on fc4-quick>
+   Memcheck:Addr4
+   fun:memcpy
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+   fun:gst_plugin_load_file
+   fun:gst_registry_scan_path_level
+   fun:gst_registry_scan_path_level
+   fun:gst_registry_scan_path_level
+   fun:init_post
+   fun:g_option_context_parse
+   fun:gst_init_check
+   fun:gst_init
+   fun:gst_check_init
+   fun:main
+}
+
+{
+   <g_module_open on wim's debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:do_sym
+   fun:_dl_sym
+   fun:dlsym_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlsym
+   fun:g_module_symbol
+   fun:g_module_open
+   fun:gst_plugin_load_file
+}
+
+{
+   <g_module_open on wim's debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+   fun:gst_plugin_load_file
+}
+{
+   <g_module_open on wim's debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+   fun:gst_plugin_load_file
+   fun:gst_plugin_load_by_name
+   fun:gst_plugin_feature_load
+}
+
+{
+   <leak on wim's debian in g_module_open>
+   Memcheck:Leak
+   fun:malloc
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+   fun:gst_plugin_load_file
+   fun:gst_plugin_load_by_name
+}
+
+{
+   <invalid read on wim's debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+}
+
+{
+   <invalid read on wim's debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+}
+
+{
+   <invalid read on wim's debian - 2006-02-02>
+   Memcheck:Addr4
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+
+{
+   <invalid read on wim's debian - 2006-02-02>
+   Memcheck:Addr4
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:dl_open_worker
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   fun:dlopen_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+
+{
+   <invalid read on wim's debian - 2006-02-02>
+   Memcheck:Addr4
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:do_sym
+   fun:_dl_sym
+   fun:dlsym_doit
+   obj:/lib/ld-2.3.*.so
+   fun:_dlerror_run
+   fun:dlsym
+   fun:g_module_symbol
+   fun:g_module_open
+}
+
+{
+   <futex on Andy's 64-bit ubuntu>
+   Memcheck:Param
+   futex(uaddr2)
+   fun:pthread_once
+   obj:/lib/libc-2.3.*.so
+   obj:/lib/libc-2.3.*.so
+   fun:mbsnrtowcs
+   fun:vfprintf
+   fun:vsprintf
+   fun:sprintf
+   obj:/lib/libc-2.3.*.so
+   fun:tmpfile
+   fun:setup_pipe
+   fun:setup_messaging_with_key
+   fun:setup_messaging
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+   fun:g_module_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   fun:_dl_sym
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlsym
+   fun:g_module_symbol
+   fun:g_module_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+   fun:g_module_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+   fun:g_module_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+   fun:g_module_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/ld-2.7.so
+   fun:__libc_dlopen_mode
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/ld-2.7.so
+   fun:__libc_dlopen_mode
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/ld-2.7.so
+   fun:__libc_dlopen_mode
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   fun:iconv_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/ld-2.7.so
+   fun:__libc_dlopen_mode
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   obj:/lib/i686/cmov/libc-2.7.so
+   fun:iconv_open
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Cond
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+{
+   <suppression for glibc 2.7 on debian>
+   Memcheck:Addr4
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   obj:/lib/ld-2.7.so
+   obj:/lib/i686/cmov/libdl-2.7.so
+   fun:dlopen
+}
+
+# suppression for a glibc bug:
+# http://valgrind.org/docs/manual/faq.html#faq.exit_errors>
+{
+   <Workaround for a glibc bug> 
+   Memcheck:Free
+   fun:free
+   obj:*libc-*.so
+   fun:__libc_freeres
+   fun:*
+   fun:_Exit
+}
+
+# valgrind doesn't allow me to specify a suppression for Addr1, Addr2, Addr4
+# as Addr*, so 3 copies for that; and then 2 of each for that pesky memcpy
+{
+   <Invalid read of size 1, 2, 4 on thomas's FC4>
+   Memcheck:Addr1
+   fun:_dl_signal_error
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+
+{
+   <Invalid read of size 1, 2, 4 on thomas's FC4>
+   Memcheck:Addr2
+   fun:_dl_signal_error
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+{
+   <Invalid read of size 1, 2, 4 on thomas's FC4>
+   Memcheck:Addr4
+   fun:_dl_signal_error
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+
+{
+   <Invalid read of size 1, 2, 4 on thomas's FC4>
+   Memcheck:Addr1
+   fun:memcpy
+   fun:_dl_signal_error
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+
+{
+   <Invalid read of size 1, 2, 4 on thomas's FC4>
+   Memcheck:Addr2
+   fun:memcpy
+   fun:_dl_signal_error
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+{
+   <Invalid read of size 1, 2, 4 on thomas's FC4>
+   Memcheck:Addr4
+   fun:memcpy
+   fun:_dl_signal_error
+   fun:_dl_map_object_deps
+   fun:dl_open_worker
+   fun:_dl_catch_error
+   fun:_dl_open
+   fun:dlopen_doit
+   fun:_dl_catch_error
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+   fun:g_module_open
+}
+
+{
+   <Addr8 on Andy's AMD64 ubuntu in dl_open>
+   Memcheck:Addr8
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/libc-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   obj:/lib/libdl-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+}
+
+{
+   <Conditional jump on Andy's AMD64 ubuntu>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/libc-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   fun:_dl_open
+   obj:/lib/libdl-2.3.*.so
+   obj:/lib/ld-2.3.*.so
+   obj:/lib/libdl-2.3.*.so
+   fun:dlopen
+   fun:g_module_open
+   fun:gst_plugin_load_file
+   fun:gst_plugin_load_by_name
+   fun:gst_plugin_feature_load
+}
+
+{
+   <Mike's x86 dapper>
+   Memcheck:Addr4
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/tls/i686/cmov/libc-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   fun:_dl_open
+   obj:/lib/tls/i686/cmov/libdl-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/tls/i686/cmov/libdl-2.3.6.so
+   fun:dlopen
+}
+
+{
+   <Mike's x86 dapper>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/tls/i686/cmov/libc-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   fun:_dl_open
+   obj:/lib/tls/i686/cmov/libdl-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/tls/i686/cmov/libdl-2.3.6.so
+   fun:dlopen
+}
+
+{
+   <Another dapper one>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/tls/i686/cmov/libc-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   fun:_dl_open
+   obj:/lib/tls/i686/cmov/libdl-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/tls/i686/cmov/libdl-2.3.6.so
+   fun:dlopen
+}
+
+### glib suppressions
+{
+   <g_parse_debug_string>
+   Memcheck:Cond
+   fun:g_parse_debug_string
+   obj:/usr/lib*/libglib-2.0.so.*
+   fun:g_slice_alloc
+   fun:g_slice_alloc0
+}
+
+{
+   <g_type_init malloc>
+   Memcheck:Leak
+   fun:malloc
+   fun:g_malloc
+   fun:g_strdup
+   fun:g_quark_from_string
+   obj:*
+   obj:*
+   fun:g_type_register_fundamental
+   obj:*
+   fun:g_type_init_with_debug_flags
+   fun:g_type_init
+   fun:init_pre
+}
+
+{
+   <g_type_init calloc>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   obj:*
+   obj:*
+   fun:g_type_register_fundamental
+}
+
+{
+   <g_type_init calloc 2>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   obj:*
+   obj:*
+   fun:g_type_init_with_debug_flags
+}
+
+{
+   <g_type_init calloc 3, GSlice version>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:g_slice_alloc
+   obj:*
+   obj:*
+   fun:g_type_init_with_debug_flags
+}
+
+#pthread memleaks
+
+{
+   Thread creation leak
+   Memcheck:Leak
+   fun:calloc
+   fun:allocate_dtv
+   fun:_dl_allocate*
+   fun:_dl_allocate*
+   fun:__pthread_initialize_minimal
+}
+
+{
+   Thread management leak
+   Memcheck:Leak
+   fun:calloc
+   fun:allocate_dtv
+   fun:_dl_allocate*
+   fun:_dl_allocate*
+   fun:__pthread_*
+}
+
+{
+   Thread management leak 2
+   Memcheck:Leak
+   fun:memalign
+   fun:_dl_allocate*
+   fun:_dl_allocate*
+   fun:__pthread_*
+}
+
+{
+   pthread_create Syscall param write(buf) points to uninitialised byte(s)
+   Memcheck:Param
+   write(buf)
+   fun:pthread_create@@GLIBC_2.2.5
+   fun:g_thread_create*
+
+}
+
+# nss_parse_* memleak (used by g_option_context_parse)
+{
+   nss_parse_* memleak
+   Memcheck:Leak
+   fun:malloc
+   fun:nss_parse_service_list
+   fun:__nss_database_lookup
+}
+
+# liboil suppressions
+{
+   <liboil cpu_fault_check_try>
+   Memcheck:Value8
+   obj:/usr/lib/liboil-0.3.so.0.1.0
+   obj:/usr/lib/liboil-0.3.so.0.1.0
+   obj:/usr/lib/liboil-0.3.so.0.1.0
+   fun:oil_cpu_fault_check_try
+   fun:oil_test_check_impl
+   fun:oil_class_optimize
+   fun:oil_optimize_all
+   fun:oil_init
+}
+
+{
+   <annoying read error inside dlopen stuff on Ubuntu Dapper x86_64>
+   Memcheck:Addr8
+   obj:/lib/ld-2.3.6.so
+}
+
+{
+   <Ubuntu Dapper x86_64>
+   Memcheck:Param
+   futex(uaddr2)
+   fun:pthread_once
+   obj:/lib/libc-2.3.6.so
+   obj:/lib/libc-2.3.6.so
+   fun:setlocale
+   fun:init_pre
+   fun:g_option_context_parse
+   fun:gst_init_check
+   fun:gst_init
+   fun:gst_check_init
+   fun:main
+}
+
+{
+   <Ubuntu Dapper x86_64 dlopen stuff again>
+   Memcheck:Cond
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   fun:_dl_open
+   obj:/lib/libdl-2.3.6.so
+   obj:/lib/ld-2.3.6.so
+   obj:/lib/libdl-2.3.6.so
+   fun:dlopen
+   fun:g_module_open
+   fun:gst_plugin_load_file
+}
+# this exists in a bunch of different variations, hence the short tail/trace
+{
+   <dlopen invalid read of size 4 suppression on tpm's Ubuntu edgy/x86>
+   Memcheck:Addr4
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+}
+{
+   <and the same for 64bit systems>
+   Memcheck:Addr8
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+}
+
+# More edgy suppressions (Mike)
+{  
+   <dlopen Condition jump suppressions for Ubuntu Edgy/x86>
+   Memcheck:Cond
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   fun:dlopen_doit
+   obj:/lib/ld-2.4.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+}
+
+{  
+   <dlopen Condition jump suppressions for Ubuntu Edgy/x86>
+   Memcheck:Cond
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   fun:dlopen_doit
+   obj:/lib/ld-2.4.so
+   fun:_dlerror_run
+   fun:dlopen@@GLIBC_2.1
+}
+
+{  
+   <dlopen Condition jump suppressions for Ubuntu Edgy/x86>
+   Memcheck:Cond
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   fun:do_sym
+   fun:_dl_sym
+}
+
+# This one's overly general, but there's zero other information in the stack
+# trace - just these five lines!
+{  
+   <dlopen Condition jump suppressions for Ubuntu Edgy/x86>
+   Memcheck:Cond
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+   obj:/lib/ld-2.4.so
+}
+
+{
+   <tls leaks on Edgy/x86>
+   Memcheck:Leak
+   fun:calloc
+   obj:/lib/ld-2.4.so
+   fun:_dl_allocate_tls
+   fun:pthread_create@@GLIBC_2.1
+}
+
+# TLS leaks for feisty/x86
+{
+   <tls leaks on Feisty/x86>
+   Memcheck:Leak
+   fun:calloc
+   fun:allocate_dtv
+   fun:_dl_allocate_tls
+   fun:pthread_create@@GLIBC_2.1
+}
+
+{
+   <libcdio 0.76 leak>
+   Memcheck:Leak
+   fun:calloc
+   obj:/usr/lib/libcdio.so.6.0.1
+   fun:cdio_open_am_linux
+   obj:/usr/lib/libcdio.so.6.0.1
+   fun:cdio_open_am
+}
+
+{
+   <Addr8 on Jan's AMD64 ubuntu Feisty in dl_open>
+   Memcheck:Addr8
+   obj:/lib/ld-2.5.so
+}
+
+{
+   <First of many Alsa errors>
+   Memcheck:Cond
+   fun:snd_pcm_direct_shm_create_or_connect
+   fun:snd_pcm_dsnoop_open
+   fun:_snd_pcm_dsnoop_open
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_plug_open
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_asym_open
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+}
+
+{
+   <alsa error>
+   Memcheck:Cond
+   fun:snd_pcm_hw_param_set_near
+   fun:set_hwparams
+}
+
+{
+   <alsa error>
+   Memcheck:Cond
+   fun:_snd_pcm_hw_param_set_min
+   fun:snd_pcm_hw_param_set_min
+   fun:snd_pcm_hw_param_set_near
+   fun:set_hwparams
+}
+
+{
+   <alsa error>
+   Memcheck:Cond
+   fun:_snd_pcm_hw_param_set_min
+   fun:snd_pcm_hw_param_set_min
+   fun:snd_pcm_hw_param_set_near
+   fun:set_hwparams
+}
+
+{
+   <alsa error>
+   Memcheck:Cond
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_hw_param_set_near
+   fun:set_hwparams
+}
+{
+   <alsa error>
+   Memcheck:Cond
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_close
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error>
+   Memcheck:Cond
+   fun:snd_pcm_direct_shm_create_or_connect
+   fun:snd_pcm_dmix_open
+   fun:_snd_pcm_dmix_open
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_softvol_open
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_plug_open
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_asym_open
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:malloc
+   fun:strdup
+   fun:snd_dlobj_cache_add
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:snd_pcm_dsnoop_open
+   fun:_snd_pcm_dsnoop_open
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_plug_open
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_pcm_open_slave
+   fun:_snd_pcm_asym_open
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+}
+# Catch about 15 variations on inserting info into an ALSA
+# internal cache
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:malloc
+   fun:snd_dlobj_cache_add
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <this catches a bunch of very similar errors related to parsing the configs>
+   Memcheck:Leak
+   fun:malloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+}
+{
+   <alsa error - same as above with 6 libasound>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+}
+{
+   <alsa error - same as above with 7 libasound>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+}
+{
+   <alsa error - same as above with 10 libasound>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+}
+{
+   <alsa error - same as above with 11 libasound>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:malloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   fun:snd_config_hook_load_for_all_cards
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+}
+{
+   <alsa error - same as above, but using calloc>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   fun:snd_config_hook_load_for_all_cards
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+}
+{
+   <alsa error - same as above, but with only 9 libasounds>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 7 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 6 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 6 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 7 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 8 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 9 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 10 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error - same as above, with 11 libasound repeats>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_update_r
+   fun:snd_config_update
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   fun:snd_config_hook_load_for_all_cards
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error - same as above, but with 8 libasound in the stack>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   fun:snd_config_hook_load_for_all_cards
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error - same as above, but with 7 libasound in the stack>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   fun:snd_config_hook_load_for_all_cards
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <alsa error - same as above, but with 6 libasound in the stack>
+   Memcheck:Leak
+   fun:calloc
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_hook_load
+   fun:snd_config_hook_load_for_all_cards
+   obj:/*lib/libasound.so.2.0.0
+   fun:snd_config_searcha_hooks
+   fun:snd_config_search_alias_hooks
+   fun:snd_config_search_definition
+   obj:/*lib/libasound.so.2.0.0
+}
+{
+   <nss lookup within ALSA>
+   Memcheck:Leak
+   fun:malloc
+   obj:/lib/libc*.so
+   fun:__nss_database_lookup
+   obj:*
+   obj:*
+   fun:getgrnam_r
+   fun:getgrnam
+   fun:snd_pcm_direct_parse_open_conf
+}
+
+{
+   <libxcb leak on Ubuntu Feisty>
+   Memcheck:Leak
+   fun:calloc
+   fun:_XCBInitDisplayLock
+   fun:XOpenDisplay
+}
+
+# GConf internal initialisations related to getting the default client.
+{
+   <Orbit something or other>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_tcval
+   obj:/usr/lib/libORBit-2.so.*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:CORBA_ORB_string_to_object
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_get_current_lock_holder
+   fun:gconf_activate_server
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf internal leak>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_tcval
+   obj:/usr/lib/libORBit-2.so.*
+   fun:PortableServer_POA_servant_to_reference
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf internal leak>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_tcval
+   obj:/usr/lib/libORBit-2.so.*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:CORBA_ORB_string_to_object
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_get_current_lock_holder
+   fun:gconf_activate_server
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}  
+{
+   <gconf internal initialisation>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   obj:/usr/lib/libORBit-2.so.*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:ORBit_demarshal_value
+   obj:/usr/lib/libORBit-2.so.*
+   fun:ORBit_small_invoke_stub
+   fun:ConfigServer_get_default_database
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf internal init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   obj:/usr/lib/libORBit-2.so.*
+   fun:IOP_generate_profiles
+   fun:ORBit_marshal_object
+   fun:ORBit_marshal_value
+   obj:/usr/lib/libORBit-2.so.*
+   fun:ORBit_small_invoke_stub
+   fun:ConfigServer_add_client
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf internal init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_by_tc
+   obj:/usr/lib/libORBit-2.so.*
+   fun:PortableServer_POA_servant_to_reference
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf internal init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_by_tc
+   obj:/usr/lib/libORBit-2.so.*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:CORBA_ORB_string_to_object
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_get_current_lock_holder
+   fun:gconf_activate_server
+   obj:/usr/lib/libgconf-2.so.*
+   obj:/usr/lib/libgconf-2.so.*
+   fun:gconf_engine_get_default
+}
+
+# Some libORBit/bonobo initialisation stuff
+{
+   <bonobo init>
+   Memcheck:Leak
+   fun:malloc
+   fun:g_malloc
+   fun:ORBit_alloc_string
+   fun:CORBA_string_dup
+   fun:Bonobo_ActivationEnvValue_set
+   fun:bonobo_activation_init_activation_env
+   fun:bonobo_activation_orb_init
+   fun:bonobo_activation_init
+}
+{
+   <bonobo init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_alloc*
+   obj:/usr/lib/libORBit-2.so*
+   fun:PortableServer_POA_servant_to_reference
+   obj:/usr/lib/libbonobo-2.so*
+}
+{
+   <bonobo init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_tcval
+   fun:ORBit_small_allocbuf
+   fun:ORBit_adaptor_setup
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_POA_setup_root
+   fun:ORBit_init_internals
+   fun:CORBA_ORB_init
+}
+{
+   <bonobo init - more recent variant of above>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc_tcval
+   fun:ORBit_adaptor_setup
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_POA_setup_root
+   fun:ORBit_init_internals
+   fun:CORBA_ORB_init
+}
+{
+   <bonobo init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_allocbuf
+   fun:bonobo_activation_init_activation_env
+   fun:bonobo_activation_orb_init
+   fun:bonobo_activation_init
+}
+
+# More GConf stuff from the FC5 buildbot, mostly variations on the 
+# above stack traces
+{
+   <incompletely initialised ORBit buffer>
+   Memcheck:Param
+   writev(vector[...])
+   fun:writev
+   obj:/usr/lib/libORBit-2.so*
+   fun:link_connection_writev
+   fun:giop_send_buffer_write
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_small_invoke_stub
+   fun:ORBit_small_invoke_stub_n
+   fun:ORBit_c_stub_invoke
+   fun:ConfigServer_ping
+   fun:gconf_activate_server
+   obj:/usr/lib/libgconf-2.so*
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_alloc*
+   obj:/usr/lib/libORBit-2.so*
+   fun:PortableServer_POA_servant_to_reference
+   obj:/usr/lib/libgconf-2.so*
+   obj:/usr/lib/libgconf-2.so*
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_alloc
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:CORBA_ORB_string_to_object
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_get_current_lock_holder
+   fun:gconf_activate_server
+   obj:/usr/lib/libgconf-2.so*
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_alloc*
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:CORBA_ORB_string_to_object
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_get_current_lock_holder
+   fun:gconf_activate_server
+   obj:/usr/lib/libgconf-2.so*
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_engine_get_default
+}
+{
+   <bonobo init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_alloc*
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_demarshal_IOR
+   fun:ORBit_demarshal_object
+   fun:ORBit_demarshal_value
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_small_invoke_stub
+   fun:ORBit_small_invoke_stub_n
+   fun:ORBit_c_stub_invoke
+   fun:ConfigServer_get_default_database
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_engine_get_default
+}
+{
+   <gconf init>
+   Memcheck:Leak
+   fun:calloc
+   fun:g_malloc0
+   fun:ORBit_alloc*
+   fun:ORBit_small_alloc*
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_OAObject_object_to_objkey
+   fun:IOP_generate_profiles
+   fun:ORBit_marshal_object
+   fun:ORBit_marshal_value
+   obj:/usr/lib/libORBit-2.so*
+   fun:ORBit_small_invoke_stub
+   fun:ORBit_small_invoke_stub_n
+   fun:ORBit_c_stub_invoke
+   fun:ConfigServer_add_client
+   obj:/usr/lib/libgconf-2.so*
+   obj:/usr/lib/libgconf-2.so*
+   fun:gconf_engine_get_default
+}
+{
+   <GLib caching the home dir>
+   Memcheck:Leak
+   fun:malloc
+   obj:*libc-*.so
+   fun:__nss_database_lookup
+   obj:*
+   obj:*
+   fun:getpwnam_r
+   obj:/usr/lib*/libglib-2.0.so.*
+   fun:g_get_home_dir
+}
+{
+   <GLib caching the user name>
+   Memcheck:Leak
+   fun:malloc
+   obj:*libc-*.so
+   fun:__nss_database_lookup
+   obj:*
+   obj:*
+   fun:getpwnam_r
+   obj:/usr/lib*/libglib-2.0.so.*
+   fun:g_get_user_name
+}
+{
+   <GLib caching the tmp dir>
+   Memcheck:Leak
+   fun:malloc
+   obj:*libc-*.so
+   fun:__nss_database_lookup
+   obj:*
+   obj:*
+   fun:getpwnam_r
+   obj:/usr/lib*/libglib-2.0.so.*
+   fun:g_get_tmp_dir
+}
+
+{
+   <GLib caching the host name>
+   Memcheck:Leak
+   fun:malloc
+   obj:*libc-*.so
+   fun:__nss_database_lookup
+   obj:*
+   obj:*
+   fun:getpwnam_r
+   obj:/usr/lib*/libglib-2.0.so.0.*
+   fun:g_get_host_name
+}
+
+
+## Some Fontconfig errors.
+{
+   <First time load of a font - feisty x86_64>
+   Memcheck:Leak
+   fun:malloc
+   fun:FcPatternObjectInsertElt
+   fun:FcPatternObjectAddWithBinding
+   fun:FcPatternAppend
+   fun:FcEndElement
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   fun:XML_ParseBuffer
+   fun:FcConfigParseAndLoad
+   fun:FcConfigParseAndLoad
+   fun:FcParseInclude
+   fun:FcEndElement
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   fun:XML_ParseBuffer
+   fun:FcConfigParseAndLoad
+}
+{
+   <First time load of a font - feisty x86_64>
+   Memcheck:Leak
+   fun:malloc
+   fun:FcStrCopy
+   fun:FcEndElement
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   fun:XML_ParseBuffer
+   fun:FcConfigParseAndLoad
+   fun:FcConfigParseAndLoad
+   fun:FcParseInclude
+   fun:FcEndElement
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   obj:/usr/lib/libexpat.so.1.0.0
+   fun:XML_ParseBuffer
+   fun:FcConfigParseAndLoad
+   fun:FcInitLoadConfig
+   fun:FcInitLoadConfigAndFonts
+}
+
diff --git a/common/gstdoc-scangobj b/common/gstdoc-scangobj
new file mode 100755 (executable)
index 0000000..90ba889
--- /dev/null
@@ -0,0 +1,1607 @@
+#!/usr/bin/perl -w
+# -*- cperl -*-
+#
+# gtk-doc - GTK DocBook documentation generator.
+# Copyright (C) 1998  Damon Chaplin
+#
+# 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 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+
+#
+# This gets information about object heirarchies and signals
+# by compiling a small C program. CFLAGS and LDFLAGS must be
+# set appropriately before running this script.
+#
+# NOTE: the lookup_signal_arg_names() function contains the argument names of
+#       standard GTK signal handlers. This may need to be updated for new
+#       GTK signals or Gnome widget signals.
+
+use Getopt::Long;
+
+unshift @INC, '/usr/share/gtk-doc/data';
+require "gtkdoc-common.pl";
+
+# Options
+
+# name of documentation module
+my $MODULE;
+my $OUTPUT_DIR;
+my $PRINT_VERSION;
+my $PRINT_HELP;
+my $TYPE_INIT_FUNC="g_type_init ()";
+
+# --nogtkinit is deprecated, as it is the default now anyway.
+%optctl = (module => \$MODULE,
+           source => \$SOURCE,
+          types => \$TYPES_FILE,
+          nogtkinit => \$NO_GTK_INIT,
+          'type-init-func' => \$TYPE_INIT_FUNC,
+          'output-dir' => \$OUTPUT_DIR,
+          'version' => \$PRINT_VERSION,
+          'help' => \$PRINT_HELP);
+          
+GetOptions(\%optctl, "module=s", "source=s", "types:s", "output-dir:s", "nogtkinit", "type-init-func:s", "version", "help");
+
+if ($NO_GTK_INIT) {
+  # Do nothing. This just avoids a warning.
+}
+
+if ($PRINT_VERSION) {
+    print "1.5\n";
+    exit 0;
+}
+
+if (!$MODULE) {
+    $PRINT_HELP = 1;
+}
+
+if ($PRINT_HELP) {
+    print "gstdoc-scangobj version 1.5\n";
+    print "\n--module=MODULE_NAME  Name of the doc module being parsed";
+    print "\n--source=SOURCE_NAME  Name of the source module for plugins";
+    print "\n--types=FILE          The name of the file to store the types in";
+    print "\n--type-init-func=FUNC The init function to call instead of g_type_init ()";
+    print "\n--output-dir=DIRNAME  The directory where the results are stored";
+    print "\n--version             Print the version of this program";
+    print "\n--help                Print this help\n";
+    exit 0;
+}
+
+$OUTPUT_DIR = $OUTPUT_DIR ? $OUTPUT_DIR : ".";
+
+# THOMAS: dynamic types; only use types file for headers
+ $TYPES_FILE = $TYPES_FILE ? $TYPES_FILE : "$OUTPUT_DIR/$MODULE.types";
+
+open (TYPES, $TYPES_FILE) || die "Cannot open $TYPES_FILE: $!\n";
+open (OUTPUT, ">$MODULE-scan.c") || die "Cannot open $MODULE-scan.c: $!\n";
+
+my $old_signals_filename = "$OUTPUT_DIR/$MODULE.signals";
+my $new_signals_filename = "$OUTPUT_DIR/$MODULE.signals.new";
+my $old_hierarchy_filename = "$OUTPUT_DIR/$MODULE.hierarchy";
+my $new_hierarchy_filename = "$OUTPUT_DIR/$MODULE.hierarchy.new";
+my $old_interfaces_filename = "$OUTPUT_DIR/$MODULE.interfaces";
+my $new_interfaces_filename = "$OUTPUT_DIR/$MODULE.interfaces.new";
+my $old_prerequisites_filename = "$OUTPUT_DIR/$MODULE.prerequisites";
+my $new_prerequisites_filename = "$OUTPUT_DIR/$MODULE.prerequisites.new";
+my $old_args_filename = "$OUTPUT_DIR/$MODULE.args";
+my $new_args_filename = "$OUTPUT_DIR/$MODULE.args.new";
+
+# write a C program to scan the types
+
+$includes = "";
+#@types = ();
+
+for (<TYPES>) {
+    if (/^#include/) {
+       $includes .= $_;
+#    } elsif (/^%/) {
+#      next;
+#    } elsif (/^\s*$/) {
+#      next;
+#    } else {
+#      chomp;
+#      push @types, $_;
+    }
+}
+
+#$ntypes = @types + 1;
+
+print OUTPUT <<EOT;
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+
+$includes
+#ifdef GTK_IS_WIDGET_CLASS
+#include <gtk/gtkversion.h>
+#endif
+GType *object_types = NULL;
+
+static GType *
+get_object_types (void)
+{
+    GList *plugins = NULL;
+    GList *factories = NULL;
+    GList *l;
+    GstElementFactory *factory = NULL;
+
+    gint i = 0;
+
+    /* get a list of features from plugins in our source module */
+    plugins = gst_registry_get_plugin_list (gst_registry_get_default());
+
+    while (plugins) {
+      GList *features;
+      GstPlugin *plugin;
+      const gchar *source;
+
+      plugin = (GstPlugin *) (plugins->data);
+      plugins = g_list_next (plugins);
+      source = gst_plugin_get_source (plugin);
+      /*g_print ("plugin: %s source: %s\\n", plugin->desc.name, source);*/
+      if (!source || strcmp (source, "$SOURCE") != 0) {
+        continue;
+      }
+      g_print ("plugin: %s source: %s\\n", plugin->desc.name, source);
+
+      features =
+          gst_registry_get_feature_list_by_plugin (gst_registry_get_default (),
+          plugin->desc.name);
+      while (features) {
+        GstPluginFeature *feature;
+        feature = GST_PLUGIN_FEATURE (features->data);
+        feature = gst_plugin_feature_load (feature);
+        if (!feature) {
+          g_warning ("Could not load plugin feature %s",
+                     gst_plugin_feature_get_name (feature));
+        }
+
+        if (GST_IS_ELEMENT_FACTORY (feature)) {
+          factory = GST_ELEMENT_FACTORY (feature);
+          factories = g_list_prepend (factories, factory);
+        }
+        features = g_list_next (features);
+      }
+    }
+
+    g_message ("number of element factories: %d", g_list_length (factories));
+
+    /* allocate the object_types array to hold them */
+    object_types = g_new0 (GType, g_list_length (factories)+1);
+
+    l = factories;
+    i = 0;
+
+    /* fill it */
+    while (l) {
+      GType type;
+      factory = GST_ELEMENT_FACTORY (l->data);
+      type = gst_element_factory_get_element_type (factory);
+      g_message ("adding type %p for factory %s", (void *) type, gst_element_factory_get_longname (factory));
+      object_types[i] = type;
+      i++;
+      l = g_list_next (l);
+    }
+    object_types[i] = 0;
+EOT
+
+print OUTPUT <<EOT;
+
+    /* Need to make sure all the types are loaded in and initialize
+     * their signals and properties.
+     */
+    for (i=0; object_types[i]; i++) {
+      if (G_TYPE_IS_CLASSED (object_types[i]))
+        g_type_class_ref (object_types[i]);
+        else {
+          g_warning ("not reffing type: %s", g_type_name (object_types[i]));
+        }
+    }
+
+    return object_types;
+}
+
+/*
+ * This uses GObject type functions to output signal prototypes and the object
+ * hierarchy.
+ */
+
+/* The output files */
+const gchar *signals_filename = "$new_signals_filename";
+const gchar *hierarchy_filename = "$new_hierarchy_filename";
+const gchar *interfaces_filename = "$new_interfaces_filename";
+const gchar *prerequisites_filename = "$new_prerequisites_filename";
+const gchar *args_filename = "$new_args_filename";
+
+
+static void output_signals (void);
+static void output_object_signals (FILE *fp,
+                                  GType object_type);
+static void output_object_signal (FILE *fp,
+                                 const gchar *object_class_name,
+                                 guint signal_id);
+static const gchar * get_type_name (GType type,
+                                   gboolean * is_pointer);
+static const gchar * get_gdk_event (const gchar * signal_name);
+static const gchar ** lookup_signal_arg_names (const gchar * type,
+                                              const gchar * signal_name);
+
+static void output_object_hierarchy (void);
+static void output_hierarchy (FILE *fp,
+                             GType type,
+                             guint level);
+
+static void output_object_interfaces (void);
+static void output_interfaces (FILE *fp,
+                              GType type);
+
+static void output_interface_prerequisites (void);
+static void output_prerequisites (FILE *fp,
+                                 GType type);
+
+static void output_args (void);
+static void output_object_args (FILE *fp, GType object_type);
+
+int
+main (int argc, char *argv[])
+{
+  /* Silence the compiler: */
+  if (argv != argv) argc = argc;
+
+  $TYPE_INIT_FUNC;
+
+  get_object_types ();
+
+  output_signals ();
+  output_object_hierarchy ();
+  output_object_interfaces ();
+  output_interface_prerequisites ();
+  output_args ();
+
+  return 0;
+}
+
+
+static void
+output_signals (void)
+{
+  FILE *fp;
+  gint i;
+
+  fp = fopen (signals_filename, "w");
+  if (fp == NULL)
+    {
+      g_warning ("Couldn't open output file: %s : %s", signals_filename, strerror(errno));
+      return;
+    }
+
+  for (i = 0; object_types[i]; i++)
+    output_object_signals (fp, object_types[i]);
+
+  fclose (fp);
+}
+
+static gint
+compare_signals (const void *a, const void *b)
+{
+  const guint *signal_a = a;
+  const guint *signal_b = b;
+
+  return strcmp (g_signal_name (*signal_a), g_signal_name (*signal_b));
+}
+
+/* This outputs all the signals of one object. */
+static void
+output_object_signals (FILE *fp, GType object_type)
+{
+  const gchar *object_class_name;
+  guint *signals, n_signals;
+  guint sig;
+
+  if (G_TYPE_IS_INSTANTIATABLE (object_type) ||
+      G_TYPE_IS_INTERFACE (object_type))
+    {
+
+      object_class_name = g_type_name (object_type);
+
+      signals = g_signal_list_ids (object_type, &n_signals);
+      qsort (signals, n_signals, sizeof (guint), compare_signals);
+
+      for (sig = 0; sig < n_signals; sig++)
+        {
+           output_object_signal (fp, object_class_name, signals[sig]);
+        }
+      g_free (signals);
+   }
+}
+
+
+/* This outputs one signal. */
+static void
+output_object_signal (FILE *fp,
+                     const gchar *object_name,
+                     guint signal_id)
+{
+  GSignalQuery query_info;
+  const gchar *type_name, *ret_type, *object_arg, *arg_name;
+  gchar *pos, *object_arg_lower;
+  gboolean is_pointer;
+  gchar ret_type_buffer[1024], buffer[1024];
+  guint i, param;
+  const gchar **arg_names;
+  gint param_num, widget_num, event_num, callback_num;
+  gint *arg_num;
+  gchar signal_name[128];
+  gchar flags[16];
+
+  /*  g_print ("Object: %s Signal: %u\\n", object_name, signal_id);*/
+
+  param_num = 1;
+  widget_num = event_num = callback_num = 0;
+
+  g_signal_query (signal_id, &query_info);
+
+  /* Output the return type and function name. */
+  ret_type = get_type_name (query_info.return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE, &is_pointer);
+  sprintf (ret_type_buffer, "%s%s", ret_type, is_pointer ? "*" : "");
+
+  /* Output the signal object type and the argument name. We assume the
+     type is a pointer - I think that is OK. We remove "Gtk" or "Gnome" and
+     convert to lower case for the argument name. */
+  pos = buffer;
+  sprintf (pos, "%s ", object_name);
+  pos += strlen (pos);
+
+  if (!strncmp (object_name, "Gtk", 3))
+      object_arg = object_name + 3;
+  else if (!strncmp (object_name, "Gnome", 5))
+      object_arg = object_name + 5;
+  else
+      object_arg = object_name;
+
+  object_arg_lower = g_ascii_strdown (object_arg, -1);
+  sprintf (pos, "*%s\\n", object_arg_lower);
+  pos += strlen (pos);
+  if (!strncmp (object_arg_lower, "widget", 6))
+    widget_num = 2;
+  g_free(object_arg_lower);
+
+  /* Convert signal name to use underscores rather than dashes '-'. */
+  strcpy (signal_name, query_info.signal_name);
+  for (i = 0; signal_name[i]; i++)
+    {
+      if (signal_name[i] == '-')
+       signal_name[i] = '_';
+    }
+
+  /* Output the signal parameters. */
+  arg_names = lookup_signal_arg_names (object_name, signal_name);
+
+  for (param = 0; param < query_info.n_params; param++)
+    {
+      if (arg_names)
+       {
+         sprintf (pos, "%s\\n", arg_names[param]);
+         pos += strlen (pos);
+       }
+      else
+       {
+         type_name = get_type_name (query_info.param_types[param] & ~G_SIGNAL_TYPE_STATIC_SCOPE, &is_pointer);
+
+         /* Most arguments to the callback are called "arg1", "arg2", etc.
+            GdkWidgets are called "widget", "widget2", ...
+            GdkEvents are called "event", "event2", ...
+            GtkCallbacks are called "callback", "callback2", ... */
+         if (!strcmp (type_name, "GtkWidget"))
+           {
+             arg_name = "widget";
+             arg_num = &widget_num;
+           }
+         else if (!strcmp (type_name, "GdkEvent"))
+           {
+             type_name = get_gdk_event (signal_name);
+             arg_name = "event";
+             arg_num = &event_num;
+             is_pointer = TRUE;
+           }
+         else if (!strcmp (type_name, "GtkCallback")
+                  || !strcmp (type_name, "GtkCCallback"))
+           {
+             arg_name = "callback";
+             arg_num = &callback_num;
+           }
+         else
+           {
+             arg_name = "arg";
+             arg_num = &param_num;
+           }
+         sprintf (pos, "%s ", type_name);
+         pos += strlen (pos);
+
+         if (!arg_num || *arg_num == 0)
+           sprintf (pos, "%s%s\\n", is_pointer ? "*" : " ", arg_name);
+         else
+           sprintf (pos, "%s%s%i\\n", is_pointer ? "*" : " ", arg_name,
+                    *arg_num);
+         pos += strlen (pos);
+
+         if (arg_num)
+           {
+             if (*arg_num == 0)
+               *arg_num = 2;
+             else
+               *arg_num += 1;
+           }
+       }
+    }
+
+  pos = flags;
+  /* We use one-character flags for simplicity. */
+  if (query_info.signal_flags & G_SIGNAL_RUN_FIRST)
+    *pos++ = 'f';
+  if (query_info.signal_flags & G_SIGNAL_RUN_LAST)
+    *pos++ = 'l';
+  if (query_info.signal_flags & G_SIGNAL_RUN_CLEANUP)
+    *pos++ = 'c';
+  if (query_info.signal_flags & G_SIGNAL_NO_RECURSE)
+    *pos++ = 'r';
+  if (query_info.signal_flags & G_SIGNAL_DETAILED)
+    *pos++ = 'd';
+  if (query_info.signal_flags & G_SIGNAL_ACTION)
+    *pos++ = 'a';
+  if (query_info.signal_flags & G_SIGNAL_NO_HOOKS)
+    *pos++ = 'h';
+  *pos = 0;
+
+  fprintf (fp,
+          "<SIGNAL>\\n<NAME>%s::%s</NAME>\\n<RETURNS>%s</RETURNS>\\n<FLAGS>%s</FLAGS>\\n%s</SIGNAL>\\n\\n",
+          object_name, query_info.signal_name, ret_type_buffer, flags, buffer);
+}
+
+
+/* Returns the type name to use for a signal argument or return value, given
+   the GtkType from the signal info. It also sets is_pointer to TRUE if the
+   argument needs a '*' since it is a pointer. */
+static const gchar *
+get_type_name (GType type, gboolean * is_pointer)
+{
+  const gchar *type_name;
+
+  *is_pointer = FALSE;
+  type_name = g_type_name (type);
+
+  switch (type) {
+  case G_TYPE_NONE:
+  case G_TYPE_CHAR:
+  case G_TYPE_UCHAR:
+  case G_TYPE_BOOLEAN:
+  case G_TYPE_INT:
+  case G_TYPE_UINT:
+  case G_TYPE_LONG:
+  case G_TYPE_ULONG:
+  case G_TYPE_FLOAT:
+  case G_TYPE_DOUBLE:
+  case G_TYPE_POINTER:
+    /* These all have normal C type names so they are OK. */
+    return type_name;
+
+  case G_TYPE_STRING:
+    /* A GtkString is really a gchar*. */
+    *is_pointer = TRUE;
+    return "gchar";
+
+  case G_TYPE_ENUM:
+  case G_TYPE_FLAGS:
+    /* We use a gint for both of these. Hopefully a subtype with a decent
+       name will be registered and used instead, as GTK+ does itself. */
+    return "gint";
+
+  case G_TYPE_BOXED:
+    /* The boxed type shouldn't be used itself, only subtypes. Though we
+       return 'gpointer' just in case. */
+    return "gpointer";
+
+  case G_TYPE_PARAM:
+    /* A GParam is really a GParamSpec*. */
+    *is_pointer = TRUE;
+    return "GParamSpec";
+
+  default:
+    break;
+  }
+
+  /* For all GObject subclasses we can use the class name with a "*",
+     e.g. 'GtkWidget *'. */
+  if (g_type_is_a (type, G_TYPE_OBJECT))
+    *is_pointer = TRUE;
+
+  if (G_TYPE_IS_CLASSED (type))
+    *is_pointer = TRUE;
+
+  /* All boxed subtypes will be pointers as well. */
+  if (g_type_is_a (type, G_TYPE_BOXED))
+    *is_pointer = TRUE;
+
+  /* All pointer subtypes will be pointers as well. */
+  if (g_type_is_a (type, G_TYPE_POINTER))
+    *is_pointer = TRUE;
+
+  /* But enums are not */
+  if (g_type_is_a (type, G_TYPE_ENUM) ||
+      g_type_is_a (type, G_TYPE_FLAGS))
+    *is_pointer = FALSE;
+
+  return type_name;
+}
+
+
+static const gchar *
+get_gdk_event (const gchar * signal_name)
+{
+  static const gchar *GbGDKEvents[] =
+  {
+    "button_press_event", "GdkEventButton",
+    "button_release_event", "GdkEventButton",
+    "motion_notify_event", "GdkEventMotion",
+    "delete_event", "GdkEvent",
+    "destroy_event", "GdkEvent",
+    "expose_event", "GdkEventExpose",
+    "key_press_event", "GdkEventKey",
+    "key_release_event", "GdkEventKey",
+    "enter_notify_event", "GdkEventCrossing",
+    "leave_notify_event", "GdkEventCrossing",
+    "configure_event", "GdkEventConfigure",
+    "focus_in_event", "GdkEventFocus",
+    "focus_out_event", "GdkEventFocus",
+    "map_event", "GdkEvent",
+    "unmap_event", "GdkEvent",
+    "property_notify_event", "GdkEventProperty",
+    "selection_clear_event", "GdkEventSelection",
+    "selection_request_event", "GdkEventSelection",
+    "selection_notify_event", "GdkEventSelection",
+    "proximity_in_event", "GdkEventProximity",
+    "proximity_out_event", "GdkEventProximity",
+    "drag_begin_event", "GdkEventDragBegin",
+    "drag_request_event", "GdkEventDragRequest",
+    "drag_end_event", "GdkEventDragRequest",
+    "drop_enter_event", "GdkEventDropEnter",
+    "drop_leave_event", "GdkEventDropLeave",
+    "drop_data_available_event", "GdkEventDropDataAvailable",
+    "other_event", "GdkEventOther",
+    "client_event", "GdkEventClient",
+    "no_expose_event", "GdkEventNoExpose",
+    "visibility_notify_event", "GdkEventVisibility",
+    "window_state_event", "GdkEventWindowState",
+    "scroll_event", "GdkEventScroll",
+    NULL
+  };
+
+  gint i;
+
+  for (i = 0; GbGDKEvents[i]; i += 2)
+    {
+      if (!strcmp (signal_name, GbGDKEvents[i]))
+       return GbGDKEvents[i + 1];
+    }
+  return "GdkEvent";
+}
+
+
+/* This returns argument names to use for some known GTK signals.
+    It is passed a widget name, e.g. 'GtkCList' and a signal name, e.g.
+    'select_row' and it returns a pointer to an array of argument types and
+    names. */
+static const gchar **
+lookup_signal_arg_names (const gchar * type, const gchar * signal_name)
+{
+  /* Each arg array starts with the object type name and the signal name,
+     and then signal arguments follow. */
+  static const gchar *GbArgTable[][16] =
+  {
+    {"GtkCList", "select_row",
+     "gint             row",
+     "gint             column",
+     "GdkEventButton  *event"},
+    {"GtkCList", "unselect_row",
+     "gint             row",
+     "gint             column",
+     "GdkEventButton  *event"},
+    {"GtkCList", "click_column",
+     "gint             column"},
+
+    {"GtkCList", "resize_column",
+     "gint             column",
+     "gint             width"},
+
+    {"GtkCList", "extend_selection",
+     "GtkScrollType    scroll_type",
+     "gfloat           position",
+     "gboolean         auto_start_selection"},
+    {"GtkCList", "scroll_vertical",
+     "GtkScrollType    scroll_type",
+     "gfloat           position"},
+    {"GtkCList", "scroll_horizontal",
+     "GtkScrollType    scroll_type",
+     "gfloat           position"},
+
+    {"GtkCTree", "tree_select_row",
+     "GtkCTreeNode    *node",
+     "gint             column"},
+    {"GtkCTree", "tree_unselect_row",
+     "GtkCTreeNode    *node",
+     "gint             column"},
+    {"GtkCTree", "tree_expand",
+     "GtkCTreeNode    *node"},
+    {"GtkCTree", "tree_collapse",
+     "GtkCTreeNode    *node"},
+    {"GtkCTree", "tree_move",
+     "GtkCTreeNode    *node",
+     "GtkCTreeNode    *new_parent",
+     "GtkCTreeNode    *new_sibling"},
+    {"GtkCTree", "change_focus_row_expansion",
+     "GtkCTreeExpansionType expansion"},
+
+    {"GtkEditable", "insert_text",
+     "gchar           *new_text",
+     "gint             new_text_length",
+     "gint            *position"},
+    {"GtkEditable", "delete_text",
+     "gint             start_pos",
+     "gint             end_pos"},
+    {"GtkEditable", "set_editable",
+     "gboolean         is_editable"},
+    {"GtkEditable", "move_cursor",
+     "gint             x",
+     "gint             y"},
+    {"GtkEditable", "move_word",
+     "gint             num_words"},
+    {"GtkEditable", "move_page",
+     "gint             x",
+     "gint             y"},
+    {"GtkEditable", "move_to_row",
+     "gint             row"},
+    {"GtkEditable", "move_to_column",
+     "gint             column"},
+
+    {"GtkEditable", "kill_char",
+     "gint             direction"},
+    {"GtkEditable", "kill_word",
+     "gint             direction"},
+    {"GtkEditable", "kill_line",
+     "gint             direction"},
+
+
+    {"GtkInputDialog", "enable_device",
+     "GdkDevice       *deviceid"},
+    {"GtkInputDialog", "disable_device",
+     "GdkDevice       *deviceid"},
+
+    {"GtkListItem", "extend_selection",
+     "GtkScrollType    scroll_type",
+     "gfloat           position",
+     "gboolean         auto_start_selection"},
+    {"GtkListItem", "scroll_vertical",
+     "GtkScrollType    scroll_type",
+     "gfloat           position"},
+    {"GtkListItem", "scroll_horizontal",
+     "GtkScrollType    scroll_type",
+     "gfloat           position"},
+
+    {"GtkMenuShell", "move_current",
+     "GtkMenuDirectionType direction"},
+    {"GtkMenuShell", "activate_current",
+     "gboolean         force_hide"},
+
+
+    {"GtkNotebook", "switch_page",
+     "GtkNotebookPage *page",
+     "guint            page_num"},
+    {"GtkStatusbar", "text_pushed",
+     "guint            context_id",
+     "gchar           *text"},
+    {"GtkStatusbar", "text_popped",
+     "guint            context_id",
+     "gchar           *text"},
+    {"GtkTipsQuery", "widget_entered",
+     "GtkWidget       *widget",
+     "gchar           *tip_text",
+     "gchar           *tip_private"},
+    {"GtkTipsQuery", "widget_selected",
+     "GtkWidget       *widget",
+     "gchar           *tip_text",
+     "gchar           *tip_private",
+     "GdkEventButton  *event"},
+    {"GtkToolbar", "orientation_changed",
+     "GtkOrientation   orientation"},
+    {"GtkToolbar", "style_changed",
+     "GtkToolbarStyle  style"},
+    {"GtkWidget", "draw",
+     "GdkRectangle    *area"},
+    {"GtkWidget", "size_request",
+     "GtkRequisition  *requisition"},
+    {"GtkWidget", "size_allocate",
+     "GtkAllocation   *allocation"},
+    {"GtkWidget", "state_changed",
+     "GtkStateType     state"},
+    {"GtkWidget", "style_set",
+     "GtkStyle        *previous_style"},
+
+    {"GtkWidget", "install_accelerator",
+     "gchar           *signal_name",
+     "gchar            key",
+     "gint             modifiers"},
+
+    {"GtkWidget", "add_accelerator",
+     "guint            accel_signal_id",
+     "GtkAccelGroup   *accel_group",
+     "guint            accel_key",
+     "GdkModifierType  accel_mods",
+     "GtkAccelFlags    accel_flags"},
+
+    {"GtkWidget", "parent_set",
+     "GtkObject       *old_parent"},
+
+    {"GtkWidget", "remove_accelerator",
+     "GtkAccelGroup   *accel_group",
+     "guint            accel_key",
+     "GdkModifierType  accel_mods"},
+    {"GtkWidget", "debug_msg",
+     "gchar           *message"},
+    {"GtkWindow", "move_resize",
+     "gint            *x",
+     "gint            *y",
+     "gint             width",
+     "gint             height"},
+    {"GtkWindow", "set_focus",
+     "GtkWidget       *widget"},
+
+    {"GtkWidget", "selection_get",
+     "GtkSelectionData *data",
+     "guint            info",
+     "guint            time"},
+    {"GtkWidget", "selection_received",
+     "GtkSelectionData *data",
+     "guint            time"},
+
+    {"GtkWidget", "drag_begin",
+     "GdkDragContext  *drag_context"},
+    {"GtkWidget", "drag_end",
+     "GdkDragContext  *drag_context"},
+    {"GtkWidget", "drag_data_delete",
+     "GdkDragContext  *drag_context"},
+    {"GtkWidget", "drag_leave",
+     "GdkDragContext  *drag_context",
+     "guint            time"},
+    {"GtkWidget", "drag_motion",
+     "GdkDragContext  *drag_context",
+     "gint             x",
+     "gint             y",
+     "guint            time"},
+    {"GtkWidget", "drag_drop",
+     "GdkDragContext  *drag_context",
+     "gint             x",
+     "gint             y",
+     "guint            time"},
+    {"GtkWidget", "drag_data_get",
+     "GdkDragContext  *drag_context",
+     "GtkSelectionData *data",
+     "guint            info",
+     "guint            time"},
+    {"GtkWidget", "drag_data_received",
+     "GdkDragContext  *drag_context",
+     "gint             x",
+     "gint             y",
+     "GtkSelectionData *data",
+     "guint            info",
+     "guint            time"},
+
+    {NULL}
+  };
+
+  gint i;
+
+  for (i = 0; GbArgTable[i][0]; i++)
+    {
+#if 1
+      if (!strcmp (type, GbArgTable[i][0])
+         && !strcmp (signal_name, GbArgTable[i][1]))
+       return &GbArgTable[i][2];
+#endif
+    }
+  return NULL;
+}
+
+/* This outputs the hierarchy of all objects which have been initialized,
+   i.e. by calling their XXX_get_type() initialization function. */
+static void
+output_object_hierarchy (void)
+{
+  FILE *fp;
+  gint i;
+
+  fp = fopen (hierarchy_filename, "w");
+  if (fp == NULL)
+    {
+      g_warning ("Couldn't open output file: %s : %s", hierarchy_filename, strerror(errno));
+      return;
+    }
+  output_hierarchy (fp, G_TYPE_OBJECT, 0);
+  output_hierarchy (fp, G_TYPE_INTERFACE, 0);
+  
+  for (i=0; object_types[i]; i++) {
+    if (!g_type_parent (object_types[i]) &&
+      (object_types[i] != G_TYPE_NONE) &&
+      (object_types[i] != G_TYPE_OBJECT) &&
+      (object_types[i] != G_TYPE_INTERFACE)
+    ) {
+      g_warning ("printing hierarchy for root type: %s",
+          g_type_name (object_types[i]));
+      output_hierarchy (fp, object_types[i], 0);
+    }
+  }
+  /* for debugging
+  for (i=0; object_types[i]; i++) {
+    if(object_types[i] != G_TYPE_NONE) {
+      g_print ("type has not been added to hierarchy: %s\\n",
+        g_type_name (object_types[i]));
+    }
+  }
+  for debugging */
+
+  fclose (fp);
+}
+
+/* This is called recursively to output the hierarchy of a widget. */
+static void
+output_hierarchy (FILE  *fp,
+                 GType  type,
+                 guint   level)
+{
+  guint i;
+  GType *children;
+  guint n_children;
+
+  if (!type)
+    return;
+
+  /* for debugging
+  for (i=0; object_types[i]; i++) {
+    if(object_types[i] == type) {
+      g_print ("added type to hierarchy (level %d): %s\\n",
+        level, g_type_name (type));
+      object_types[i] = G_TYPE_NONE;
+      break;
+    }
+  }
+  for debugging */
+
+  for (i = 0; i < level; i++)
+    fprintf (fp, "  ");
+  fprintf (fp, g_type_name (type));
+  fprintf (fp, "\\n");
+
+  children = g_type_children (type, &n_children);
+
+  for (i=0; i < n_children; i++) {
+    output_hierarchy (fp, children[i], level + 1);
+  }
+
+  g_free (children);
+}
+
+static void output_object_interfaces (void)
+{
+  guint i;
+  FILE *fp;
+
+  fp = fopen (interfaces_filename, "w");
+  if (fp == NULL)
+    {
+      g_warning ("Couldn't open output file: %s : %s", interfaces_filename, strerror(errno));
+      return;
+    }
+  output_interfaces (fp, G_TYPE_OBJECT);
+
+  for (i = 0; object_types[i]; i++)
+    {
+      if (!g_type_parent (object_types[i]) &&
+          (object_types[i] != G_TYPE_OBJECT) &&
+          G_TYPE_IS_INSTANTIATABLE (object_types[i]))
+        {
+          output_interfaces (fp, object_types[i]);
+        }
+    }
+  fclose (fp);
+}
+
+static void
+output_interfaces (FILE  *fp,
+                  GType  type)
+{
+  guint i;
+  GType *children, *interfaces;
+  guint n_children, n_interfaces;
+
+  if (!type)
+    return;
+
+  interfaces = g_type_interfaces (type, &n_interfaces);
+
+  if (n_interfaces > 0)
+    {
+      fprintf (fp, g_type_name (type));
+      for (i=0; i < n_interfaces; i++)
+          fprintf (fp, " %s", g_type_name (interfaces[i]));
+      fprintf (fp, "\\n");
+     }
+  g_free (interfaces);
+
+  children = g_type_children (type, &n_children);
+
+  for (i=0; i < n_children; i++)
+    output_interfaces (fp, children[i]);
+
+  g_free (children);
+}
+
+static void output_interface_prerequisites (void)
+{
+  FILE *fp;
+
+  fp = fopen (prerequisites_filename, "w");
+  if (fp == NULL)
+    {
+      g_warning ("Couldn't open output file: %s : %s", prerequisites_filename, strerror(errno));
+      return;
+    }
+  output_prerequisites (fp, G_TYPE_INTERFACE);
+  fclose (fp);
+}
+
+static void
+output_prerequisites (FILE  *fp,
+                     GType  type)
+{
+#if GLIB_CHECK_VERSION(2,1,0)
+  guint i;
+  GType *children, *prerequisites;
+  guint n_children, n_prerequisites;
+
+  if (!type)
+    return;
+
+  prerequisites = g_type_interface_prerequisites (type, &n_prerequisites);
+
+  if (n_prerequisites > 0)
+    {
+      fprintf (fp, g_type_name (type));
+      for (i=0; i < n_prerequisites; i++)
+          fprintf (fp, " %s", g_type_name (prerequisites[i]));
+      fprintf (fp, "\\n");
+     }
+  g_free (prerequisites);
+
+  children = g_type_children (type, &n_children);
+
+  for (i=0; i < n_children; i++)
+    output_prerequisites (fp, children[i]);
+
+  g_free (children);
+#endif
+}
+
+static void
+output_args (void)
+{
+  FILE *fp;
+  gint i;
+
+  fp = fopen (args_filename, "w");
+  if (fp == NULL)
+    {
+      g_warning ("Couldn't open output file: %s : %s", args_filename, strerror(errno));
+      return;
+    }
+
+  for (i = 0; object_types[i]; i++) {
+    output_object_args (fp, object_types[i]);
+  }
+
+  fclose (fp);
+}
+
+static gint
+compare_param_specs (const void *a, const void *b)
+{
+  GParamSpec *spec_a = *(GParamSpec **)a;
+  GParamSpec *spec_b = *(GParamSpec **)b;
+
+  return strcmp (g_param_spec_get_name (spec_a), g_param_spec_get_name (spec_b));
+}
+
+/* Its common to have unsigned properties restricted
+ * to the signed range. Therefore we make this look
+ * a bit nicer by spelling out the max constants.
+ */
+
+/* Don't use "==" with floats, it might trigger a gcc warning.  */
+#define GTKDOC_COMPARE_FLOAT(x, y) (x <= y && x >= y)
+
+static gchar*
+describe_double_constant (gdouble value)
+{
+  gchar *desc;
+
+  if (GTKDOC_COMPARE_FLOAT (value, G_MAXDOUBLE))
+    desc = g_strdup ("G_MAXDOUBLE");
+  else if (GTKDOC_COMPARE_FLOAT (value, G_MINDOUBLE))
+    desc = g_strdup ("G_MINDOUBLE");
+  else if (GTKDOC_COMPARE_FLOAT (value, -G_MAXDOUBLE))
+    desc = g_strdup ("-G_MAXDOUBLE");
+  else if (GTKDOC_COMPARE_FLOAT (value, G_MAXFLOAT))
+    desc = g_strdup ("G_MAXFLOAT");
+  else if (GTKDOC_COMPARE_FLOAT (value, G_MINFLOAT))
+    desc = g_strdup ("G_MINFLOAT");
+  else if (GTKDOC_COMPARE_FLOAT (value, -G_MAXFLOAT))
+    desc = g_strdup ("-G_MAXFLOAT");
+  else
+    desc = g_strdup_printf ("%lg", value);
+
+  return desc;
+}
+
+static gchar*
+describe_signed_constant (gint64 value)
+{
+  gchar *desc;
+
+  if (value == G_MAXINT)
+    desc = g_strdup ("G_MAXINT");
+  else if (value == G_MININT)
+    desc = g_strdup ("G_MININT");
+  else if (value == G_MAXUINT)
+    desc = g_strdup ("G_MAXUINT");
+  else if (value == G_MAXLONG)
+    desc = g_strdup ("G_MAXLONG");
+  else if (value == G_MINLONG)
+    desc = g_strdup ("G_MINLONG");
+  else if (value == G_MAXULONG)
+    desc = g_strdup ("G_MAXULONG");
+  else if (value == G_MAXINT64)
+    desc = g_strdup ("G_MAXINT64");
+  else if (value == G_MININT64)
+    desc = g_strdup ("G_MININT64");
+  else
+    desc = g_strdup_printf ("%" G_GINT64_FORMAT, value);
+
+  return desc;
+}
+
+static gchar*
+describe_unsigned_constant (guint64 value)
+{
+  gchar *desc;
+
+  if (value == G_MAXINT)
+    desc = g_strdup ("G_MAXINT");
+  else if (value == G_MININT)
+    desc = g_strdup ("G_MININT");
+  else if (value == G_MAXUINT)
+    desc = g_strdup ("G_MAXUINT");
+  else if (value == G_MAXLONG)
+    desc = g_strdup ("G_MAXLONG");
+  else if (value == G_MINLONG)
+    desc = g_strdup ("G_MINLONG");
+  else if (value == G_MAXULONG)
+    desc = g_strdup ("G_MAXULONG");
+  else if (value == G_MAXINT64)
+    desc = g_strdup ("G_MAXINT64");
+  else if (value == G_MININT64)
+    desc = g_strdup ("G_MININT64");
+  else if (value == G_MAXUINT64)
+    desc = g_strdup ("G_MAXUINT64");
+  else
+    desc = g_strdup_printf ("%" G_GUINT64_FORMAT, value);
+
+  return desc;
+}
+
+static gchar*
+describe_type (GParamSpec *spec)
+{
+  gchar *desc;
+  gchar *lower;
+  gchar *upper;
+
+  if (G_IS_PARAM_SPEC_CHAR (spec))
+    {
+      GParamSpecChar *pspec = G_PARAM_SPEC_CHAR (spec);
+
+      lower = describe_signed_constant (pspec->minimum);
+      upper = describe_signed_constant (pspec->maximum);
+      if (pspec->minimum == G_MININT8 && pspec->maximum == G_MAXINT8)
+       desc = g_strdup ("");
+      else if (pspec->minimum == G_MININT8)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXINT8)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_UCHAR (spec))
+    {
+      GParamSpecUChar *pspec = G_PARAM_SPEC_UCHAR (spec);
+
+      lower = describe_unsigned_constant (pspec->minimum);
+      upper = describe_unsigned_constant (pspec->maximum);
+      if (pspec->minimum == 0 && pspec->maximum == G_MAXUINT8)
+       desc = g_strdup ("");
+      else if (pspec->minimum == 0)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXUINT8)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_INT (spec))
+    {
+      GParamSpecInt *pspec = G_PARAM_SPEC_INT (spec);
+
+      lower = describe_signed_constant (pspec->minimum);
+      upper = describe_signed_constant (pspec->maximum);
+      if (pspec->minimum == G_MININT && pspec->maximum == G_MAXINT)
+       desc = g_strdup ("");
+      else if (pspec->minimum == G_MININT)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXINT)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_UINT (spec))
+    {
+      GParamSpecUInt *pspec = G_PARAM_SPEC_UINT (spec);
+
+      lower = describe_unsigned_constant (pspec->minimum);
+      upper = describe_unsigned_constant (pspec->maximum);
+      if (pspec->minimum == 0 && pspec->maximum == G_MAXUINT)
+       desc = g_strdup ("");
+      else if (pspec->minimum == 0)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXUINT)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_LONG (spec))
+    {
+      GParamSpecLong *pspec = G_PARAM_SPEC_LONG (spec);
+
+      lower = describe_signed_constant (pspec->minimum);
+      upper = describe_signed_constant (pspec->maximum);
+      if (pspec->minimum == G_MINLONG && pspec->maximum == G_MAXLONG)
+       desc = g_strdup ("");
+      else if (pspec->minimum == G_MINLONG)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXLONG)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_ULONG (spec))
+    {
+      GParamSpecULong *pspec = G_PARAM_SPEC_ULONG (spec);
+      gchar *upper;
+
+      lower = describe_unsigned_constant (pspec->minimum);
+      upper = describe_unsigned_constant (pspec->maximum);
+      if (pspec->minimum == 0 && pspec->maximum == G_MAXULONG)
+       desc = g_strdup ("");
+      else if (pspec->minimum == 0)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXULONG)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_INT64 (spec))
+    {
+      GParamSpecInt64 *pspec = G_PARAM_SPEC_INT64 (spec);
+
+      lower = describe_signed_constant (pspec->minimum);
+      upper = describe_signed_constant (pspec->maximum);
+      if (pspec->minimum == G_MININT64 && pspec->maximum == G_MAXINT64)
+       desc = g_strdup ("");
+      else if (pspec->minimum == G_MININT64)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXINT64)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_UINT64 (spec))
+    {
+      GParamSpecUInt64 *pspec = G_PARAM_SPEC_UINT64 (spec);
+
+      lower = describe_unsigned_constant (pspec->minimum);
+      upper = describe_unsigned_constant (pspec->maximum);
+      if (pspec->minimum == 0 && pspec->maximum == G_MAXUINT64)
+       desc = g_strdup ("");
+      else if (pspec->minimum == 0)
+       desc = g_strdup_printf ("<= %s", upper);
+      else if (pspec->maximum == G_MAXUINT64)
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_FLOAT (spec))
+    {
+      GParamSpecFloat *pspec = G_PARAM_SPEC_FLOAT (spec);
+
+      lower = describe_double_constant (pspec->minimum);
+      upper = describe_double_constant (pspec->maximum);
+      if (GTKDOC_COMPARE_FLOAT (pspec->minimum, -G_MAXFLOAT))
+       {
+         if (GTKDOC_COMPARE_FLOAT (pspec->maximum, G_MAXFLOAT))
+           desc = g_strdup ("");
+         else
+           desc = g_strdup_printf ("<= %s", upper);
+       }
+      else if (GTKDOC_COMPARE_FLOAT (pspec->maximum, G_MAXFLOAT))
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else if (G_IS_PARAM_SPEC_DOUBLE (spec))
+    {
+      GParamSpecDouble *pspec = G_PARAM_SPEC_DOUBLE (spec);
+
+      lower = describe_double_constant (pspec->minimum);
+      upper = describe_double_constant (pspec->maximum);
+      if (GTKDOC_COMPARE_FLOAT (pspec->minimum, -G_MAXDOUBLE))
+       {
+         if (GTKDOC_COMPARE_FLOAT (pspec->maximum, G_MAXDOUBLE))
+           desc = g_strdup ("");
+         else
+           desc = g_strdup_printf ("<= %s", upper);
+       }
+      else if (GTKDOC_COMPARE_FLOAT (pspec->maximum, G_MAXDOUBLE))
+       desc = g_strdup_printf (">= %s", lower);
+      else
+       desc = g_strdup_printf ("[%s,%s]", lower, upper);
+      g_free (lower);
+      g_free (upper);
+    }
+  else
+    {
+      desc = g_strdup ("");
+    }
+
+  return desc;
+}
+
+static gchar*
+describe_default (GParamSpec *spec)
+{
+  gchar *desc;
+
+  if (G_IS_PARAM_SPEC_CHAR (spec))
+    {
+      GParamSpecChar *pspec = G_PARAM_SPEC_CHAR (spec);
+
+      desc = g_strdup_printf ("%d", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_UCHAR (spec))
+    {
+      GParamSpecUChar *pspec = G_PARAM_SPEC_UCHAR (spec);
+
+      desc = g_strdup_printf ("%u", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_BOOLEAN (spec))
+    {
+      GParamSpecBoolean *pspec = G_PARAM_SPEC_BOOLEAN (spec);
+
+      desc = g_strdup_printf ("%s", pspec->default_value ? "TRUE" : "FALSE");
+    }
+  else if (G_IS_PARAM_SPEC_INT (spec))
+    {
+      GParamSpecInt *pspec = G_PARAM_SPEC_INT (spec);
+
+      desc = g_strdup_printf ("%d", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_UINT (spec))
+    {
+      GParamSpecUInt *pspec = G_PARAM_SPEC_UINT (spec);
+
+      desc = g_strdup_printf ("%u", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_LONG (spec))
+    {
+      GParamSpecLong *pspec = G_PARAM_SPEC_LONG (spec);
+
+      desc = g_strdup_printf ("%ld", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_LONG (spec))
+    {
+      GParamSpecULong *pspec = G_PARAM_SPEC_ULONG (spec);
+
+      desc = g_strdup_printf ("%lu", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_INT64 (spec))
+    {
+      GParamSpecInt64 *pspec = G_PARAM_SPEC_INT64 (spec);
+
+      desc = g_strdup_printf ("%" G_GINT64_FORMAT, pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_UINT64 (spec))
+    {
+      GParamSpecUInt64 *pspec = G_PARAM_SPEC_UINT64 (spec);
+
+      desc = g_strdup_printf ("%" G_GUINT64_FORMAT, pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_UNICHAR (spec))
+    {
+      GParamSpecUnichar *pspec = G_PARAM_SPEC_UNICHAR (spec);
+
+      if (g_unichar_isprint (pspec->default_value))
+       desc = g_strdup_printf ("'%c'", pspec->default_value);
+      else
+       desc = g_strdup_printf ("%u", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_ENUM (spec))
+    {
+      GParamSpecEnum *pspec = G_PARAM_SPEC_ENUM (spec);
+
+      GEnumValue *value = g_enum_get_value (pspec->enum_class, pspec->default_value);
+      if (value)
+       desc = g_strdup_printf ("%s", value->value_name);
+      else
+       desc = g_strdup_printf ("%d", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_FLAGS (spec))
+    {
+      GParamSpecFlags *pspec = G_PARAM_SPEC_FLAGS (spec);
+      guint default_value;
+      GString *acc;
+
+      default_value = pspec->default_value;
+      acc = g_string_new ("");
+
+      while (default_value)
+       {
+         GFlagsValue *value = g_flags_get_first_value (pspec->flags_class, default_value);
+
+         if (!value)
+           break;
+
+         if (acc->len > 0)
+           g_string_append (acc, "|");
+         g_string_append (acc, value->value_name);
+
+         default_value &= ~value->value;
+       }
+
+      if (default_value == 0)
+       desc = g_string_free (acc, FALSE);
+      else
+       {
+         desc = g_strdup_printf ("%d", pspec->default_value);
+         g_string_free (acc, TRUE);
+       }
+    }
+  else if (G_IS_PARAM_SPEC_FLOAT (spec))
+    {
+      GParamSpecFloat *pspec = G_PARAM_SPEC_FLOAT (spec);
+
+      desc = g_strdup_printf ("%g", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_DOUBLE (spec))
+    {
+      GParamSpecDouble *pspec = G_PARAM_SPEC_DOUBLE (spec);
+
+      desc = g_strdup_printf ("%lg", pspec->default_value);
+    }
+  else if (G_IS_PARAM_SPEC_STRING (spec))
+    {
+      GParamSpecString *pspec = G_PARAM_SPEC_STRING (spec);
+
+      if (pspec->default_value)
+       {
+         gchar *esc = g_strescape (pspec->default_value, NULL);
+
+         desc = g_strdup_printf ("\\"%s\\"", esc);
+
+         g_free (esc);
+       }
+      else
+       desc = g_strdup_printf ("NULL");
+    }
+  else
+    {
+      desc = g_strdup ("");
+    }
+
+  return desc;
+}
+
+
+static void
+output_object_args (FILE *fp, GType object_type)
+{
+  gpointer class;
+  const gchar *object_class_name;
+  guint arg;
+  gchar flags[16], *pos;
+  GParamSpec **properties;
+  guint n_properties;
+  gboolean child_prop;
+  gboolean style_prop;
+  gboolean is_pointer;
+  const gchar *type_name;
+  gchar *type_desc;
+  gchar *default_value;
+
+  if (G_TYPE_IS_OBJECT (object_type))
+    {
+      class = g_type_class_peek (object_type);
+      if (!class)
+       return;
+
+      properties = g_object_class_list_properties (class, &n_properties);
+    }
+#if GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 3)
+  else if (G_TYPE_IS_INTERFACE (object_type))
+    {
+      class = g_type_default_interface_ref (object_type);
+
+      if (!class)
+       return;
+
+      properties = g_object_interface_list_properties (class, &n_properties);
+    }
+#endif
+  else
+    return;
+
+  object_class_name = g_type_name (object_type);
+
+  child_prop = FALSE;
+  style_prop = FALSE;
+
+  while (TRUE) {
+    qsort (properties, n_properties, sizeof (GParamSpec *), compare_param_specs);
+    for (arg = 0; arg < n_properties; arg++)
+      {
+        GParamSpec *spec = properties[arg];
+        const gchar *nick, *blurb, *dot;
+
+        if (spec->owner_type != object_type)
+          continue;
+
+        pos = flags;
+        /* We use one-character flags for simplicity. */
+        if (child_prop && !style_prop)
+         *pos++ = 'c';
+        if (style_prop)
+         *pos++ = 's';
+        if (spec->flags & G_PARAM_READABLE)
+         *pos++ = 'r';
+        if (spec->flags & G_PARAM_WRITABLE)
+         *pos++ = 'w';
+        if (spec->flags & G_PARAM_CONSTRUCT)
+         *pos++ = 'x';
+        if (spec->flags & G_PARAM_CONSTRUCT_ONLY)
+         *pos++ = 'X';
+        *pos = 0;
+
+        nick = g_param_spec_get_nick (spec);
+        blurb = g_param_spec_get_blurb (spec);
+
+        dot = "";
+        if (blurb) {
+          int str_len = strlen (blurb);
+          if (str_len > 0  && blurb[str_len - 1] != '.')
+            dot = ".";
+        }
+
+       type_desc = describe_type (spec);
+       default_value = describe_default (spec);
+       type_name = get_type_name (spec->value_type, &is_pointer);
+        fprintf (fp, "<ARG>\\n<NAME>%s::%s</NAME>\\n<TYPE>%s%s</TYPE>\\n<RANGE>%s</RANGE>\\n<FLAGS>%s</FLAGS>\\n<NICK>%s</NICK>\\n<BLURB>%s%s</BLURB>\\n<DEFAULT>%s</DEFAULT>\\n</ARG>\\n\\n",
+                object_class_name, g_param_spec_get_name (spec), type_name, is_pointer ? "*" : "", type_desc, flags, nick ? nick : "(null)", blurb ? blurb : "(null)", dot, default_value);
+       g_free (type_desc);
+       g_free (default_value);
+      }
+
+    g_free (properties);
+
+#ifdef GTK_IS_CONTAINER_CLASS
+    if (!child_prop && GTK_IS_CONTAINER_CLASS (class)) {
+      properties = gtk_container_class_list_child_properties (class, &n_properties);
+      child_prop = TRUE;
+      continue;
+    }
+#endif
+
+#ifdef GTK_IS_WIDGET_CLASS
+#if GTK_CHECK_VERSION(2,1,0)
+    if (!style_prop && GTK_IS_WIDGET_CLASS (class)) {
+      properties = gtk_widget_class_list_style_properties (GTK_WIDGET_CLASS (class), &n_properties);
+      style_prop = TRUE;
+      continue;
+    }
+#endif
+#endif
+
+    break;
+  }
+}
+EOT
+
+close OUTPUT;
+
+# Compile and run our file
+
+$CC = $ENV{CC} ? $ENV{CC} : "gcc";
+$LD = $ENV{LD} ? $ENV{LD} : $CC;
+$CFLAGS = $ENV{CFLAGS} ? "$ENV{CFLAGS} -Wall -g" : "-Wall -g";
+$LDFLAGS = $ENV{LDFLAGS} ? $ENV{LDFLAGS} : "";
+
+my $o_file;
+if ($CC =~ /libtool/) {
+  $o_file  = "$MODULE-scan.lo"
+} else {
+  $o_file = "$MODULE-scan.o"
+}
+
+print "gtk-doc: Compiling scanner\n";
+$command = "$CC $CFLAGS -c -o $o_file $MODULE-scan.c";
+system($command) == 0 or die "Compilation of scanner failed: $!\n";
+
+print "gtk-doc: Linking scanner\n";
+$command = "$LD -o $MODULE-scan $o_file $LDFLAGS";
+system($command) == 0 or die "Linking of scanner failed: $!\n";
+
+print "gtk-doc: Running scanner $MODULE-scan\n";
+system("sh -c ./$MODULE-scan") == 0 or die "Scan failed: $!\n";
+
+unlink "./$MODULE-scan.c", "./$MODULE-scan.o", "./$MODULE-scan.lo", "./$MODULE-scan";
+
+#&UpdateFileIfChanged ($old_signals_filename, $new_signals_filename, 0);
+&UpdateFileIfChanged ($old_hierarchy_filename, $new_hierarchy_filename, 0);
+&UpdateFileIfChanged ($old_interfaces_filename, $new_interfaces_filename, 0);
+&UpdateFileIfChanged ($old_prerequisites_filename, $new_prerequisites_filename, 0);
+#&UpdateFileIfChanged ($old_args_filename, $new_args_filename, 0);
+
+
diff --git a/common/gtk-doc-plugins.mak b/common/gtk-doc-plugins.mak
new file mode 100755 (executable)
index 0000000..71f60ba
--- /dev/null
@@ -0,0 +1,397 @@
+# This is an include file specifically tuned for building documentation
+# for GStreamer plug-ins
+
+help:
+       @echo
+       @echo "If you are a doc maintainer, run 'make update' to update"
+       @echo "the documentation files maintained in CVS"
+       @echo
+       @echo Other useful make targets:
+       @echo
+       @echo  check-inspected-versions: make sure the inspected plugin info
+       @echo                            is up to date before a release
+       @echo
+
+# update the stuff maintained by doc maintainers
+update:
+       $(MAKE) inspect-update
+       $(MAKE) scanobj-update
+
+# We set GPATH here; this gives us semantics for GNU make
+# which are more like other make's VPATH, when it comes to
+# whether a source that is a target of one rule is then
+# searched for in VPATH/GPATH.
+#
+GPATH = $(srcdir)
+
+# thomas: make docs parallel installable
+TARGET_DIR=$(HTML_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@
+
+EXTRA_DIST =                           \
+       scanobj-build.stamp             \
+       $(srcdir)/inspect/*.xml         \
+       inspect.stamp                   \
+       inspect-build.stamp             \
+       $(SCANOBJ_FILES)                \
+       $(content_files)                \
+       $(extra_files)                  \
+       $(HTML_IMAGES)                  \
+       $(DOC_MAIN_SGML_FILE)   \
+       $(DOC_OVERRIDES)                \
+       $(DOC_MODULE)-sections.txt
+
+MAINTAINER_DOC_STAMPS =                        \
+       scanobj-build.stamp             \
+       inspect-build.stamp             \
+       inspect.stamp
+
+# we don't add inspect-build.stamp and scanobj-build.stamp here since they are
+# built manually by docs maintainers and result is commited to CVS
+DOC_STAMPS =                           \
+       scan-build.stamp                \
+       tmpl-build.stamp                \
+       sgml-build.stamp                \
+       html-build.stamp                \
+       scan.stamp                      \
+       tmpl.stamp                      \
+       sgml.stamp                      \
+       html.stamp
+
+# files generated/updated by gtkdoc-scangobj
+SCANOBJ_FILES =                                \
+       $(DOC_MODULE).signals           \
+        $(DOC_MODULE).hierarchy         \
+        $(DOC_MODULE).interfaces        \
+        $(DOC_MODULE).prerequisites     \
+       $(DOC_MODULE).types             \
+        $(DOC_MODULE).args
+
+SCANOBJ_FILES_O =                      \
+       .libs/$(DOC_MODULE)-scan.o
+
+# files generated/updated by gtkdoc-scan
+SCAN_FILES =                           \
+       $(DOC_MODULE)-sections.txt      \
+       $(DOC_MODULE)-overrides.txt     \
+       $(DOC_MODULE)-undocumented.txt  \
+       $(DOC_MODULE)-decl.txt          \
+       $(DOC_MODULE)-decl-list.txt
+
+
+REPORT_FILES = \
+       $(DOC_MODULE)-undocumented.txt \
+       $(DOC_MODULE)-undeclared.txt \
+       $(DOC_MODULE)-unused.txt
+
+# FC3 seems to need -scan.c to be part of CLEANFILES for distcheck
+# no idea why FC4 can do without
+CLEANFILES = \
+       $(SCANOBJ_FILES_O) \
+       $(DOC_MODULE)-scan.c \
+       $(REPORT_FILES) \
+       $(DOC_STAMPS) \
+       inspect-registry.xml
+
+
+if ENABLE_GTK_DOC
+all-local: html-build.stamp
+
+#### scan gobjects; done by documentation maintainer ####
+scanobj-update:
+       -rm scanobj-build.stamp
+       $(MAKE) scanobj-build.stamp
+
+# in the case of non-srcdir builds, the built gst directory gets added
+# to gtk-doc scanning; but only then, to avoid duplicates
+# FIXME: since we don't have the scan step as part of the build anymore,
+# we could remove that
+# TODO: finish elite script that updates the output files of this step
+# instead of rewriting them, so that multiple maintainers can generate
+# a collective set of args and signals
+scanobj-build.stamp: $(SCANOBJ_DEPS) $(basefiles)
+       @echo '*** Scanning GObjects ***'
+       if test x"$(srcdir)" != x. ; then                               \
+           for f in $(SCANOBJ_FILES);                                  \
+           do                                                          \
+               cp $(srcdir)/$$f . ;                                    \
+           done;                                                       \
+       else                                                            \
+           $(INSPECT_ENVIRONMENT)                                      \
+           CC="$(GTKDOC_CC)" LD="$(GTKDOC_LD)"                         \
+           CFLAGS="-g $(GTKDOC_CFLAGS)" LDFLAGS="$(GTKDOC_LIBS)"               \
+           $(GST_DOC_SCANOBJ) --type-init-func="gst_init(NULL,NULL)"   \
+               --module=$(DOC_MODULE) --source=$(PACKAGE) &&           \
+               $(PYTHON)                                               \
+               $(top_srcdir)/common/scangobj-merge.py $(DOC_MODULE);   \
+       fi
+       touch scanobj-build.stamp
+
+$(DOC_MODULE)-decl.txt $(SCANOBJ_FILES) $(SCANOBJ_FILES_O): scan-build.stamp
+       @true
+
+### inspect GStreamer plug-ins; done by documentation maintainer ###
+
+# only look at the plugins in this module when building inspect .xml stuff
+INSPECT_REGISTRY=$(top_builddir)/docs/plugins/inspect-registry.xml
+INSPECT_ENVIRONMENT=\
+        GST_PLUGIN_SYSTEM_PATH= \
+        GST_PLUGIN_PATH=$(top_builddir)/gst:$(top_builddir)/sys:$(top_builddir)/ext:$(top_builddir)/plugins:$(top_builddir)/src \
+        GST_REGISTRY=$(INSPECT_REGISTRY)
+
+# update the element and plugin XML descriptions; store in inspect/
+inspect:
+       mkdir inspect
+
+inspect-update: inspect
+       -rm $(INSPECT_REGISTRY)
+       -rm inspect-build.stamp
+       $(MAKE) inspect-build.stamp
+
+# FIXME: inspect.stamp should be written to by gst-xmlinspect.py
+# IF the output changed; see gtkdoc-mktmpl
+inspect-build.stamp:
+       @echo '*** Rebuilding plugin inspection files ***'
+       if test x"$(srcdir)" != x. ; then \
+           cp $(srcdir)/inspect.stamp . ; \
+           cp $(srcdir)/inspect-build.stamp . ; \
+       else \
+           $(INSPECT_ENVIRONMENT) $(PYTHON) \
+               $(top_srcdir)/common/gst-xmlinspect.py $(PACKAGE) inspect && \
+           echo -n "timestamp" > inspect.stamp && \
+           touch inspect-build.stamp; \
+        fi
+
+### scan headers; done on every build ###
+scan-build.stamp: $(HFILE_GLOB) $(EXTRA_HFILES) $(basefiles) scanobj-build.stamp inspect-build.stamp
+       if test "x$(top_srcdir)" != "x$(top_builddir)" &&               \
+          test -d "$(top_builddir)/gst";                               \
+        then                                                           \
+            export BUILT_OPTIONS="--source-dir=$(top_builddir)/gst";   \
+        fi;                                                            \
+       gtkdoc-scan                                                     \
+           $(SCAN_OPTIONS) $(EXTRA_HFILES)                             \
+           --module=$(DOC_MODULE)                                      \
+           $$BUILT_OPTIONS                                             \
+           --ignore-headers="$(IGNORE_HFILES)";                        \
+       touch scan-build.stamp
+
+#### update templates; done on every build ####
+
+### FIXME: make this error out again when docs are fixed for 0.9
+# in a non-srcdir build, we need to copy files from the previous step
+# and the files from previous runs of this step
+tmpl-build.stamp: $(DOC_MODULE)-decl.txt $(SCANOBJ_FILES) $(DOC_MODULE)-sections.txt $(DOC_OVERRIDES)
+       @echo '*** Rebuilding template files ***'
+       if test x"$(srcdir)" != x. ; then                               \
+           for f in $(SCANOBJ_FILES) $(SCAN_FILES);                    \
+           do                                                          \
+               if test -e $(srcdir)/$$f; then cp $(srcdir)/$$f . ; fi; \
+           done;                                                       \
+       fi
+       gtkdoc-mktmpl --module=$(DOC_MODULE) | tee tmpl-build.log
+       $(PYTHON) \
+               $(top_srcdir)/common/mangle-tmpl.py $(srcdir)/inspect tmpl
+       @cat $(DOC_MODULE)-unused.txt
+       rm -f tmpl-build.log
+       touch tmpl-build.stamp
+
+tmpl.stamp: tmpl-build.stamp
+       @true
+
+#### build xml; done on every build ####
+
+### FIXME: make this error out again when docs are fixed for 0.9
+sgml-build.stamp: tmpl.stamp inspect.stamp $(CFILE_GLOB) $(top_srcdir)/common/plugins.xsl
+       @echo '*** Building XML ***'
+       @-mkdir -p xml
+       @for a in $(srcdir)/inspect/*.xml; do \
+            xsltproc --stringparam module $(MODULE) \
+               $(top_srcdir)/common/plugins.xsl $$a > xml/`basename $$a`; done
+       @for f in $(EXAMPLE_CFILES); do \
+               $(PYTHON) $(top_srcdir)/common/c-to-xml.py $$f > xml/element-`basename $$f .c`.xml; done
+       gtkdoc-mkdb \
+               --module=$(DOC_MODULE) \
+               --source-dir=$(DOC_SOURCE_DIR) \
+               --main-sgml-file=$(srcdir)/$(DOC_MAIN_SGML_FILE) \
+               --output-format=xml \
+               --ignore-files="$(IGNORE_HFILES) $(IGNORE_CFILES)" \
+               $(MKDB_OPTIONS) \
+               | tee sgml-build.log
+       @if grep "WARNING:" sgml-build.log > /dev/null; then true; fi # exit 1; fi
+       cp ../version.entities xml
+       rm sgml-build.log
+       touch sgml-build.stamp
+
+sgml.stamp: sgml-build.stamp
+       @true
+
+#### build html; done on every step ####
+
+html-build.stamp: sgml.stamp $(DOC_MAIN_SGML_FILE) $(content_files)
+       @echo '*** Building HTML ***'
+       if test -d html; then rm -rf html; fi
+       mkdir html
+       cp $(srcdir)/$(DOC_MAIN_SGML_FILE) html
+       @for f in $(content_files); do cp $(srcdir)/$$f html; done
+       cp -pr xml html
+       cp ../version.entities html
+       cd html && gtkdoc-mkhtml $(DOC_MODULE) $(DOC_MAIN_SGML_FILE) \
+           2>&1 | tee ../html-build.log
+       @if grep "warning:" html-build.log > /dev/null; then \
+               echo "ERROR"; grep "warning:" html-build.log; exit 1; fi
+       @rm html-build.log
+       mv html/index.sgml html/index.sgml.bak
+       $(SED) "s/ href=\"$(DOC_MODULE)\// href=\"$(DOC_MODULE)-@GST_MAJORMINOR@\//g" html/index.sgml.bak >html/index.sgml
+       rm -f html/index.sgml.bak
+       rm -f html/$(DOC_MAIN_SGML_FILE)
+       rm -rf html/xml
+       rm -f html/version.entities
+       test "x$(HTML_IMAGES)" = "x" || for i in "" $(HTML_IMAGES) ; do \
+           if test "$$i" != ""; then cp $(srcdir)/$$i html ; fi; done
+       @echo '-- Fixing Crossreferences' 
+       gtkdoc-fixxref --module-dir=html --html-dir=$(HTML_DIR) $(FIXXREF_OPTIONS)
+       touch html-build.stamp
+else
+all-local:
+endif
+
+# FIXME: these rules need a little cleaning up
+clean-local:
+       rm -f *~ *.bak
+       rm -rf .libs
+# clean files generated for tmpl build
+       -rm -rf tmpl
+# clean files copied/generated for nonsrcdir tmpl build
+       if test x"$(srcdir)" != x. ; then \
+           rm -rf $(SCANOBJ_FILES) $(SCAN_FILES);                      \
+       fi
+# clean files generated for xml build
+       -rm -rf xml
+# clean files generate for html build
+       -rm -rf html
+
+distclean-local: clean
+       rm -rf tmpl/*.sgml.bak
+       rm -f *.stamp || true
+       rm -rf *.o
+
+# thomas: make docs parallel installable; devhelp requires majorminor too
+install-data-local:
+       $(mkinstalldirs) $(DESTDIR)$(TARGET_DIR) 
+       (installfiles=`echo ./html/*.html`; \
+       if test "$$installfiles" = './html/*.html'; \
+       then echo '-- Nothing to install' ; \
+       else \
+         for i in $$installfiles; do \
+           echo '-- Installing '$$i ; \
+           $(INSTALL_DATA) $$i $(DESTDIR)$(TARGET_DIR); \
+         done; \
+         pngfiles=`echo ./html/*.png`; \
+         if test "$$pngfiles" != './html/*.png'; then \
+           for i in $$pngfiles; do \
+             echo '-- Installing '$$i ; \
+             $(INSTALL_DATA) $$i $(DESTDIR)$(TARGET_DIR); \
+           done; \
+         fi; \
+         echo '-- Installing $(srcdir)/html/$(DOC_MODULE).devhelp' ; \
+         $(INSTALL_DATA) $(srcdir)/html/$(DOC_MODULE).devhelp \
+           $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp; \
+         if test -e $(srcdir)/html/$(DOC_MODULE).devhelp2; then \
+                 $(INSTALL_DATA) $(srcdir)/html/$(DOC_MODULE).devhelp2 \
+                  $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp2; \
+         fi; \
+         echo '-- Installing $(srcdir)/html/index.sgml' ; \
+         $(INSTALL_DATA) $(srcdir)/html/index.sgml $(DESTDIR)$(TARGET_DIR); \
+               if test -e $(srcdir)/html/style.css; then \
+                       echo '-- Installing $(srcdir)/html/style.css' ; \
+                       $(INSTALL_DATA) $(srcdir)/html/style.css $(DESTDIR)$(TARGET_DIR); \
+               fi; \
+       fi) 
+uninstall-local:
+       (installfiles=`echo ./html/*.html`; \
+       if test "$$installfiles" = './html/*.html'; \
+       then echo '-- Nothing to uninstall' ; \
+       else \
+         for i in $$installfiles; do \
+           rmfile=`basename $$i` ; \
+           echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/'$$rmfile ; \
+           rm -f $(DESTDIR)$(TARGET_DIR)/$$rmfile; \
+         done; \
+         pngfiles=`echo ./html/*.png`; \
+         if test "$$pngfiles" != './html/*.png'; then \
+           for i in $$pngfiles; do \
+             rmfile=`basename $$i` ; \
+             echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/'$$rmfile ; \
+             rm -f $(DESTDIR)$(TARGET_DIR)/$$rmfile; \
+           done; \
+         fi; \
+         echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE).devhelp' ; \
+         rm -f $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp; \
+         if test -e $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp2; then \
+           rm -f $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp2; \
+         fi; \
+         echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/index.sgml' ; \
+         rm -f $(DESTDIR)$(TARGET_DIR)/index.sgml; \
+               if test -e $(DESTDIR)$(TARGET_DIR)/style.css; then \
+                       echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/style.css' ; \
+                       rm -f $(DESTDIR)$(TARGET_DIR)/style.css; \
+               fi; \
+       fi) 
+       if test -d $(DESTDIR)$(TARGET_DIR); then rmdir -p --ignore-fail-on-non-empty $(DESTDIR)$(TARGET_DIR) 2>/dev/null; fi; true
+
+#
+# Checks
+#
+check-hierarchy: $(DOC_MODULE).hierarchy
+       @if grep '      ' $(DOC_MODULE).hierarchy; then \
+           echo "$(DOC_MODULE).hierarchy contains tabs, please fix"; \
+           /bin/false; \
+       fi
+
+check: check-hierarchy
+
+# wildcard is apparently not portable to other makes, hence the use of find
+inspect_files = $(shell find $(top_srcdir)/docs/plugins/inspect -name '*.xml')
+
+check-inspected-versions:
+       @echo Checking plugin versions of inspected plugin data ...; \
+       fail=0 ; \
+       for each in $(inspect_files) ; do \
+         if (grep -H '<version>' $$each | grep -v '<version>$(VERSION)'); then \
+           echo $$each should be fixed to say version $(VERSION) or be removed ; \
+           echo "sed -i -e 's/<version.*version>/<version>$(VERSION)<\/version>/'" $$each; \
+           echo ; \
+           fail=1; \
+         fi ; \
+       done ; \
+       exit $$fail
+
+#
+# Require gtk-doc when making dist
+#
+if ENABLE_GTK_DOC
+dist-check-gtkdoc:
+else
+dist-check-gtkdoc:
+       @echo "*** gtk-doc must be installed and enabled in order to make dist"
+       @false
+endif
+
+# FIXME: decide whether we want to dist generated html or not
+dist-hook: dist-check-gtkdoc dist-hook-local
+       mkdir $(distdir)/tmpl
+       mkdir $(distdir)/xml
+       mkdir $(distdir)/html
+       -cp $(srcdir)/tmpl/*.sgml $(distdir)/tmpl
+       -cp $(srcdir)/sgml/*.xml $(distdir)/xml
+       -cp $(srcdir)/html/index.sgml $(distdir)/html
+       -cp $(srcdir)/html/*.html $(srcdir)/html/*.css $(distdir)/html
+       -cp $(srcdir)/html/$(DOC_MODULE).devhelp* $(distdir)/html
+
+       images=$(HTML_IMAGES) ;               \
+       for i in "" $$images ; do                     \
+         if test "$$i" != ""; then cp $(srcdir)/$$i $(distdir)/html ; fi; \
+       done
+
+.PHONY : dist-hook-local
+
diff --git a/common/gtk-doc.mak b/common/gtk-doc.mak
new file mode 100755 (executable)
index 0000000..1c9ece1
--- /dev/null
@@ -0,0 +1,267 @@
+###########################################################################
+# Everything below here is generic and you shouldn't need to change it.
+###########################################################################
+# thomas: except of course that we did
+
+# thomas: copied from glib-2
+# We set GPATH here; this gives us semantics for GNU make
+# which are more like other make's VPATH, when it comes to
+# whether a source that is a target of one rule is then
+# searched for in VPATH/GPATH.
+#
+GPATH = $(srcdir)
+
+# thomas: make docs parallel installable
+TARGET_DIR=$(HTML_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@
+
+EXTRA_DIST =                           \
+       $(content_files)                \
+       $(extra_files)                  \
+       $(HTML_IMAGES)                  \
+       $(DOC_MAIN_SGML_FILE)           \
+       $(DOC_MODULE).types             \
+       $(DOC_OVERRIDES)                \
+       $(DOC_MODULE)-sections.txt
+
+DOC_STAMPS =                           \
+       scan-build.stamp                \
+       tmpl-build.stamp                \
+       sgml-build.stamp                \
+       html-build.stamp                \
+       $(srcdir)/tmpl.stamp            \
+       $(srcdir)/sgml.stamp            \
+       $(srcdir)/html.stamp
+
+SCANOBJ_FILES =                                \
+       $(DOC_MODULE).args              \
+       $(DOC_MODULE).hierarchy         \
+       $(DOC_MODULE).interfaces        \
+       $(DOC_MODULE).prerequisites     \
+       .libs/$(DOC_MODULE)-scan.o      \
+       $(DOC_MODULE).signals
+
+REPORT_FILES = \
+       $(DOC_MODULE)-undocumented.txt \
+       $(DOC_MODULE)-undeclared.txt \
+       $(DOC_MODULE)-unused.txt
+
+CLEANFILES = $(SCANOBJ_FILES) $(REPORT_FILES) $(DOC_STAMPS)
+
+if ENABLE_GTK_DOC
+all-local: html-build.stamp
+
+#### scan ####
+
+# in the case of non-srcdir builds, the built gst directory gets added
+# to gtk-doc scanning; but only then, to avoid duplicates
+scan-build.stamp: $(HFILE_GLOB) $(SCANOBJ_DEPS) $(basefiles)
+       @echo '*** Scanning header files ***'
+       if grep -l '^..*$$' $(srcdir)/$(DOC_MODULE).types > /dev/null;  \
+       then                                                            \
+           if test x"$(srcdir)" != x. ; then                           \
+               cp $(srcdir)/$(DOC_MODULE).types . ;                    \
+               chmod u+w $(DOC_MODULE).types ;                         \
+           fi ;                                                        \
+           GST_PLUGIN_SYSTEM_PATH=`cd $(top_builddir) && pwd`          \
+           GST_PLUGIN_PATH=                                            \
+           CC="$(GTKDOC_CC)" LD="$(GTKDOC_LD)"                         \
+           CFLAGS="$(GTKDOC_CFLAGS)" LDFLAGS="$(GTKDOC_LIBS)"          \
+           gtkdoc-scangobj --type-init-func="gst_init(NULL,NULL)"      \
+               --module=$(DOC_MODULE) ;                                \
+       else                                                            \
+           cd $(srcdir) ;                                              \
+           for i in $(SCANOBJ_FILES) ; do                              \
+               test -f $$i || touch $$i ;                              \
+           done                                                        \
+       fi
+       if test "x$(top_srcdir)" != "x$(top_builddir)";                 \
+        then                                                           \
+          export BUILT_OPTIONS="--source-dir=$(DOC_BUILD_DIR)";                \
+        fi;                                                            \
+       gtkdoc-scan                                                     \
+               $(SCAN_OPTIONS) $(EXTRA_HFILES)                         \
+               --module=$(DOC_MODULE)                                  \
+               --source-dir=$(DOC_SOURCE_DIR)                          \
+               $$BUILT_OPTIONS                                         \
+               --ignore-headers="$(IGNORE_HFILES)"
+       touch scan-build.stamp
+
+$(DOC_MODULE)-decl.txt $(SCANOBJ_FILES): scan-build.stamp
+       @true
+
+#### templates ####
+
+tmpl-build.stamp: $(DOC_MODULE)-decl.txt $(SCANOBJ_FILES) $(DOC_MODULE)-sections.txt $(DOC_OVERRIDES)
+       @echo '*** Rebuilding template files ***'
+       if test x"$(srcdir)" != x. ; then \
+           cp $(srcdir)/$(DOC_MODULE)-sections.txt . ; \
+           touch $(DOC_MODULE)-decl.txt ; \
+       fi
+       gtkdoc-mktmpl --module=$(DOC_MODULE) | tee tmpl-build.log
+       @if test -s $(DOC_MODULE)-unused.txt; then \
+           exit $(if $(DOCS_ARE_INCOMPLETE_PLEASE_FIXME),0,1); fi
+       rm -f tmpl-build.log
+       touch tmpl-build.stamp
+
+tmpl.stamp: tmpl-build.stamp
+       @true
+
+#### xml ####
+
+### FIXME: make this error out again when docs are complete
+sgml-build.stamp: tmpl.stamp $(CFILE_GLOB)
+       @echo '*** Building XML ***'
+       gtkdoc-mkdb --module=$(DOC_MODULE) --source-dir=$(DOC_SOURCE_DIR) --main-sgml-file=$(srcdir)/$(DOC_MAIN_SGML_FILE) --output-format=xml $(MKDB_OPTIONS) | tee sgml-build.log
+       @if grep "WARNING:" sgml-build.log > /dev/null; then true; fi # exit 1; fi
+       rm sgml-build.log
+       touch sgml-build.stamp
+
+sgml.stamp: sgml-build.stamp
+       @true
+
+#### html ####
+
+html-build.stamp: sgml.stamp $(DOC_MAIN_SGML_FILE) $(content_files)
+       @echo '*** Building HTML ***'
+       if test -d html; then rm -rf html; fi
+       mkdir html
+       cp $(srcdir)/$(DOC_MAIN_SGML_FILE) html
+       @for f in $(content_files); do cp $(srcdir)/$$f html; done
+       cp -pr xml html
+       cp ../version.entities html
+       cd html && gtkdoc-mkhtml $(DOC_MODULE) $(DOC_MAIN_SGML_FILE)
+       mv html/index.sgml html/index.sgml.bak
+       $(SED) "s/ href=\"$(DOC_MODULE)\// href=\"$(DOC_MODULE)-@GST_MAJORMINOR@\//g" html/index.sgml.bak >html/index.sgml
+       rm -f html/index.sgml.bak
+       rm -f html/$(DOC_MAIN_SGML_FILE)
+       rm -rf html/xml
+       rm -f html/version.entities
+       test "x$(HTML_IMAGES)" = "x" || for i in "" $(HTML_IMAGES) ; do \
+           if test "$$i" != ""; then cp $(srcdir)/$$i html ; fi; done
+       @echo '-- Fixing Crossreferences' 
+       gtkdoc-fixxref --module-dir=html --html-dir=$(HTML_DIR) $(FIXXREF_OPTIONS)
+       touch html-build.stamp
+else
+all-local:
+endif
+
+clean-local:
+       rm -f *~ *.bak
+       rm -rf xml html
+       rm -rf .libs
+
+maintainer-clean-local: clean
+       cd $(srcdir) && rm -rf xml html $(DOC_MODULE)-decl-list.txt $(DOC_MODULE)-decl.txt
+
+# company: don't delete .sgml and -sections.txt as they're in CVS
+# FIXME : thomas added all sgml files and some other things to make
+# make distcheck work
+distclean-local: clean
+       rm -f $(DOC_MODULE)-decl-list.txt
+       rm -f $(DOC_MODULE)-decl.txt
+       rm -f $(REPORT_FILES)
+       rm -rf tmpl/*.sgml.bak
+       rm -f $(DOC_MODULE).hierarchy
+       rm -f *.stamp || true
+       if test x"$(srcdir)" != x. ; then \
+           rm -f $(DOC_MODULE)-docs.sgml ; \
+           rm -f $(DOC_MODULE).types ; \
+           rm -f $(DOC_MODULE).interfaces ; \
+            rm -f $(DOC_MODULE)-overrides.txt ; \
+           rm -f $(DOC_MODULE).prerequisites ; \
+           rm -f $(DOC_MODULE)-sections.txt ; \
+           rm -rf tmpl/*.sgml ; \
+       fi
+       rm -rf *.o
+
+# thomas: make docs parallel installable; devhelp requires majorminor too
+install-data-local:
+       $(mkinstalldirs) $(DESTDIR)$(TARGET_DIR) 
+       (installfiles=`echo ./html/*.html`; \
+       if test "$$installfiles" = './html/*.html'; \
+       then echo '-- Nothing to install' ; \
+       else \
+         for i in $$installfiles; do \
+           echo '-- Installing '$$i ; \
+           $(INSTALL_DATA) $$i $(DESTDIR)$(TARGET_DIR); \
+         done; \
+         pngfiles=`echo ./html/*.png`; \
+         if test "$$pngfiles" != './html/*.png'; then \
+           for i in $$pngfiles; do \
+             echo '-- Installing '$$i ; \
+             $(INSTALL_DATA) $$i $(DESTDIR)$(TARGET_DIR); \
+           done; \
+         fi; \
+         echo '-- Installing $(srcdir)/html/$(DOC_MODULE).devhelp' ; \
+         $(INSTALL_DATA) $(srcdir)/html/$(DOC_MODULE).devhelp \
+           $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp; \
+         if test -e $(srcdir)/html/$(DOC_MODULE).devhelp2; then \
+                 $(INSTALL_DATA) $(srcdir)/html/$(DOC_MODULE).devhelp2 \
+                  $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp2; \
+         fi; \
+         echo '-- Installing $(srcdir)/html/index.sgml' ; \
+         $(INSTALL_DATA) $(srcdir)/html/index.sgml $(DESTDIR)$(TARGET_DIR); \
+               if test -e $(srcdir)/html/style.css; then \
+                       echo '-- Installing $(srcdir)/html/style.css' ; \
+                       $(INSTALL_DATA) $(srcdir)/html/style.css $(DESTDIR)$(TARGET_DIR); \
+               fi; \
+       fi) 
+uninstall-local:
+       (installfiles=`echo ./html/*.html`; \
+       if test "$$installfiles" = './html/*.html'; \
+       then echo '-- Nothing to uninstall' ; \
+       else \
+         for i in $$installfiles; do \
+           rmfile=`basename $$i` ; \
+           echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/'$$rmfile ; \
+           rm -f $(DESTDIR)$(TARGET_DIR)/$$rmfile; \
+         done; \
+         pngfiles=`echo ./html/*.png`; \
+         if test "$$pngfiles" != './html/*.png'; then \
+           for i in $$pngfiles; do \
+             rmfile=`basename $$i` ; \
+             echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/'$$rmfile ; \
+             rm -f $(DESTDIR)$(TARGET_DIR)/$$rmfile; \
+           done; \
+         fi; \
+         echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE).devhelp' ; \
+         rm -f $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp; \
+         if test -e $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp2; then \
+           rm -f $(DESTDIR)$(TARGET_DIR)/$(DOC_MODULE)-@GST_MAJORMINOR@.devhelp2; \
+         fi; \
+         echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/index.sgml' ; \
+         rm -f $(DESTDIR)$(TARGET_DIR)/index.sgml; \
+               if test -e $(DESTDIR)$(TARGET_DIR)/style.css; then \
+                       echo '-- Uninstalling $(DESTDIR)$(TARGET_DIR)/style.css' ; \
+                       rm -f $(DESTDIR)$(TARGET_DIR)/style.css; \
+               fi; \
+       fi) 
+       if test -d $(DESTDIR)$(TARGET_DIR); then rmdir -p --ignore-fail-on-non-empty $(DESTDIR)$(TARGET_DIR) 2>/dev/null; fi; true
+
+#
+# Require gtk-doc when making dist
+#
+if ENABLE_GTK_DOC
+dist-check-gtkdoc:
+else
+dist-check-gtkdoc:
+       @echo "*** gtk-doc must be installed and enabled in order to make dist"
+       @false
+endif
+
+dist-hook: dist-check-gtkdoc dist-hook-local
+       mkdir $(distdir)/tmpl
+       mkdir $(distdir)/xml
+       mkdir $(distdir)/html
+       -cp $(srcdir)/tmpl/*.sgml $(distdir)/tmpl
+       -cp $(srcdir)/sgml/*.xml $(distdir)/xml
+       -cp $(srcdir)/html/index.sgml $(distdir)/html
+       -cp $(srcdir)/html/*.html $(srcdir)/html/*.css $(distdir)/html
+       -cp $(srcdir)/html/$(DOC_MODULE).devhelp* $(distdir)/html
+
+       images=$(HTML_IMAGES) ;               \
+       for i in "" $$images ; do                     \
+         if test "$$i" != ""; then cp $(srcdir)/$$i $(distdir)/html ; fi; \
+       done
+
+.PHONY : dist-hook-local
diff --git a/common/m4/Makefile.am b/common/m4/Makefile.am
new file mode 100644 (file)
index 0000000..99ead5c
--- /dev/null
@@ -0,0 +1,29 @@
+EXTRA_DIST = \
+       README \
+       as-ac-expand.m4 \
+       as-auto-alt.m4 \
+       as-compiler-flag.m4 \
+       as-compiler.m4 \
+       as-docbook.m4 \
+       as-gcc-inline-assembly.m4 \
+       as-libtool.m4 \
+       as-libtool-tags.m4 \
+       as-python.m4 \
+       as-scrub-include.m4 \
+       as-version.m4 \
+       ax_create_stdint_h.m4 \
+       glib-gettext.m4 \
+       gst-arch.m4 \
+       gst-args.m4 \
+       gst-check.m4 \
+       gst-debuginfo.m4 \
+       gst-default.m4 \
+       gst-doc.m4 \
+       gst-feature.m4 \
+       gst-function.m4 \
+       gst-gettext.m4 \
+       gst-glib2.m4 \
+       gst-libxml2.m4 \
+       gst-plugindir.m4 \
+       gst-valgrind.m4 \
+       pkg.m4
diff --git a/common/m4/README b/common/m4/README
new file mode 100755 (executable)
index 0000000..f044598
--- /dev/null
@@ -0,0 +1,3 @@
+All aclocal .m4 files we need are put here and cat'd to acinclude.m4 in 
+the source root.  Official ones (taken from the relevant devel packages) 
+are named as-is, unofficial ones (or changed ones) get a gst-prefix.
diff --git a/common/m4/as-ac-expand.m4 b/common/m4/as-ac-expand.m4
new file mode 100755 (executable)
index 0000000..d6c9e33
--- /dev/null
@@ -0,0 +1,43 @@
+dnl as-ac-expand.m4 0.2.0
+dnl autostars m4 macro for expanding directories using configure's prefix
+dnl thomas@apestaart.org
+
+dnl AS_AC_EXPAND(VAR, CONFIGURE_VAR)
+dnl example
+dnl AS_AC_EXPAND(SYSCONFDIR, $sysconfdir)
+dnl will set SYSCONFDIR to /usr/local/etc if prefix=/usr/local
+
+AC_DEFUN([AS_AC_EXPAND],
+[
+  EXP_VAR=[$1]
+  FROM_VAR=[$2]
+
+  dnl first expand prefix and exec_prefix if necessary
+  prefix_save=$prefix
+  exec_prefix_save=$exec_prefix
+
+  dnl if no prefix given, then use /usr/local, the default prefix
+  if test "x$prefix" = "xNONE"; then
+    prefix="$ac_default_prefix"
+  fi
+  dnl if no exec_prefix given, then use prefix
+  if test "x$exec_prefix" = "xNONE"; then
+    exec_prefix=$prefix
+  fi
+
+  full_var="$FROM_VAR"
+  dnl loop until it doesn't change anymore
+  while true; do
+    new_full_var="`eval echo $full_var`"
+    if test "x$new_full_var" = "x$full_var"; then break; fi
+    full_var=$new_full_var
+  done
+
+  dnl clean up
+  full_var=$new_full_var
+  AC_SUBST([$1], "$full_var")
+
+  dnl restore prefix and exec_prefix
+  prefix=$prefix_save
+  exec_prefix=$exec_prefix_save
+])
diff --git a/common/m4/as-auto-alt.m4 b/common/m4/as-auto-alt.m4
new file mode 100755 (executable)
index 0000000..3f7920d
--- /dev/null
@@ -0,0 +1,50 @@
+dnl as-auto-alt.m4 0.0.2
+dnl autostars m4 macro for supplying alternate autotools versions to configure
+dnl thomas@apestaart.org
+dnl
+dnl AS_AUTOTOOLS_ALTERNATE()
+dnl
+dnl supplies --with arguments for autoconf, autoheader, automake, aclocal
+
+AC_DEFUN([AS_AUTOTOOLS_ALTERNATE],
+[
+  dnl allow for different autoconf version
+  AC_ARG_WITH(autoconf,
+    AC_HELP_STRING([--with-autoconf],
+                   [use a different autoconf for regeneration of Makefiles]),
+    [
+      unset AUTOCONF
+      AM_MISSING_PROG(AUTOCONF, ${withval})
+      AC_MSG_NOTICE([Using $AUTOCONF as autoconf])
+    ])
+
+  dnl allow for different autoheader version
+  AC_ARG_WITH(autoheader,
+    AC_HELP_STRING([--with-autoheader],
+                   [use a different autoheader for regeneration of Makefiles]),
+    [
+      unset AUTOHEADER
+      AM_MISSING_PROG(AUTOHEADER, ${withval})
+      AC_MSG_NOTICE([Using $AUTOHEADER as autoheader])
+    ])
+
+  dnl allow for different automake version
+  AC_ARG_WITH(automake,
+    AC_HELP_STRING([--with-automake],
+                   [use a different automake for regeneration of Makefiles]),
+    [
+      unset AUTOMAKE
+      AM_MISSING_PROG(AUTOMAKE, ${withval})
+      AC_MSG_NOTICE([Using $AUTOMAKE as automake])
+    ])
+
+  dnl allow for different aclocal version
+  AC_ARG_WITH(aclocal,
+    AC_HELP_STRING([--with-aclocal],
+                   [use a different aclocal for regeneration of Makefiles]),
+    [
+      unset ACLOCAL
+      AM_MISSING_PROG(ACLOCAL, ${withval})
+      AC_MSG_NOTICE([Using $ACLOCAL as aclocal])
+    ])
+])
diff --git a/common/m4/as-compiler-flag.m4 b/common/m4/as-compiler-flag.m4
new file mode 100755 (executable)
index 0000000..882a4c7
--- /dev/null
@@ -0,0 +1,64 @@
+dnl as-compiler-flag.m4 0.1.0
+
+dnl autostars m4 macro for detection of compiler flags
+
+dnl David Schleef <ds@schleef.org>
+dnl Tim-Philipp Müller <tim centricular net>
+
+dnl AS_COMPILER_FLAG(CFLAGS, ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_COMPILER_FLAG],
+[
+  AC_MSG_CHECKING([to see if compiler understands $1])
+
+  save_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS $1"
+
+  AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no])
+  CFLAGS="$save_CFLAGS"
+
+  if test "X$flag_ok" = Xyes ; then
+    $2
+    true
+  else
+    $3
+    true
+  fi
+  AC_MSG_RESULT([$flag_ok])
+])
+
+dnl AS_CXX_COMPILER_FLAG(CPPFLAGS, ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CPPFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_CXX_COMPILER_FLAG],
+[
+  AC_REQUIRE([AC_PROG_CXX])
+
+  AC_MSG_CHECKING([to see if c++ compiler understands $1])
+
+  save_CPPFLAGS="$CPPFLAGS"
+  CPPFLAGS="$CPPFLAGS $1"
+
+  AC_LANG_PUSH(C++)
+
+  AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no])
+  CPPFLAGS="$save_CPPFLAGS"
+
+  if test "X$flag_ok" = Xyes ; then
+    $2
+    true
+  else
+    $3
+    true
+  fi
+
+  AC_LANG_POP(C++)
+
+  AC_MSG_RESULT([$flag_ok])
+])
+
diff --git a/common/m4/as-compiler.m4 b/common/m4/as-compiler.m4
new file mode 100755 (executable)
index 0000000..233a719
--- /dev/null
@@ -0,0 +1,44 @@
+dnl as-compiler.m4 0.1.0
+                                                                                
+dnl autostars m4 macro for detection of compiler flavor
+
+dnl Thomas Vander Stichele <thomas at apestaart dot org>
+
+dnl $Id: as-compiler.m4,v 1.4 2004/06/01 09:33:45 thomasvs Exp $
+                                                                                
+dnl AS_COMPILER(COMPILER)
+dnl will set variable COMPILER to
+dnl - gcc
+dnl - forte
+dnl - (empty) if no guess could be made
+
+AC_DEFUN([AS_COMPILER],
+[
+  as_compiler=
+  AC_MSG_CHECKING(for compiler flavour)
+
+  dnl is it gcc ?
+  if test "x$GCC" = "xyes"; then
+    as_compiler="gcc"
+  fi
+
+  dnl is it forte ?
+  AC_TRY_RUN([
+int main
+(int argc, char *argv[])
+{
+#ifdef __sun
+  return 0;
+#else
+  return 1;
+#endif
+}
+  ], as_compiler="forte", ,)
+
+  if test "x$as_compiler" = "x"; then
+    AC_MSG_RESULT([unknown !])
+  else
+    AC_MSG_RESULT($as_compiler)
+  fi
+  [$1]=$as_compiler
+])
diff --git a/common/m4/as-docbook.m4 b/common/m4/as-docbook.m4
new file mode 100755 (executable)
index 0000000..8a1b32a
--- /dev/null
@@ -0,0 +1,66 @@
+dnl AS_DOCBOOK([, ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]])
+dnl checks if xsltproc can build docbook documentation
+dnl (which is possible if the catalog is set up properly
+dnl I also tried checking for a specific version and type of docbook
+dnl but xsltproc seemed to happily run anyway, so we can't check for that
+dnl and version
+dnl this macro takes inspiration from
+dnl http://www.movement.uklinux.net/docs/docbook-autotools/configure.html
+AC_DEFUN([AS_DOCBOOK],
+[
+  XSLTPROC_FLAGS=--nonet
+  DOCBOOK_ROOT=
+  TYPE_LC=xml
+  TYPE_UC=XML
+  DOCBOOK_VERSION=4.1.2
+
+  if test ! -f /etc/xml/catalog; then
+    for i in /usr/share/sgml/docbook/stylesheet/xsl/nwalsh /usr/share/sgml/docbook/xsl-stylesheets/ /usr/local/share/xsl/docbook ;
+    do
+      if test -d "$i"; then
+        DOCBOOK_ROOT=$i
+      fi
+    done
+  else
+    XML_CATALOG=/etc/xml/catalog
+    CAT_ENTRY_START='<!--'
+    CAT_ENTRY_END='-->'
+  fi
+
+  dnl We need xsltproc to process the test
+  AC_CHECK_PROG(XSLTPROC,xsltproc,xsltproc,)
+  XSLTPROC_WORKS=no
+  if test -n "$XSLTPROC"; then
+    AC_MSG_CHECKING([whether xsltproc docbook processing works])
+
+    if test -n "$XML_CATALOG"; then
+      DB_FILE="http://docbook.sourceforge.net/release/xsl/current/xhtml/docbook.xsl"
+    else
+      DB_FILE="$DOCBOOK_ROOT/xhtml/docbook.xsl"
+    fi
+    $XSLTPROC $XSLTPROC_FLAGS $DB_FILE >/dev/null 2>&1 << END
+<?xml version="1.0" encoding='ISO-8859-1'?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook $TYPE_UC V$DOCBOOK_VERSION//EN" "http://www.oasis-open.org/docbook/$TYPE_LC/$DOCBOOK_VERSION/docbookx.dtd">
+<book id="test">
+</book>
+END
+    if test "$?" = 0; then
+      XSLTPROC_WORKS=yes
+    fi
+    AC_MSG_RESULT($XSLTPROC_WORKS)
+  fi
+
+  if test "x$XSLTPROC_WORKS" = "xyes"; then
+    dnl execute ACTION-IF-FOUND
+    ifelse([$1], , :, [$1])
+  else
+    dnl execute ACTION-IF-NOT-FOUND
+    ifelse([$2], , :, [$2])
+  fi
+
+  AC_SUBST(XML_CATALOG)
+  AC_SUBST(XSLTPROC_FLAGS)
+  AC_SUBST(DOCBOOK_ROOT)
+  AC_SUBST(CAT_ENTRY_START)
+  AC_SUBST(CAT_ENTRY_END)
+])
diff --git a/common/m4/as-gcc-inline-assembly.m4 b/common/m4/as-gcc-inline-assembly.m4
new file mode 100755 (executable)
index 0000000..799e80e
--- /dev/null
@@ -0,0 +1,52 @@
+dnl as-gcc-inline-assembly.m4 0.1.0
+
+dnl autostars m4 macro for detection of gcc inline assembly
+
+dnl David Schleef <ds@schleef.org>
+
+dnl $Id: as-gcc-inline-assembly.m4,v 1.1 2008-02-26 09:38:00 thaytan Exp $
+
+dnl AS_COMPILER_FLAG(ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_GCC_INLINE_ASSEMBLY],
+[
+  AC_MSG_CHECKING([if compiler supports gcc-style inline assembly])
+
+  AC_TRY_COMPILE([], [
+#ifdef __GNUC_MINOR__
+#if (__GNUC__ * 1000 + __GNUC_MINOR__) < 3004
+#error GCC before 3.4 has critical bugs compiling inline assembly
+#endif
+#endif
+__asm__ (""::) ], [flag_ok=yes], [flag_ok=no])
+
+  if test "X$flag_ok" = Xyes ; then
+    $1
+    true
+  else
+    $2
+    true
+  fi
+  AC_MSG_RESULT([$flag_ok])
+])
+
+
+AC_DEFUN([AS_GCC_ASM_POWERPC_FPU],
+[
+  AC_MSG_CHECKING([if compiler supports FPU instructions on PowerPC])
+
+  AC_TRY_COMPILE([], [__asm__ ("fadd 0,0,0"::) ], [flag_ok=yes], [flag_ok=no])
+
+  if test "X$flag_ok" = Xyes ; then
+    $1
+    true
+  else
+    $2
+    true
+  fi
+  AC_MSG_RESULT([$flag_ok])
+])
+
diff --git a/common/m4/as-libtool-tags.m4 b/common/m4/as-libtool-tags.m4
new file mode 100755 (executable)
index 0000000..c522ff2
--- /dev/null
@@ -0,0 +1,83 @@
+dnl as-libtool-tags.m4 0.1.4
+
+dnl autostars m4 macro for selecting libtool "tags" (languages)
+
+dnl Andy Wingo does not claim credit for this macro
+dnl backported from libtool 1.6 by Paolo Bonzini
+dnl see http://lists.gnu.org/archive/html/libtool/2003-12/msg00007.html
+
+dnl $Id: as-libtool-tags.m4,v 1.3 2006-04-01 15:30:56 thomasvs Exp $
+
+dnl AS_LIBTOOL_TAGS([tags...])
+
+dnl example
+dnl AS_LIBTOOL_TAGS([]) for only C (no fortran, etc)
+
+dnl When AC_LIBTOOL_TAGS is used, I redefine _LT_AC_TAGCONFIG
+dnl to be more similar to the libtool 1.6 implementation, which
+dnl uses an m4 loop and m4 case instead of a shell loop.  This
+dnl way the CXX/GCJ/F77/RC tests are not always expanded.
+
+dnl AS_LIBTOOL_TAGS
+dnl ---------------
+dnl tags to enable
+AC_DEFUN([AS_LIBTOOL_TAGS],
+[m4_define([_LT_TAGS],[$1])
+m4_define([_LT_AC_TAGCONFIG], [
+  # redefined LT AC TAGCONFIG
+  if test -f "$ltmain"; then
+    if test ! -f "${ofile}"; then
+      AC_MSG_WARN([output file `$ofile' does not exist])
+    fi
+
+    if test -z "$LTCC"; then
+      eval "`$SHELL ${ofile} --config | grep '^LTCC='`"
+      if test -z "$LTCC"; then
+        AC_MSG_WARN([output file `$ofile' does not look like a libtool script])
+      else
+        AC_MSG_WARN([using `LTCC=$LTCC', extracted from `$ofile'])
+      fi
+    fi
+
+    AC_FOREACH([_LT_TAG], _LT_TAGS,
+      echo THOMAS: tag _LT_TAG
+      [m4_case(_LT_TAG,
+      [CXX], [
+    if test -n "$CXX" && test "X$CXX" != "Xno"; then
+      echo "THOMAS: YAY CXX"
+      AC_LIBTOOL_LANG_CXX_CONFIG
+      available_tags="$available_tags _LT_TAG"
+    fi],
+      [F77], [
+    if test -n "$F77" && test "X$F77" != "Xno"; then
+      AC_LIBTOOL_LANG_F77_CONFIG
+      available_tags="$available_tags _LT_TAG"
+    fi],
+      [GCJ], [
+    if test -n "$GCJ" && test "X$GCJ" != "Xno"; then
+      AC_LIBTOOL_LANG_GCJ_CONFIG
+      available_tags="$available_tags _LT_TAG"
+    fi],
+      [RC], [
+    if test -n "$RC" && test "X$RC" != "Xno"; then
+      AC_LIBTOOL_LANG_RC_CONFIG
+      available_tags="$available_tags _LT_TAG"
+    fi],
+      [m4_errprintn(m4_location[: error: invalid tag name: ]"_LT_TAG")
+      m4_exit(1)])
+    ])
+    echo THOMAS: available tags: $available_tags
+  fi
+  # Now substitute the updated list of available tags.
+  if eval "sed -e 's/^available_tags=.*\$/available_tags=\"$available_tags\"/' \"$ofile\" > \"${ofile}T\""; then
+    mv "${ofile}T" "$ofile"
+    chmod +x "$ofile"
+    AC_MSG_NOTICE([updated available libtool tags with $available_tags.])
+  else
+    rm -f "${ofile}T"
+    AC_MSG_ERROR([unable to update list of available tagged configurations.])
+
+  fi
+
+])dnl _LT_AC_TAG_CONFIG
+])
diff --git a/common/m4/as-libtool.m4 b/common/m4/as-libtool.m4
new file mode 100755 (executable)
index 0000000..73dec1f
--- /dev/null
@@ -0,0 +1,45 @@
+dnl as-libtool.m4 0.1.4
+
+dnl autostars m4 macro for libtool versioning
+
+dnl Thomas Vander Stichele <thomas at apestaart dot org>
+
+dnl $Id: as-libtool.m4,v 1.6 2004/06/01 10:04:44 thomasvs Exp $
+
+dnl AS_LIBTOOL(PREFIX, CURRENT, REVISION, AGE, [RELEASE])
+
+dnl example
+dnl AS_LIBTOOL(GST, 2, 0, 0)
+
+dnl this macro
+dnl - defines [$PREFIX]_CURRENT, REVISION and AGE
+dnl - defines [$PREFIX]_LIBVERSION
+dnl - defines [$PREFIX]_LT_LDFLAGS to set versioning
+dnl - AC_SUBST's them all
+
+dnl if RELEASE is given, then add a -release option to the LDFLAGS
+dnl with the given release version
+dnl then use [$PREFIX]_LT_LDFLAGS in the relevant Makefile.am's
+
+dnl call AM_PROG_LIBTOOL after this call
+
+AC_DEFUN([AS_LIBTOOL],
+[
+  [$1]_CURRENT=[$2]
+  [$1]_REVISION=[$3]
+  [$1]_AGE=[$4]
+  [$1]_LIBVERSION=[$2]:[$3]:[$4]
+  AC_SUBST([$1]_CURRENT)
+  AC_SUBST([$1]_REVISION)
+  AC_SUBST([$1]_AGE)
+  AC_SUBST([$1]_LIBVERSION)
+
+  [$1]_LT_LDFLAGS="$[$1]_LT_LDFLAGS -version-info $[$1]_LIBVERSION"
+  if test ! -z "[$5]"
+  then
+    [$1]_LT_LDFLAGS="$[$1]_LT_LDFLAGS -release [$5]"
+  fi
+  AC_SUBST([$1]_LT_LDFLAGS)
+
+  AC_LIBTOOL_DLOPEN
+])
diff --git a/common/m4/as-python.m4 b/common/m4/as-python.m4
new file mode 100755 (executable)
index 0000000..eb9b175
--- /dev/null
@@ -0,0 +1,152 @@
+## ------------------------
+## Python file handling
+## From Andrew Dalke
+## Updated by James Henstridge
+## Updated by Andy Wingo to loop through possible pythons
+## ------------------------
+
+# AS_PATH_PYTHON([MINIMUM-VERSION])
+
+# Adds support for distributing Python modules and packages.  To
+# install modules, copy them to $(pythondir), using the python_PYTHON
+# automake variable.  To install a package with the same name as the
+# automake package, install to $(pkgpythondir), or use the
+# pkgpython_PYTHON automake variable.
+
+# The variables $(pyexecdir) and $(pkgpyexecdir) are provided as
+# locations to install python extension modules (shared libraries).
+# Another macro is required to find the appropriate flags to compile
+# extension modules.
+
+# If your package is configured with a different prefix to python,
+# users will have to add the install directory to the PYTHONPATH
+# environment variable, or create a .pth file (see the python
+# documentation for details).
+
+# If the MINIMUM-VERSION argument is passed, AS_PATH_PYTHON will
+# cause an error if the version of python installed on the system
+# doesn't meet the requirement.  MINIMUM-VERSION should consist of
+# numbers and dots only.
+
+# Updated to loop over all possible python binaries by Andy Wingo
+# <wingo@pobox.com>
+# Updated to only warn and unset PYTHON if no good one is found
+
+AC_DEFUN([AS_PATH_PYTHON],
+ [
+  dnl Find a version of Python.  I could check for python versions 1.4
+  dnl or earlier, but the default installation locations changed from
+  dnl $prefix/lib/site-python in 1.4 to $prefix/lib/python1.5/site-packages
+  dnl in 1.5, and I don't want to maintain that logic.
+
+  dnl should we do the version check?
+  PYTHON_CANDIDATES="python python2.2 python2.1 python2.0 python2 \
+                     python1.6 python1.5"
+  ifelse([$1],[],
+         [AC_PATH_PROG(PYTHON, $PYTHON_CANDIDATES)],
+         [
+     AC_MSG_NOTICE(Looking for Python version >= $1)
+    changequote(<<, >>)dnl
+    prog="
+import sys, string
+minver = '$1'
+# split string by '.' and convert to numeric
+minver_info = map(string.atoi, string.split(minver, '.'))
+# we can now do comparisons on the two lists:
+if sys.version_info >= tuple(minver_info):
+       sys.exit(0)
+else:
+       sys.exit(1)"
+    changequote([, ])dnl
+
+    python_good=false
+    for python_candidate in $PYTHON_CANDIDATES; do
+      unset PYTHON
+      AC_PATH_PROG(PYTHON, $python_candidate) 1> /dev/null 2> /dev/null
+
+      if test "x$PYTHON" = "x"; then continue; fi
+
+      if $PYTHON -c "$prog" 1>&AC_FD_CC 2>&AC_FD_CC; then
+        AC_MSG_CHECKING(["$PYTHON":])
+       AC_MSG_RESULT([okay])
+        python_good=true
+        break;
+      else
+        dnl clear the cache val
+        unset ac_cv_path_PYTHON
+      fi
+    done
+  ])
+
+  if test "$python_good" != "true"; then
+    AC_MSG_WARN([No suitable version of python found])
+    PYTHON=
+  else
+
+  AC_MSG_CHECKING([local Python configuration])
+
+  dnl Query Python for its version number.  Getting [:3] seems to be
+  dnl the best way to do this; it's what "site.py" does in the standard
+  dnl library.  Need to change quote character because of [:3]
+
+  AC_SUBST(PYTHON_VERSION)
+  changequote(<<, >>)dnl
+  PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+  changequote([, ])dnl
+
+
+  dnl Use the values of $prefix and $exec_prefix for the corresponding
+  dnl values of PYTHON_PREFIX and PYTHON_EXEC_PREFIX.  These are made
+  dnl distinct variables so they can be overridden if need be.  However,
+  dnl general consensus is that you shouldn't need this ability.
+
+  AC_SUBST(PYTHON_PREFIX)
+  PYTHON_PREFIX='${prefix}'
+
+  AC_SUBST(PYTHON_EXEC_PREFIX)
+  PYTHON_EXEC_PREFIX='${exec_prefix}'
+
+  dnl At times (like when building shared libraries) you may want
+  dnl to know which OS platform Python thinks this is.
+
+  AC_SUBST(PYTHON_PLATFORM)
+  PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+
+
+  dnl Set up 4 directories:
+
+  dnl pythondir -- where to install python scripts.  This is the
+  dnl   site-packages directory, not the python standard library
+  dnl   directory like in previous automake betas.  This behaviour
+  dnl   is more consistent with lispdir.m4 for example.
+  dnl
+  dnl Also, if the package prefix isn't the same as python's prefix,
+  dnl then the old $(pythondir) was pretty useless.
+
+  AC_SUBST(pythondir)
+  pythondir=$PYTHON_PREFIX"/lib/python"$PYTHON_VERSION/site-packages
+
+  dnl pkgpythondir -- $PACKAGE directory under pythondir.  Was
+  dnl   PYTHON_SITE_PACKAGE in previous betas, but this naming is
+  dnl   more consistent with the rest of automake.
+  dnl   Maybe this should be put in python.am?
+
+  AC_SUBST(pkgpythondir)
+  pkgpythondir=\${pythondir}/$PACKAGE
+
+  dnl pyexecdir -- directory for installing python extension modules
+  dnl   (shared libraries)  Was PYTHON_SITE_EXEC in previous betas.
+
+  AC_SUBST(pyexecdir)
+  pyexecdir=$PYTHON_EXEC_PREFIX"/lib/python"$PYTHON_VERSION/site-packages
+
+  dnl pkgpyexecdir -- $(pyexecdir)/$(PACKAGE)
+  dnl   Maybe this should be put in python.am?
+
+  AC_SUBST(pkgpyexecdir)
+  pkgpyexecdir=\${pyexecdir}/$PACKAGE
+
+  AC_MSG_RESULT([looks good])
+
+  fi
+])
diff --git a/common/m4/as-scrub-include.m4 b/common/m4/as-scrub-include.m4
new file mode 100755 (executable)
index 0000000..96dfb8f
--- /dev/null
@@ -0,0 +1,36 @@
+dnl as-scrub-include.m4 0.0.4
+
+dnl autostars m4 macro for scrubbing CFLAGS of system include dirs
+dnl because gcc 3.x complains about including system including dirs
+
+dnl Thomas Vander Stichele <thomas at apestaart dot org>
+
+dnl $Id: as-scrub-include.m4,v 1.5 2004/06/12 08:19:09 thomasvs Exp $
+
+dnl This macro uses output of cpp -v and expects it to contain text that 
+dnl looks a little bit like this:
+dnl #include <...> search starts here:
+dnl  /usr/local/include
+dnl  /usr/lib/gcc-lib/i386-redhat-linux/3.2/include
+dnl  /usr/include
+dnl End of search list.
+
+dnl AS_SCRUB_INCLUDE(VAR)
+dnl example
+dnl AS_SCRUB_INCLUDE(CFLAGS)
+dnl will remove all system include dirs from the given CFLAGS
+
+AC_DEFUN([AS_SCRUB_INCLUDE],
+[
+  GIVEN_CFLAGS=$[$1]
+  INCLUDE_DIRS=`echo | cpp -v 2>&1`
+
+  dnl remove everything from this output between the "starts here" and "End of"
+  dnl line
+  INCLUDE_DIRS=`echo $INCLUDE_DIRS | sed -e 's/.*<...> search starts here://' | sed -e 's/End of search list.*//'`
+  for dir in $INCLUDE_DIRS; do
+    dnl use "" as the sed script so $dir gets expanded
+    GIVEN_CFLAGS=`echo $GIVEN_CFLAGS | sed -e "s#-I$dir ##"`
+  done
+  [$1]=$GIVEN_CFLAGS
+])
diff --git a/common/m4/as-version.m4 b/common/m4/as-version.m4
new file mode 100755 (executable)
index 0000000..a5b4399
--- /dev/null
@@ -0,0 +1,71 @@
+dnl as-version.m4 0.2.0
+
+dnl autostars m4 macro for versioning
+
+dnl Thomas Vander Stichele <thomas at apestaart dot org>
+
+dnl $Id: as-version.m4,v 1.4 2004/06/01 09:40:05 thomasvs Exp $
+
+dnl AS_VERSION
+
+dnl example
+dnl AS_VERSION
+
+dnl this macro
+dnl - AC_SUBST's PACKAGE_VERSION_MAJOR, _MINOR, _MICRO
+dnl - AC_SUBST's PACKAGE_VERSION_RELEASE,
+dnl    which can be used for rpm release fields
+dnl - doesn't call AM_INIT_AUTOMAKE anymore because it prevents
+dnl   maintainer mode from running correctly
+dnl
+dnl don't forget to put #undef PACKAGE_VERSION_RELEASE in acconfig.h
+dnl if you use acconfig.h
+
+AC_DEFUN([AS_VERSION],
+[
+  PACKAGE_VERSION_MAJOR=$(echo AC_PACKAGE_VERSION | cut -d'.' -f1)
+  PACKAGE_VERSION_MINOR=$(echo AC_PACKAGE_VERSION | cut -d'.' -f2)
+  PACKAGE_VERSION_MICRO=$(echo AC_PACKAGE_VERSION | cut -d'.' -f3)
+
+  AC_SUBST(PACKAGE_VERSION_MAJOR)
+  AC_SUBST(PACKAGE_VERSION_MINOR)
+  AC_SUBST(PACKAGE_VERSION_MICRO)
+])
+
+dnl AS_NANO(ACTION-IF-NO-NANO, [ACTION-IF-NANO])
+
+dnl requires AC_INIT to be called before
+dnl For projects using a fourth or nano number in your versioning to indicate
+dnl development or prerelease snapshots, this macro allows the build to be
+dnl set up differently accordingly.
+
+dnl this macro:
+dnl - parses AC_PACKAGE_VERSION, set by AC_INIT, and extracts the nano number
+dnl - sets the variable PACKAGE_VERSION_NANO
+dnl - sets the variable PACKAGE_VERSION_RELEASE, which can be used
+dnl   for rpm release fields
+dnl - executes ACTION-IF-NO-NANO or ACTION-IF-NANO
+    
+dnl example:
+dnl AS_NANO(RELEASE="yes", RELEASE="no")
+
+AC_DEFUN([AS_NANO],
+[
+  AC_MSG_CHECKING(nano version)
+
+  NANO=$(echo AC_PACKAGE_VERSION | cut -d'.' -f4)
+
+  if test x"$NANO" = x || test "x$NANO" = "x0" ; then
+    AC_MSG_RESULT([0 (release)])
+    NANO=0
+    PACKAGE_VERSION_RELEASE=1
+    ifelse([$1], , :, [$1])
+  else
+    AC_MSG_RESULT($NANO)
+    PACKAGE_VERSION_RELEASE=0.`date +%Y%m%d.%H%M%S`
+    ifelse([$2], , :, [$2])
+  fi
+  PACKAGE_VERSION_NANO=$NANO
+  AC_SUBST(PACKAGE_VERSION_NANO)
+  AC_SUBST(PACKAGE_VERSION_RELEASE)
+])
diff --git a/common/m4/ax_create_stdint_h.m4 b/common/m4/ax_create_stdint_h.m4
new file mode 100755 (executable)
index 0000000..13bf699
--- /dev/null
@@ -0,0 +1,734 @@
+##### http://autoconf-archive.cryp.to/ax_create_stdint_h.html
+#
+# SYNOPSIS
+#
+#   AX_CREATE_STDINT_H [( HEADER-TO-GENERATE [, HEDERS-TO-CHECK])]
+#
+# DESCRIPTION
+#
+#   the "ISO C9X: 7.18 Integer types <stdint.h>" section requires the
+#   existence of an include file <stdint.h> that defines a set of
+#   typedefs, especially uint8_t,int32_t,uintptr_t. Many older
+#   installations will not provide this file, but some will have the
+#   very same definitions in <inttypes.h>. In other enviroments we can
+#   use the inet-types in <sys/types.h> which would define the typedefs
+#   int8_t and u_int8_t respectivly.
+#
+#   This macros will create a local "_stdint.h" or the headerfile given
+#   as an argument. In many cases that file will just "#include
+#   <stdint.h>" or "#include <inttypes.h>", while in other environments
+#   it will provide the set of basic 'stdint's definitions/typedefs:
+#
+#     int8_t,uint8_t,int16_t,uint16_t,int32_t,uint32_t,intptr_t,uintptr_t
+#     int_least32_t.. int_fast32_t.. intmax_t
+#
+#   which may or may not rely on the definitions of other files, or
+#   using the AC_CHECK_SIZEOF macro to determine the actual sizeof each
+#   type.
+#
+#   if your header files require the stdint-types you will want to
+#   create an installable file mylib-int.h that all your other
+#   installable header may include. So if you have a library package
+#   named "mylib", just use
+#
+#        AX_CREATE_STDINT_H(mylib-int.h)
+#
+#   in configure.ac and go to install that very header file in
+#   Makefile.am along with the other headers (mylib.h) - and the
+#   mylib-specific headers can simply use "#include <mylib-int.h>" to
+#   obtain the stdint-types.
+#
+#   Remember, if the system already had a valid <stdint.h>, the
+#   generated file will include it directly. No need for fuzzy
+#   HAVE_STDINT_H things... (oops, GCC 4.2.x has deliberatly disabled
+#   its stdint.h for non-c99 compilation and the c99-mode is not the
+#   default. Therefore this macro will not use the compiler's stdint.h
+#   - please complain to the GCC developers).
+#
+# LAST MODIFICATION
+#
+#   2007-06-27
+#
+# COPYLEFT
+#
+#   Copyright (c) 2007 Guido U. Draheim <guidod@gmx.de>
+#
+#   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 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, write to the Free Software
+#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+#   02111-1307, USA.
+#
+#   As a special exception, the respective Autoconf Macro's copyright
+#   owner gives unlimited permission to copy, distribute and modify the
+#   configure scripts that are the output of Autoconf when processing
+#   the Macro. You need not follow the terms of the GNU General Public
+#   License when using or distributing such scripts, even though
+#   portions of the text of the Macro appear in them. The GNU General
+#   Public License (GPL) does govern all other use of the material that
+#   constitutes the Autoconf Macro.
+#
+#   This special exception to the GPL applies to versions of the
+#   Autoconf Macro released by the Autoconf Macro Archive. When you
+#   make and distribute a modified version of the Autoconf Macro, you
+#   may extend this special exception to the GPL to apply to your
+#   modified version as well.
+
+AC_DEFUN([AX_CHECK_DATA_MODEL],[
+   AC_CHECK_SIZEOF(char)
+   AC_CHECK_SIZEOF(short)
+   AC_CHECK_SIZEOF(int)
+   AC_CHECK_SIZEOF(long)
+   AC_CHECK_SIZEOF(void*)
+   ac_cv_char_data_model=""
+   ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_char"
+   ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_short"
+   ac_cv_char_data_model="$ac_cv_char_data_model$ac_cv_sizeof_int"
+   ac_cv_long_data_model=""
+   ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_int"
+   ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_long"
+   ac_cv_long_data_model="$ac_cv_long_data_model$ac_cv_sizeof_voidp"
+   AC_MSG_CHECKING([data model])
+   case "$ac_cv_char_data_model/$ac_cv_long_data_model" in
+    122/242)     ac_cv_data_model="IP16"  ; n="standard 16bit machine" ;;
+    122/244)     ac_cv_data_model="LP32"  ; n="standard 32bit machine" ;;
+    122/*)       ac_cv_data_model="i16"   ; n="unusual int16 model" ;;
+    124/444)     ac_cv_data_model="ILP32" ; n="standard 32bit unixish" ;;
+    124/488)     ac_cv_data_model="LP64"  ; n="standard 64bit unixish" ;;
+    124/448)     ac_cv_data_model="LLP64" ; n="unusual 64bit unixish" ;;
+    124/*)       ac_cv_data_model="i32"   ; n="unusual int32 model" ;;
+    128/888)     ac_cv_data_model="ILP64" ; n="unusual 64bit numeric" ;;
+    128/*)       ac_cv_data_model="i64"   ; n="unusual int64 model" ;;
+    222/*2)      ac_cv_data_model="DSP16" ; n="strict 16bit dsptype" ;;
+    333/*3)      ac_cv_data_model="DSP24" ; n="strict 24bit dsptype" ;;
+    444/*4)      ac_cv_data_model="DSP32" ; n="strict 32bit dsptype" ;;
+    666/*6)      ac_cv_data_model="DSP48" ; n="strict 48bit dsptype" ;;
+    888/*8)      ac_cv_data_model="DSP64" ; n="strict 64bit dsptype" ;;
+    222/*|333/*|444/*|666/*|888/*) :
+                 ac_cv_data_model="iDSP"  ; n="unusual dsptype" ;;
+     *)          ac_cv_data_model="none"  ; n="very unusual model" ;;
+   esac
+   AC_MSG_RESULT([$ac_cv_data_model ($ac_cv_long_data_model, $n)])
+])
+
+dnl AX_CHECK_HEADER_STDINT_X([HEADERLIST][,ACTION-IF])
+AC_DEFUN([AX_CHECK_HEADER_STDINT_X],[
+AC_CACHE_CHECK([for stdint uintptr_t], [ac_cv_header_stdint_x],[
+ ac_cv_header_stdint_x="" # the 1997 typedefs (inttypes.h)
+  AC_MSG_RESULT([(..)])
+  for i in m4_ifval([$1],[$1],[stdint.h inttypes.h sys/inttypes.h sys/types.h])
+  do
+   unset ac_cv_type_uintptr_t
+   unset ac_cv_type_uint64_t
+   AC_CHECK_TYPE(uintptr_t,[ac_cv_header_stdint_x=$i],continue,[#include <$i>])
+   AC_CHECK_TYPE(uint64_t,[and64="/uint64_t"],[and64=""],[#include<$i>])
+   m4_ifvaln([$2],[$2]) break
+  done
+  AC_MSG_CHECKING([for stdint uintptr_t])
+ ])
+])
+
+AC_DEFUN([AX_CHECK_HEADER_STDINT_O],[
+AC_CACHE_CHECK([for stdint uint32_t], [ac_cv_header_stdint_o],[
+ ac_cv_header_stdint_o="" # the 1995 typedefs (sys/inttypes.h)
+  AC_MSG_RESULT([(..)])
+  for i in m4_ifval([$1],[$1],[inttypes.h sys/inttypes.h sys/types.h stdint.h])
+  do
+   unset ac_cv_type_uint32_t
+   unset ac_cv_type_uint64_t
+   AC_CHECK_TYPE(uint32_t,[ac_cv_header_stdint_o=$i],continue,[#include <$i>])
+   AC_CHECK_TYPE(uint64_t,[and64="/uint64_t"],[and64=""],[#include<$i>])
+   m4_ifvaln([$2],[$2]) break
+   break;
+  done
+  AC_MSG_CHECKING([for stdint uint32_t])
+ ])
+])
+
+AC_DEFUN([AX_CHECK_HEADER_STDINT_U],[
+AC_CACHE_CHECK([for stdint u_int32_t], [ac_cv_header_stdint_u],[
+ ac_cv_header_stdint_u="" # the BSD typedefs (sys/types.h)
+  AC_MSG_RESULT([(..)])
+  for i in m4_ifval([$1],[$1],[sys/types.h inttypes.h sys/inttypes.h]) ; do
+   unset ac_cv_type_u_int32_t
+   unset ac_cv_type_u_int64_t
+   AC_CHECK_TYPE(u_int32_t,[ac_cv_header_stdint_u=$i],continue,[#include <$i>])
+   AC_CHECK_TYPE(u_int64_t,[and64="/u_int64_t"],[and64=""],[#include<$i>])
+   m4_ifvaln([$2],[$2]) break
+   break;
+  done
+  AC_MSG_CHECKING([for stdint u_int32_t])
+ ])
+])
+
+AC_DEFUN([AX_CREATE_STDINT_H],
+[# ------ AX CREATE STDINT H -------------------------------------
+AC_MSG_CHECKING([for stdint types])
+ac_stdint_h=`echo ifelse($1, , _stdint.h, $1)`
+# try to shortcircuit - if the default include path of the compiler
+# can find a "stdint.h" header then we assume that all compilers can.
+AC_CACHE_VAL([ac_cv_header_stdint_t],[
+old_CXXFLAGS="$CXXFLAGS" ; CXXFLAGS=""
+old_CPPFLAGS="$CPPFLAGS" ; CPPFLAGS=""
+old_CFLAGS="$CFLAGS"     ; CFLAGS=""
+AC_TRY_COMPILE([#include <stdint.h>],[int_least32_t v = 0;],
+[ac_cv_stdint_result="(assuming C99 compatible system)"
+ ac_cv_header_stdint_t="stdint.h"; ],
+[ac_cv_header_stdint_t=""])
+if test "$GCC" = "yes" && test ".$ac_cv_header_stdint_t" = "."; then
+CFLAGS="-std=c99"
+AC_TRY_COMPILE([#include <stdint.h>],[int_least32_t v = 0;],
+[AC_MSG_WARN(your GCC compiler has a defunct stdint.h for its default-mode)])
+fi
+CXXFLAGS="$old_CXXFLAGS"
+CPPFLAGS="$old_CPPFLAGS"
+CFLAGS="$old_CFLAGS" ])
+
+v="... $ac_cv_header_stdint_h"
+if test "$ac_stdint_h" = "stdint.h" ; then
+ AC_MSG_RESULT([(are you sure you want them in ./stdint.h?)])
+elif test "$ac_stdint_h" = "inttypes.h" ; then
+ AC_MSG_RESULT([(are you sure you want them in ./inttypes.h?)])
+elif test "_$ac_cv_header_stdint_t" = "_" ; then
+ AC_MSG_RESULT([(putting them into $ac_stdint_h)$v])
+else
+ ac_cv_header_stdint="$ac_cv_header_stdint_t"
+ AC_MSG_RESULT([$ac_cv_header_stdint (shortcircuit)])
+fi
+
+if test "_$ac_cv_header_stdint_t" = "_" ; then # can not shortcircuit..
+
+dnl .....intro message done, now do a few system checks.....
+dnl btw, all old CHECK_TYPE macros do automatically "DEFINE" a type,
+dnl therefore we use the autoconf implementation detail CHECK_TYPE_NEW
+dnl instead that is triggered with 3 or more arguments (see types.m4)
+
+inttype_headers=`echo $2 | sed -e 's/,/ /g'`
+
+ac_cv_stdint_result="(no helpful system typedefs seen)"
+AX_CHECK_HEADER_STDINT_X(dnl
+   stdint.h inttypes.h sys/inttypes.h $inttype_headers,
+   ac_cv_stdint_result="(seen uintptr_t$and64 in $i)")
+
+if test "_$ac_cv_header_stdint_x" = "_" ; then
+AX_CHECK_HEADER_STDINT_O(dnl,
+   inttypes.h sys/inttypes.h stdint.h $inttype_headers,
+   ac_cv_stdint_result="(seen uint32_t$and64 in $i)")
+fi
+
+if test "_$ac_cv_header_stdint_x" = "_" ; then
+if test "_$ac_cv_header_stdint_o" = "_" ; then
+AX_CHECK_HEADER_STDINT_U(dnl,
+   sys/types.h inttypes.h sys/inttypes.h $inttype_headers,
+   ac_cv_stdint_result="(seen u_int32_t$and64 in $i)")
+fi fi
+
+dnl if there was no good C99 header file, do some typedef checks...
+if test "_$ac_cv_header_stdint_x" = "_" ; then
+   AC_MSG_CHECKING([for stdint datatype model])
+   AC_MSG_RESULT([(..)])
+   AX_CHECK_DATA_MODEL
+fi
+
+if test "_$ac_cv_header_stdint_x" != "_" ; then
+   ac_cv_header_stdint="$ac_cv_header_stdint_x"
+elif  test "_$ac_cv_header_stdint_o" != "_" ; then
+   ac_cv_header_stdint="$ac_cv_header_stdint_o"
+elif  test "_$ac_cv_header_stdint_u" != "_" ; then
+   ac_cv_header_stdint="$ac_cv_header_stdint_u"
+else
+   ac_cv_header_stdint="stddef.h"
+fi
+
+AC_MSG_CHECKING([for extra inttypes in chosen header])
+AC_MSG_RESULT([($ac_cv_header_stdint)])
+dnl see if int_least and int_fast types are present in _this_ header.
+unset ac_cv_type_int_least32_t
+unset ac_cv_type_int_fast32_t
+AC_CHECK_TYPE(int_least32_t,,,[#include <$ac_cv_header_stdint>])
+AC_CHECK_TYPE(int_fast32_t,,,[#include<$ac_cv_header_stdint>])
+AC_CHECK_TYPE(intmax_t,,,[#include <$ac_cv_header_stdint>])
+
+fi # shortcircut to system "stdint.h"
+# ------------------ PREPARE VARIABLES ------------------------------
+if test "$GCC" = "yes" ; then
+ac_cv_stdint_message="using gnu compiler "`$CC --version | head -1`
+else
+ac_cv_stdint_message="using $CC"
+fi
+
+AC_MSG_RESULT([make use of $ac_cv_header_stdint in $ac_stdint_h dnl
+$ac_cv_stdint_result])
+
+dnl -----------------------------------------------------------------
+# ----------------- DONE inttypes.h checks START header -------------
+AC_CONFIG_COMMANDS([$ac_stdint_h],[
+AC_MSG_NOTICE(creating $ac_stdint_h : $_ac_stdint_h)
+ac_stdint=$tmp/_stdint.h
+
+echo "#ifndef" $_ac_stdint_h >$ac_stdint
+echo "#define" $_ac_stdint_h "1" >>$ac_stdint
+echo "#ifndef" _GENERATED_STDINT_H >>$ac_stdint
+echo "#define" _GENERATED_STDINT_H '"'$PACKAGE $VERSION'"' >>$ac_stdint
+echo "/* generated $ac_cv_stdint_message */" >>$ac_stdint
+if test "_$ac_cv_header_stdint_t" != "_" ; then
+echo "#define _STDINT_HAVE_STDINT_H" "1" >>$ac_stdint
+echo "#include <stdint.h>" >>$ac_stdint
+echo "#endif" >>$ac_stdint
+echo "#endif" >>$ac_stdint
+else
+
+cat >>$ac_stdint <<STDINT_EOF
+
+/* ................... shortcircuit part ........................... */
+
+#if defined HAVE_STDINT_H || defined _STDINT_HAVE_STDINT_H
+#include <stdint.h>
+#else
+#include <stddef.h>
+
+/* .................... configured part ............................ */
+
+STDINT_EOF
+
+echo "/* whether we have a C99 compatible stdint header file */" >>$ac_stdint
+if test "_$ac_cv_header_stdint_x" != "_" ; then
+  ac_header="$ac_cv_header_stdint_x"
+  echo "#define _STDINT_HEADER_INTPTR" '"'"$ac_header"'"' >>$ac_stdint
+else
+  echo "/* #undef _STDINT_HEADER_INTPTR */" >>$ac_stdint
+fi
+
+echo "/* whether we have a C96 compatible inttypes header file */" >>$ac_stdint
+if  test "_$ac_cv_header_stdint_o" != "_" ; then
+  ac_header="$ac_cv_header_stdint_o"
+  echo "#define _STDINT_HEADER_UINT32" '"'"$ac_header"'"' >>$ac_stdint
+else
+  echo "/* #undef _STDINT_HEADER_UINT32 */" >>$ac_stdint
+fi
+
+echo "/* whether we have a BSD compatible inet types header */" >>$ac_stdint
+if  test "_$ac_cv_header_stdint_u" != "_" ; then
+  ac_header="$ac_cv_header_stdint_u"
+  echo "#define _STDINT_HEADER_U_INT32" '"'"$ac_header"'"' >>$ac_stdint
+else
+  echo "/* #undef _STDINT_HEADER_U_INT32 */" >>$ac_stdint
+fi
+
+echo "" >>$ac_stdint
+
+if test "_$ac_header" != "_" ; then if test "$ac_header" != "stddef.h" ; then
+  echo "#include <$ac_header>" >>$ac_stdint
+  echo "" >>$ac_stdint
+fi fi
+
+echo "/* which 64bit typedef has been found */" >>$ac_stdint
+if test "$ac_cv_type_uint64_t" = "yes" ; then
+echo "#define   _STDINT_HAVE_UINT64_T" "1"  >>$ac_stdint
+else
+echo "/* #undef _STDINT_HAVE_UINT64_T */" >>$ac_stdint
+fi
+if test "$ac_cv_type_u_int64_t" = "yes" ; then
+echo "#define   _STDINT_HAVE_U_INT64_T" "1"  >>$ac_stdint
+else
+echo "/* #undef _STDINT_HAVE_U_INT64_T */" >>$ac_stdint
+fi
+echo "" >>$ac_stdint
+
+echo "/* which type model has been detected */" >>$ac_stdint
+if test "_$ac_cv_char_data_model" != "_" ; then
+echo "#define   _STDINT_CHAR_MODEL" "$ac_cv_char_data_model" >>$ac_stdint
+echo "#define   _STDINT_LONG_MODEL" "$ac_cv_long_data_model" >>$ac_stdint
+else
+echo "/* #undef _STDINT_CHAR_MODEL // skipped */" >>$ac_stdint
+echo "/* #undef _STDINT_LONG_MODEL // skipped */" >>$ac_stdint
+fi
+echo "" >>$ac_stdint
+
+echo "/* whether int_least types were detected */" >>$ac_stdint
+if test "$ac_cv_type_int_least32_t" = "yes"; then
+echo "#define   _STDINT_HAVE_INT_LEAST32_T" "1"  >>$ac_stdint
+else
+echo "/* #undef _STDINT_HAVE_INT_LEAST32_T */" >>$ac_stdint
+fi
+echo "/* whether int_fast types were detected */" >>$ac_stdint
+if test "$ac_cv_type_int_fast32_t" = "yes"; then
+echo "#define   _STDINT_HAVE_INT_FAST32_T" "1" >>$ac_stdint
+else
+echo "/* #undef _STDINT_HAVE_INT_FAST32_T */" >>$ac_stdint
+fi
+echo "/* whether intmax_t type was detected */" >>$ac_stdint
+if test "$ac_cv_type_intmax_t" = "yes"; then
+echo "#define   _STDINT_HAVE_INTMAX_T" "1" >>$ac_stdint
+else
+echo "/* #undef _STDINT_HAVE_INTMAX_T */" >>$ac_stdint
+fi
+echo "" >>$ac_stdint
+
+  cat >>$ac_stdint <<STDINT_EOF
+/* .................... detections part ............................ */
+
+/* whether we need to define bitspecific types from compiler base types */
+#ifndef _STDINT_HEADER_INTPTR
+#ifndef _STDINT_HEADER_UINT32
+#ifndef _STDINT_HEADER_U_INT32
+#define _STDINT_NEED_INT_MODEL_T
+#else
+#define _STDINT_HAVE_U_INT_TYPES
+#endif
+#endif
+#endif
+
+#ifdef _STDINT_HAVE_U_INT_TYPES
+#undef _STDINT_NEED_INT_MODEL_T
+#endif
+
+#ifdef  _STDINT_CHAR_MODEL
+#if     _STDINT_CHAR_MODEL+0 == 122 || _STDINT_CHAR_MODEL+0 == 124
+#ifndef _STDINT_BYTE_MODEL
+#define _STDINT_BYTE_MODEL 12
+#endif
+#endif
+#endif
+
+#ifndef _STDINT_HAVE_INT_LEAST32_T
+#define _STDINT_NEED_INT_LEAST_T
+#endif
+
+#ifndef _STDINT_HAVE_INT_FAST32_T
+#define _STDINT_NEED_INT_FAST_T
+#endif
+
+#ifndef _STDINT_HEADER_INTPTR
+#define _STDINT_NEED_INTPTR_T
+#ifndef _STDINT_HAVE_INTMAX_T
+#define _STDINT_NEED_INTMAX_T
+#endif
+#endif
+
+
+/* .................... definition part ............................ */
+
+/* some system headers have good uint64_t */
+#ifndef _HAVE_UINT64_T
+#if     defined _STDINT_HAVE_UINT64_T  || defined HAVE_UINT64_T
+#define _HAVE_UINT64_T
+#elif   defined _STDINT_HAVE_U_INT64_T || defined HAVE_U_INT64_T
+#define _HAVE_UINT64_T
+typedef u_int64_t uint64_t;
+#endif
+#endif
+
+#ifndef _HAVE_UINT64_T
+/* .. here are some common heuristics using compiler runtime specifics */
+#if defined __STDC_VERSION__ && defined __STDC_VERSION__ >= 199901L
+#define _HAVE_UINT64_T
+#define _HAVE_LONGLONG_UINT64_T
+typedef long long int64_t;
+typedef unsigned long long uint64_t;
+
+#elif !defined __STRICT_ANSI__
+#if defined _MSC_VER || defined __WATCOMC__ || defined __BORLANDC__
+#define _HAVE_UINT64_T
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+
+#elif defined __GNUC__ || defined __MWERKS__ || defined __ELF__
+/* note: all ELF-systems seem to have loff-support which needs 64-bit */
+#if !defined _NO_LONGLONG
+#define _HAVE_UINT64_T
+#define _HAVE_LONGLONG_UINT64_T
+typedef long long int64_t;
+typedef unsigned long long uint64_t;
+#endif
+
+#elif defined __alpha || (defined __mips && defined _ABIN32)
+#if !defined _NO_LONGLONG
+typedef long int64_t;
+typedef unsigned long uint64_t;
+#endif
+  /* compiler/cpu type to define int64_t */
+#endif
+#endif
+#endif
+
+#if defined _STDINT_HAVE_U_INT_TYPES
+/* int8_t int16_t int32_t defined by inet code, redeclare the u_intXX types */
+typedef u_int8_t uint8_t;
+typedef u_int16_t uint16_t;
+typedef u_int32_t uint32_t;
+
+/* glibc compatibility */
+#ifndef __int8_t_defined
+#define __int8_t_defined
+#endif
+#endif
+
+#ifdef _STDINT_NEED_INT_MODEL_T
+/* we must guess all the basic types. Apart from byte-adressable system, */
+/* there a few 32-bit-only dsp-systems that we guard with BYTE_MODEL 8-} */
+/* (btw, those nibble-addressable systems are way off, or so we assume) */
+
+dnl   /* have a look at "64bit and data size neutrality" at */
+dnl   /* http://unix.org/version2/whatsnew/login_64bit.html */
+dnl   /* (the shorthand "ILP" types always have a "P" part) */
+
+#if defined _STDINT_BYTE_MODEL
+#if _STDINT_LONG_MODEL+0 == 242
+/* 2:4:2 =  IP16 = a normal 16-bit system                */
+typedef unsigned char   uint8_t;
+typedef unsigned short  uint16_t;
+typedef unsigned long   uint32_t;
+#ifndef __int8_t_defined
+#define __int8_t_defined
+typedef          char    int8_t;
+typedef          short   int16_t;
+typedef          long    int32_t;
+#endif
+#elif _STDINT_LONG_MODEL+0 == 244 || _STDINT_LONG_MODEL == 444
+/* 2:4:4 =  LP32 = a 32-bit system derived from a 16-bit */
+/* 4:4:4 = ILP32 = a normal 32-bit system                */
+typedef unsigned char   uint8_t;
+typedef unsigned short  uint16_t;
+typedef unsigned int    uint32_t;
+#ifndef __int8_t_defined
+#define __int8_t_defined
+typedef          char    int8_t;
+typedef          short   int16_t;
+typedef          int     int32_t;
+#endif
+#elif _STDINT_LONG_MODEL+0 == 484 || _STDINT_LONG_MODEL+0 == 488
+/* 4:8:4 =  IP32 = a 32-bit system prepared for 64-bit    */
+/* 4:8:8 =  LP64 = a normal 64-bit system                 */
+typedef unsigned char   uint8_t;
+typedef unsigned short  uint16_t;
+typedef unsigned int    uint32_t;
+#ifndef __int8_t_defined
+#define __int8_t_defined
+typedef          char    int8_t;
+typedef          short   int16_t;
+typedef          int     int32_t;
+#endif
+/* this system has a "long" of 64bit */
+#ifndef _HAVE_UINT64_T
+#define _HAVE_UINT64_T
+typedef unsigned long   uint64_t;
+typedef          long    int64_t;
+#endif
+#elif _STDINT_LONG_MODEL+0 == 448
+/*      LLP64   a 64-bit system derived from a 32-bit system */
+typedef unsigned char   uint8_t;
+typedef unsigned short  uint16_t;
+typedef unsigned int    uint32_t;
+#ifndef __int8_t_defined
+#define __int8_t_defined
+typedef          char    int8_t;
+typedef          short   int16_t;
+typedef          int     int32_t;
+#endif
+/* assuming the system has a "long long" */
+#ifndef _HAVE_UINT64_T
+#define _HAVE_UINT64_T
+#define _HAVE_LONGLONG_UINT64_T
+typedef unsigned long long uint64_t;
+typedef          long long  int64_t;
+#endif
+#else
+#define _STDINT_NO_INT32_T
+#endif
+#else
+#define _STDINT_NO_INT8_T
+#define _STDINT_NO_INT32_T
+#endif
+#endif
+
+/*
+ * quote from SunOS-5.8 sys/inttypes.h:
+ * Use at your own risk.  As of February 1996, the committee is squarely
+ * behind the fixed sized types; the "least" and "fast" types are still being
+ * discussed.  The probability that the "fast" types may be removed before
+ * the standard is finalized is high enough that they are not currently
+ * implemented.
+ */
+
+#if defined _STDINT_NEED_INT_LEAST_T
+typedef  int8_t    int_least8_t;
+typedef  int16_t   int_least16_t;
+typedef  int32_t   int_least32_t;
+#ifdef _HAVE_UINT64_T
+typedef  int64_t   int_least64_t;
+#endif
+
+typedef uint8_t   uint_least8_t;
+typedef uint16_t  uint_least16_t;
+typedef uint32_t  uint_least32_t;
+#ifdef _HAVE_UINT64_T
+typedef uint64_t  uint_least64_t;
+#endif
+  /* least types */
+#endif
+
+#if defined _STDINT_NEED_INT_FAST_T
+typedef  int8_t    int_fast8_t;
+typedef  int       int_fast16_t;
+typedef  int32_t   int_fast32_t;
+#ifdef _HAVE_UINT64_T
+typedef  int64_t   int_fast64_t;
+#endif
+
+typedef uint8_t   uint_fast8_t;
+typedef unsigned  uint_fast16_t;
+typedef uint32_t  uint_fast32_t;
+#ifdef _HAVE_UINT64_T
+typedef uint64_t  uint_fast64_t;
+#endif
+  /* fast types */
+#endif
+
+#ifdef _STDINT_NEED_INTMAX_T
+#ifdef _HAVE_UINT64_T
+typedef  int64_t       intmax_t;
+typedef uint64_t      uintmax_t;
+#else
+typedef          long  intmax_t;
+typedef unsigned long uintmax_t;
+#endif
+#endif
+
+#ifdef _STDINT_NEED_INTPTR_T
+#ifndef __intptr_t_defined
+#define __intptr_t_defined
+/* we encourage using "long" to store pointer values, never use "int" ! */
+#if   _STDINT_LONG_MODEL+0 == 242 || _STDINT_LONG_MODEL+0 == 484
+typedef  unsigned int   uintptr_t;
+typedef           int    intptr_t;
+#elif _STDINT_LONG_MODEL+0 == 244 || _STDINT_LONG_MODEL+0 == 444
+typedef  unsigned long  uintptr_t;
+typedef           long   intptr_t;
+#elif _STDINT_LONG_MODEL+0 == 448 && defined _HAVE_UINT64_T
+typedef        uint64_t uintptr_t;
+typedef         int64_t  intptr_t;
+#else /* matches typical system types ILP32 and LP64 - but not IP16 or LLP64 */
+typedef  unsigned long  uintptr_t;
+typedef           long   intptr_t;
+#endif
+#endif
+#endif
+
+/* The ISO C99 standard specifies that in C++ implementations these
+   should only be defined if explicitly requested.  */
+#if !defined __cplusplus || defined __STDC_CONSTANT_MACROS
+#ifndef UINT32_C
+
+/* Signed.  */
+# define INT8_C(c)      c
+# define INT16_C(c)     c
+# define INT32_C(c)     c
+# ifdef _HAVE_LONGLONG_UINT64_T
+#  define INT64_C(c)    c ## L
+# else
+#  define INT64_C(c)    c ## LL
+# endif
+
+/* Unsigned.  */
+# define UINT8_C(c)     c ## U
+# define UINT16_C(c)    c ## U
+# define UINT32_C(c)    c ## U
+# ifdef _HAVE_LONGLONG_UINT64_T
+#  define UINT64_C(c)   c ## UL
+# else
+#  define UINT64_C(c)   c ## ULL
+# endif
+
+/* Maximal type.  */
+# ifdef _HAVE_LONGLONG_UINT64_T
+#  define INTMAX_C(c)   c ## L
+#  define UINTMAX_C(c)  c ## UL
+# else
+#  define INTMAX_C(c)   c ## LL
+#  define UINTMAX_C(c)  c ## ULL
+# endif
+
+  /* literalnumbers */
+#endif
+#endif
+
+/* These limits are merily those of a two complement byte-oriented system */
+
+/* Minimum of signed integral types.  */
+# define INT8_MIN               (-128)
+# define INT16_MIN              (-32767-1)
+# define INT32_MIN              (-2147483647-1)
+# define INT64_MIN              (-__INT64_C(9223372036854775807)-1)
+/* Maximum of signed integral types.  */
+# define INT8_MAX               (127)
+# define INT16_MAX              (32767)
+# define INT32_MAX              (2147483647)
+# define INT64_MAX              (__INT64_C(9223372036854775807))
+
+/* Maximum of unsigned integral types.  */
+# define UINT8_MAX              (255)
+# define UINT16_MAX             (65535)
+# define UINT32_MAX             (4294967295U)
+# define UINT64_MAX             (__UINT64_C(18446744073709551615))
+
+/* Minimum of signed integral types having a minimum size.  */
+# define INT_LEAST8_MIN         INT8_MIN
+# define INT_LEAST16_MIN        INT16_MIN
+# define INT_LEAST32_MIN        INT32_MIN
+# define INT_LEAST64_MIN        INT64_MIN
+/* Maximum of signed integral types having a minimum size.  */
+# define INT_LEAST8_MAX         INT8_MAX
+# define INT_LEAST16_MAX        INT16_MAX
+# define INT_LEAST32_MAX        INT32_MAX
+# define INT_LEAST64_MAX        INT64_MAX
+
+/* Maximum of unsigned integral types having a minimum size.  */
+# define UINT_LEAST8_MAX        UINT8_MAX
+# define UINT_LEAST16_MAX       UINT16_MAX
+# define UINT_LEAST32_MAX       UINT32_MAX
+# define UINT_LEAST64_MAX       UINT64_MAX
+
+  /* shortcircuit*/
+#endif
+  /* once */
+#endif
+#endif
+STDINT_EOF
+fi
+    if cmp -s $ac_stdint_h $ac_stdint 2>/dev/null; then
+      AC_MSG_NOTICE([$ac_stdint_h is unchanged])
+    else
+      ac_dir=`AS_DIRNAME(["$ac_stdint_h"])`
+      AS_MKDIR_P(["$ac_dir"])
+      rm -f $ac_stdint_h
+      mv $ac_stdint $ac_stdint_h
+    fi
+],[# variables for create stdint.h replacement
+PACKAGE="$PACKAGE"
+VERSION="$VERSION"
+ac_stdint_h="$ac_stdint_h"
+_ac_stdint_h=AS_TR_CPP(_$PACKAGE-$ac_stdint_h)
+ac_cv_stdint_message="$ac_cv_stdint_message"
+ac_cv_header_stdint_t="$ac_cv_header_stdint_t"
+ac_cv_header_stdint_x="$ac_cv_header_stdint_x"
+ac_cv_header_stdint_o="$ac_cv_header_stdint_o"
+ac_cv_header_stdint_u="$ac_cv_header_stdint_u"
+ac_cv_type_uint64_t="$ac_cv_type_uint64_t"
+ac_cv_type_u_int64_t="$ac_cv_type_u_int64_t"
+ac_cv_char_data_model="$ac_cv_char_data_model"
+ac_cv_long_data_model="$ac_cv_long_data_model"
+ac_cv_type_int_least32_t="$ac_cv_type_int_least32_t"
+ac_cv_type_int_fast32_t="$ac_cv_type_int_fast32_t"
+ac_cv_type_intmax_t="$ac_cv_type_intmax_t"
+])
+])
diff --git a/common/m4/check.m4 b/common/m4/check.m4
new file mode 100755 (executable)
index 0000000..19784ae
--- /dev/null
@@ -0,0 +1,181 @@
+dnl _AM_TRY_CHECK(MINIMUM-VERSION, EXTRA-CFLAGS, EXTRA-LIBS, CHECK-LIB-NAME
+dnl               [, ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]])
+dnl Test for check, and define CHECK_CFLAGS and CHECK_LIBS
+dnl Done this way because of the brokenness that is
+dnl https://launchpad.net/distros/ubuntu/+source/check/+bug/5840
+dnl
+
+AC_DEFUN([_AM_TRY_CHECK],
+[
+  min_check_version=$1
+  extra_cflags=$2
+  extra_libs=$3
+  check_lib_name=$4
+  
+  CHECK_CFLAGS="$extra_cflags"
+  CHECK_LIBS="$extra_libs -l$check_lib_name"
+
+  ac_save_CFLAGS="$CFLAGS"
+  ac_save_LIBS="$LIBS"
+
+  CFLAGS="$CFLAGS $CHECK_CFLAGS"
+  LIBS="$CHECK_LIBS $LIBS"
+
+  AC_MSG_CHECKING(for check named $check_lib_name  - version >= $min_check_version)
+
+  rm -f conf.check-test
+  dnl unset no_check, since in our second run it would have been set to yes
+  dnl before
+  no_check=
+  AC_TRY_RUN([
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <check.h>
+
+int main ()
+{
+  int major, minor, micro;
+  char *tmp_version;
+
+  system ("touch conf.check-test");
+
+  /* HP/UX 9 (%@#!) writes to sscanf strings */
+  tmp_version = strdup("$min_check_version");
+  if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, &micro) != 3) {
+     printf("%s, bad version string\n", "$min_check_version");
+     return 1;
+   }
+    
+  if ((CHECK_MAJOR_VERSION != check_major_version) ||
+      (CHECK_MINOR_VERSION != check_minor_version) ||
+      (CHECK_MICRO_VERSION != check_micro_version))
+    {
+      printf("\n*** The check header file (version %d.%d.%d) does not match\n",
+            CHECK_MAJOR_VERSION, CHECK_MINOR_VERSION, CHECK_MICRO_VERSION);
+      printf("*** the check library (version %d.%d.%d).\n",
+            check_major_version, check_minor_version, check_micro_version);
+      return 1;
+    }
+
+  if ((check_major_version > major) ||
+      ((check_major_version == major) && (check_minor_version > minor)) ||
+      ((check_major_version == major) && (check_minor_version == minor) && (check_micro_version >= micro)))
+    {
+      return 0;
+    }
+  else
+    {
+      printf("\n*** An old version of check (%d.%d.%d) was found.\n",
+             check_major_version, check_minor_version, check_micro_version);
+      printf("*** You need a version of check being at least %d.%d.%d.\n", major, minor, micro);
+      printf("***\n"); 
+      printf("*** If you have already installed a sufficiently new version, this error\n");
+      printf("*** probably means that the wrong copy of the check library and header\n");
+      printf("*** file is being found. Rerun configure with the --with-check=PATH option\n");
+      printf("*** to specify the prefix where the correct version was installed.\n");
+    }
+
+  return 1;
+}
+],, no_check=yes, [echo $ac_n "cross compiling; assumed OK... $ac_c"])
+
+  CFLAGS="$ac_save_CFLAGS"
+  LIBS="$ac_save_LIBS"
+
+  if test "x$no_check" = x ; then
+    AC_MSG_RESULT(yes)
+    ifelse([$5], , :, [$5])
+  else
+    AC_MSG_RESULT(no)
+    if test -f conf.check-test ; then
+      :
+    else
+      echo "*** Could not run check test program, checking why..."
+      CFLAGS="$CFLAGS $CHECK_CFLAGS"
+      LIBS="$CHECK_LIBS $LIBS"
+      AC_TRY_LINK([
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <check.h>
+], ,  [ echo "*** The test program compiled, but did not run. This usually means"
+        echo "*** that the run-time linker is not finding check. You'll need to set your"
+        echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
+        echo "*** to the installed location  Also, make sure you have run ldconfig if that"
+        echo "*** is required on your system"
+       echo "***"
+        echo "*** If you have an old version installed, it is best to remove it, although"
+        echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"],
+      [ echo "*** The test program failed to compile or link. See the file config.log for"
+        echo "*** the exact error that occured." ])
+    
+      CFLAGS="$ac_save_CFLAGS"
+      LIBS="$ac_save_LIBS"
+    fi
+
+    CHECK_CFLAGS=""
+    CHECK_LIBS=""
+
+    rm -f conf.check-test
+    ifelse([$6], , AC_MSG_ERROR([check not found]), [$6])
+  fi
+])
+
+
+dnl AM_PATH_CHECK([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
+dnl Test for check, and define CHECK_CFLAGS and CHECK_LIBS
+dnl
+
+AC_DEFUN([AM_PATH_CHECK],
+[
+  AC_ARG_WITH(check,
+  [  --with-check=PATH       prefix where check is installed [default=auto]])
+  AC_ARG_WITH(checklibname,
+    AC_HELP_STRING([--with-check-lib-name=NAME],
+      [name of the PIC check library (default=check)]))
+  min_check_version=ifelse([$1], ,0.8.2,$1)
+
+  if test x$with_check = xno; then
+    AC_MSG_RESULT(disabled)
+    ifelse([$3], , AC_MSG_ERROR([disabling check is not supported]), [$3])
+  else
+    if test "x$with_check" != x; then
+      CHECK_EXTRA_CFLAGS="-I$with_check/include"
+      CHECK_EXTRA_LIBS="-L$with_check/lib"
+    else
+      CHECK_EXTRA_CFLAGS=""
+      CHECK_EXTRA_LIBS=""
+    fi
+
+    if test x$with_checklibname = x; then
+      _AM_TRY_CHECK($min_check_version, $CHECK_EXTRA_CFLAGS, $CHECK_EXTRA_LIBS,
+        check_pic, [have_check=true], [have_check=false])
+      if test x$have_check = xtrue; then
+        ifelse([$2], , :, [$2])
+      else
+        _AM_TRY_CHECK($min_check_version, $CHECK_EXTRA_CFLAGS, $CHECK_EXTRA_LIBS,
+          check, [have_check=true], [have_check=false])
+        if test x$have_check = xtrue; then
+          ifelse([$2], , :, [$2])
+        else
+          ifelse([$3], , AC_MSG_ERROR([check not found]), [$3])
+        fi
+      fi
+    else
+      _AM_TRY_CHECK($min_check_version, $CHECK_EXTRA_CFLAGS, $CHECK_EXTRA_LIBS,
+        $with_checklibname, [have_check=true], [have_check=false])
+      if test x$have_check = xtrue; then
+        ifelse([$2], , :, [$2])
+      else
+        ifelse([$3], , AC_MSG_ERROR([check not found]), [$3])
+      fi
+    fi
+
+    AC_SUBST(CHECK_CFLAGS)
+    AC_SUBST(CHECK_LIBS)
+    rm -f conf.check-test
+  fi
+])
diff --git a/common/m4/gettext.m4 b/common/m4/gettext.m4
new file mode 100755 (executable)
index 0000000..45cad85
--- /dev/null
@@ -0,0 +1,587 @@
+# gettext.m4 serial 17 (gettext-0.11.5)
+dnl Copyright (C) 1995-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+dnl
+dnl This file can can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Library General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Library General Public License, and the rest of the GNU
+dnl gettext package package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl   Bruno Haible <haible@clisp.cons.org>, 2000-2002.
+
+dnl Macro to add for using GNU gettext.
+
+dnl Usage: AM_GNU_GETTEXT([INTLSYMBOL], [NEEDSYMBOL], [INTLDIR]).
+dnl INTLSYMBOL can be one of 'external', 'no-libtool', 'use-libtool'. The
+dnl    default (if it is not specified or empty) is 'no-libtool'.
+dnl    INTLSYMBOL should be 'external' for packages with no intl directory,
+dnl    and 'no-libtool' or 'use-libtool' for packages with an intl directory.
+dnl    If INTLSYMBOL is 'use-libtool', then a libtool library
+dnl    $(top_builddir)/intl/libintl.la will be created (shared and/or static,
+dnl    depending on --{enable,disable}-{shared,static} and on the presence of
+dnl    AM-DISABLE-SHARED). If INTLSYMBOL is 'no-libtool', a static library
+dnl    $(top_builddir)/intl/libintl.a will be created.
+dnl If NEEDSYMBOL is specified and is 'need-ngettext', then GNU gettext
+dnl    implementations (in libc or libintl) without the ngettext() function
+dnl    will be ignored.  If NEEDSYMBOL is specified and is
+dnl    'need-formatstring-macros', then GNU gettext implementations that don't
+dnl    support the ISO C 99 <inttypes.h> formatstring macros will be ignored.
+dnl INTLDIR is used to find the intl libraries.  If empty,
+dnl    the value `$(top_builddir)/intl/' is used.
+dnl
+dnl The result of the configuration is one of three cases:
+dnl 1) GNU gettext, as included in the intl subdirectory, will be compiled
+dnl    and used.
+dnl    Catalog format: GNU --> install in $(datadir)
+dnl    Catalog extension: .mo after installation, .gmo in source tree
+dnl 2) GNU gettext has been found in the system's C library.
+dnl    Catalog format: GNU --> install in $(datadir)
+dnl    Catalog extension: .mo after installation, .gmo in source tree
+dnl 3) No internationalization, always use English msgid.
+dnl    Catalog format: none
+dnl    Catalog extension: none
+dnl If INTLSYMBOL is 'external', only cases 2 and 3 can occur.
+dnl The use of .gmo is historical (it was needed to avoid overwriting the
+dnl GNU format catalogs when building on a platform with an X/Open gettext),
+dnl but we keep it in order not to force irrelevant filename changes on the
+dnl maintainers.
+dnl
+AC_DEFUN([AM_GNU_GETTEXT],
+[
+  dnl Argument checking.
+  ifelse([$1], [], , [ifelse([$1], [external], , [ifelse([$1], [no-libtool], , [ifelse([$1], [use-libtool], ,
+    [errprint([ERROR: invalid first argument to AM_GNU_GETTEXT
+])])])])])
+  ifelse([$2], [], , [ifelse([$2], [need-ngettext], , [ifelse([$2], [need-formatstring-macros], ,
+    [errprint([ERROR: invalid second argument to AM_GNU_GETTEXT
+])])])])
+  define(gt_included_intl, ifelse([$1], [external], [no], [yes]))
+  define(gt_libtool_suffix_prefix, ifelse([$1], [use-libtool], [l], []))
+
+  AC_REQUIRE([AM_PO_SUBDIRS])dnl
+  ifelse(gt_included_intl, yes, [
+    AC_REQUIRE([AM_INTL_SUBDIR])dnl
+  ])
+
+  dnl Prerequisites of AC_LIB_LINKFLAGS_BODY.
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+
+  dnl Sometimes libintl requires libiconv, so first search for libiconv.
+  dnl Ideally we would do this search only after the
+  dnl      if test "$USE_NLS" = "yes"; then
+  dnl        if test "$gt_cv_func_gnugettext_libc" != "yes"; then
+  dnl tests. But if configure.in invokes AM_ICONV after AM_GNU_GETTEXT
+  dnl the configure script would need to contain the same shell code
+  dnl again, outside any 'if'. There are two solutions:
+  dnl - Invoke AM_ICONV_LINKFLAGS_BODY here, outside any 'if'.
+  dnl - Control the expansions in more detail using AC_PROVIDE_IFELSE.
+  dnl Since AC_PROVIDE_IFELSE is only in autoconf >= 2.52 and not
+  dnl documented, we avoid it.
+  ifelse(gt_included_intl, yes, , [
+    AC_REQUIRE([AM_ICONV_LINKFLAGS_BODY])
+  ])
+
+  AC_MSG_CHECKING([whether NLS is requested])
+  dnl Default is enabled NLS
+  AC_ARG_ENABLE(nls,
+    [  --disable-nls           do not use Native Language Support],
+    USE_NLS=$enableval, USE_NLS=yes)
+  AC_MSG_RESULT($USE_NLS)
+  AC_SUBST(USE_NLS)
+
+  ifelse(gt_included_intl, yes, [
+    BUILD_INCLUDED_LIBINTL=no
+    USE_INCLUDED_LIBINTL=no
+  ])
+  LIBINTL=
+  LTLIBINTL=
+  POSUB=
+
+  dnl If we use NLS figure out what method
+  if test "$USE_NLS" = "yes"; then
+    gt_use_preinstalled_gnugettext=no
+    ifelse(gt_included_intl, yes, [
+      AC_MSG_CHECKING([whether included gettext is requested])
+      AC_ARG_WITH(included-gettext,
+        [  --with-included-gettext use the GNU gettext library included here],
+        nls_cv_force_use_gnu_gettext=$withval,
+        nls_cv_force_use_gnu_gettext=no)
+      AC_MSG_RESULT($nls_cv_force_use_gnu_gettext)
+
+      nls_cv_use_gnu_gettext="$nls_cv_force_use_gnu_gettext"
+      if test "$nls_cv_force_use_gnu_gettext" != "yes"; then
+    ])
+        dnl User does not insist on using GNU NLS library.  Figure out what
+        dnl to use.  If GNU gettext is available we use this.  Else we have
+        dnl to fall back to GNU NLS library.
+
+        dnl Add a version number to the cache macros.
+        define([gt_api_version], ifelse([$2], [need-formatstring-macros], 3, ifelse([$2], [need-ngettext], 2, 1)))
+        define([gt_cv_func_gnugettext_libc], [gt_cv_func_gnugettext]gt_api_version[_libc])
+        define([gt_cv_func_gnugettext_libintl], [gt_cv_func_gnugettext]gt_api_version[_libintl])
+
+        AC_CACHE_CHECK([for GNU gettext in libc], gt_cv_func_gnugettext_libc,
+         [AC_TRY_LINK([#include <libintl.h>
+]ifelse([$2], [need-formatstring-macros],
+[#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+#define __GNU_GETTEXT_SUPPORTED_REVISION(major) ((major) == 0 ? 0 : -1)
+#endif
+changequote(,)dnl
+typedef int array [2 * (__GNU_GETTEXT_SUPPORTED_REVISION(0) >= 1) - 1];
+changequote([,])dnl
+], [])[extern int _nl_msg_cat_cntr;
+extern int *_nl_domain_bindings;],
+            [bindtextdomain ("", "");
+return (int) gettext ("")]ifelse([$2], [need-ngettext], [ + (int) ngettext ("", "", 0)], [])[ + _nl_msg_cat_cntr + *_nl_domain_bindings],
+            gt_cv_func_gnugettext_libc=yes,
+            gt_cv_func_gnugettext_libc=no)])
+
+        if test "$gt_cv_func_gnugettext_libc" != "yes"; then
+          dnl Sometimes libintl requires libiconv, so first search for libiconv.
+          ifelse(gt_included_intl, yes, , [
+            AM_ICONV_LINK
+          ])
+          dnl Search for libintl and define LIBINTL, LTLIBINTL and INCINTL
+          dnl accordingly. Don't use AC_LIB_LINKFLAGS_BODY([intl],[iconv])
+          dnl because that would add "-liconv" to LIBINTL and LTLIBINTL
+          dnl even if libiconv doesn't exist.
+          AC_LIB_LINKFLAGS_BODY([intl])
+          AC_CACHE_CHECK([for GNU gettext in libintl],
+            gt_cv_func_gnugettext_libintl,
+           [gt_save_CPPFLAGS="$CPPFLAGS"
+            CPPFLAGS="$CPPFLAGS $INCINTL"
+            gt_save_LIBS="$LIBS"
+            LIBS="$LIBS $LIBINTL"
+            dnl Now see whether libintl exists and does not depend on libiconv.
+            AC_TRY_LINK([#include <libintl.h>
+]ifelse([$2], [need-formatstring-macros],
+[#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+#define __GNU_GETTEXT_SUPPORTED_REVISION(major) ((major) == 0 ? 0 : -1)
+#endif
+changequote(,)dnl
+typedef int array [2 * (__GNU_GETTEXT_SUPPORTED_REVISION(0) >= 1) - 1];
+changequote([,])dnl
+], [])[extern int _nl_msg_cat_cntr;
+extern
+#ifdef __cplusplus
+"C"
+#endif
+const char *_nl_expand_alias ();],
+              [bindtextdomain ("", "");
+return (int) gettext ("")]ifelse([$2], [need-ngettext], [ + (int) ngettext ("", "", 0)], [])[ + _nl_msg_cat_cntr + *_nl_expand_alias (0)],
+              gt_cv_func_gnugettext_libintl=yes,
+              gt_cv_func_gnugettext_libintl=no)
+            dnl Now see whether libintl exists and depends on libiconv.
+            if test "$gt_cv_func_gnugettext_libintl" != yes && test -n "$LIBICONV"; then
+              LIBS="$LIBS $LIBICONV"
+              AC_TRY_LINK([#include <libintl.h>
+]ifelse([$2], [need-formatstring-macros],
+[#ifndef __GNU_GETTEXT_SUPPORTED_REVISION
+#define __GNU_GETTEXT_SUPPORTED_REVISION(major) ((major) == 0 ? 0 : -1)
+#endif
+changequote(,)dnl
+typedef int array [2 * (__GNU_GETTEXT_SUPPORTED_REVISION(0) >= 1) - 1];
+changequote([,])dnl
+], [])[extern int _nl_msg_cat_cntr;
+extern
+#ifdef __cplusplus
+"C"
+#endif
+const char *_nl_expand_alias ();],
+                [bindtextdomain ("", "");
+return (int) gettext ("")]ifelse([$2], [need-ngettext], [ + (int) ngettext ("", "", 0)], [])[ + _nl_msg_cat_cntr + *_nl_expand_alias (0)],
+               [LIBINTL="$LIBINTL $LIBICONV"
+                LTLIBINTL="$LTLIBINTL $LTLIBICONV"
+                gt_cv_func_gnugettext_libintl=yes
+               ])
+            fi
+            CPPFLAGS="$gt_save_CPPFLAGS"
+            LIBS="$gt_save_LIBS"])
+        fi
+
+        dnl If an already present or preinstalled GNU gettext() is found,
+        dnl use it.  But if this macro is used in GNU gettext, and GNU
+        dnl gettext is already preinstalled in libintl, we update this
+        dnl libintl.  (Cf. the install rule in intl/Makefile.in.)
+        if test "$gt_cv_func_gnugettext_libc" = "yes" \
+           || { test "$gt_cv_func_gnugettext_libintl" = "yes" \
+                && test "$PACKAGE" != gettext; }; then
+          gt_use_preinstalled_gnugettext=yes
+        else
+          dnl Reset the values set by searching for libintl.
+          LIBINTL=
+          LTLIBINTL=
+          INCINTL=
+        fi
+
+    ifelse(gt_included_intl, yes, [
+        if test "$gt_use_preinstalled_gnugettext" != "yes"; then
+          dnl GNU gettext is not found in the C library.
+          dnl Fall back on included GNU gettext library.
+          nls_cv_use_gnu_gettext=yes
+        fi
+      fi
+
+      if test "$nls_cv_use_gnu_gettext" = "yes"; then
+        dnl Mark actions used to generate GNU NLS library.
+        INTLOBJS="\$(GETTOBJS)"
+        BUILD_INCLUDED_LIBINTL=yes
+        USE_INCLUDED_LIBINTL=yes
+        LIBINTL="ifelse([$3],[],\${top_builddir}/intl,[$3])/libintl.[]gt_libtool_suffix_prefix[]a $LIBICONV"
+        LTLIBINTL="ifelse([$3],[],\${top_builddir}/intl,[$3])/libintl.[]gt_libtool_suffix_prefix[]a $LTLIBICONV"
+        LIBS=`echo " $LIBS " | sed -e 's/ -lintl / /' -e 's/^ //' -e 's/ $//'`
+      fi
+
+      if test "$gt_use_preinstalled_gnugettext" = "yes" \
+         || test "$nls_cv_use_gnu_gettext" = "yes"; then
+        dnl Mark actions to use GNU gettext tools.
+        CATOBJEXT=.gmo
+      fi
+    ])
+
+    if test "$gt_use_preinstalled_gnugettext" = "yes" \
+       || test "$nls_cv_use_gnu_gettext" = "yes"; then
+      AC_DEFINE(ENABLE_NLS, 1,
+        [Define to 1 if translation of program messages to the user's native language
+   is requested.])
+    else
+      USE_NLS=no
+    fi
+  fi
+
+  if test "$USE_NLS" = "yes"; then
+
+    if test "$gt_use_preinstalled_gnugettext" = "yes"; then
+      if test "$gt_cv_func_gnugettext_libintl" = "yes"; then
+        AC_MSG_CHECKING([how to link with libintl])
+        AC_MSG_RESULT([$LIBINTL])
+        AC_LIB_APPENDTOVAR([CPPFLAGS], [$INCINTL])
+      fi
+
+      dnl For backward compatibility. Some packages may be using this.
+      AC_DEFINE(HAVE_GETTEXT, 1,
+       [Define if the GNU gettext() function is already present or preinstalled.])
+      AC_DEFINE(HAVE_DCGETTEXT, 1,
+       [Define if the GNU dcgettext() function is already present or preinstalled.])
+    fi
+
+    dnl We need to process the po/ directory.
+    POSUB=po
+  fi
+
+  ifelse(gt_included_intl, yes, [
+    dnl If this is used in GNU gettext we have to set BUILD_INCLUDED_LIBINTL
+    dnl to 'yes' because some of the testsuite requires it.
+    if test "$PACKAGE" = gettext; then
+      BUILD_INCLUDED_LIBINTL=yes
+    fi
+
+    dnl Make all variables we use known to autoconf.
+    AC_SUBST(BUILD_INCLUDED_LIBINTL)
+    AC_SUBST(USE_INCLUDED_LIBINTL)
+    AC_SUBST(CATOBJEXT)
+    AC_SUBST(INTLOBJS)
+
+    dnl For backward compatibility. Some configure.ins may be using this.
+    nls_cv_header_intl=
+    nls_cv_header_libgt=
+
+    dnl For backward compatibility. Some Makefiles may be using this.
+    DATADIRNAME=share
+    AC_SUBST(DATADIRNAME)
+
+    dnl For backward compatibility. Some Makefiles may be using this.
+    INSTOBJEXT=.mo
+    AC_SUBST(INSTOBJEXT)
+
+    dnl For backward compatibility. Some Makefiles may be using this.
+    GENCAT=gencat
+    AC_SUBST(GENCAT)
+
+    dnl Enable libtool support if the surrounding package wishes it.
+    INTL_LIBTOOL_SUFFIX_PREFIX=gt_libtool_suffix_prefix
+    AC_SUBST(INTL_LIBTOOL_SUFFIX_PREFIX)
+  ])
+
+  dnl For backward compatibility. Some Makefiles may be using this.
+  INTLLIBS="$LIBINTL"
+  AC_SUBST(INTLLIBS)
+
+  dnl Make all documented variables known to autoconf.
+  AC_SUBST(LIBINTL)
+  AC_SUBST(LTLIBINTL)
+  AC_SUBST(POSUB)
+])
+
+
+dnl Checks for all prerequisites of the po subdirectory,
+dnl except for USE_NLS.
+AC_DEFUN([AM_PO_SUBDIRS],
+[
+  AC_REQUIRE([AC_PROG_MAKE_SET])dnl
+  AC_REQUIRE([AC_PROG_INSTALL])dnl
+  AC_REQUIRE([AM_MKINSTALLDIRS])dnl
+
+  dnl Perform the following tests also if --disable-nls has been given,
+  dnl because they are needed for "make dist" to work.
+
+  dnl Search for GNU msgfmt in the PATH.
+  dnl The first test excludes Solaris msgfmt and early GNU msgfmt versions.
+  dnl The second test excludes FreeBSD msgfmt.
+  AM_PATH_PROG_WITH_TEST(MSGFMT, msgfmt,
+    [$ac_dir/$ac_word --statistics /dev/null >/dev/null 2>&1 &&
+     (if $ac_dir/$ac_word --statistics /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi)],
+    :)
+  AC_PATH_PROG(GMSGFMT, gmsgfmt, $MSGFMT)
+
+  dnl Search for GNU xgettext 0.11 or newer in the PATH.
+  dnl The first test excludes Solaris xgettext and early GNU xgettext versions.
+  dnl The second test excludes FreeBSD xgettext.
+  AM_PATH_PROG_WITH_TEST(XGETTEXT, xgettext,
+    [$ac_dir/$ac_word --omit-header --copyright-holder= /dev/null >/dev/null 2>&1 &&
+     (if $ac_dir/$ac_word --omit-header --copyright-holder= /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi)],
+    :)
+  dnl Remove leftover from FreeBSD xgettext call.
+  rm -f messages.po
+
+  dnl Search for GNU msgmerge 0.11 or newer in the PATH.
+  AM_PATH_PROG_WITH_TEST(MSGMERGE, msgmerge,
+    [$ac_dir/$ac_word --update -q /dev/null /dev/null >/dev/null 2>&1], :)
+
+  dnl This could go away some day; the PATH_PROG_WITH_TEST already does it.
+  dnl Test whether we really found GNU msgfmt.
+  if test "$GMSGFMT" != ":"; then
+    dnl If it is no GNU msgfmt we define it as : so that the
+    dnl Makefiles still can work.
+    if $GMSGFMT --statistics /dev/null >/dev/null 2>&1 &&
+       (if $GMSGFMT --statistics /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi); then
+      : ;
+    else
+      GMSGFMT=`echo "$GMSGFMT" | sed -e 's,^.*/,,'`
+      AC_MSG_RESULT(
+        [found $GMSGFMT program is not GNU msgfmt; ignore it])
+      GMSGFMT=":"
+    fi
+  fi
+
+  dnl This could go away some day; the PATH_PROG_WITH_TEST already does it.
+  dnl Test whether we really found GNU xgettext.
+  if test "$XGETTEXT" != ":"; then
+    dnl If it is no GNU xgettext we define it as : so that the
+    dnl Makefiles still can work.
+    if $XGETTEXT --omit-header --copyright-holder= /dev/null >/dev/null 2>&1 &&
+       (if $XGETTEXT --omit-header --copyright-holder= /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi); then
+      : ;
+    else
+      AC_MSG_RESULT(
+        [found xgettext program is not GNU xgettext; ignore it])
+      XGETTEXT=":"
+    fi
+    dnl Remove leftover from FreeBSD xgettext call.
+    rm -f messages.po
+  fi
+
+  AC_OUTPUT_COMMANDS([
+    for ac_file in $CONFIG_FILES; do
+      # Support "outfile[:infile[:infile...]]"
+      case "$ac_file" in
+        *:*) ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
+      esac
+      # PO directories have a Makefile.in generated from Makefile.in.in.
+      case "$ac_file" in */Makefile.in)
+        # Adjust a relative srcdir.
+        ac_dir=`echo "$ac_file"|sed 's%/[^/][^/]*$%%'`
+        ac_dir_suffix="/`echo "$ac_dir"|sed 's%^\./%%'`"
+        ac_dots=`echo "$ac_dir_suffix"|sed 's%/[^/]*%../%g'`
+        # In autoconf-2.13 it is called $ac_given_srcdir.
+        # In autoconf-2.50 it is called $srcdir.
+        test -n "$ac_given_srcdir" || ac_given_srcdir="$srcdir"
+        case "$ac_given_srcdir" in
+          .)  top_srcdir=`echo $ac_dots|sed 's%/$%%'` ;;
+          /*) top_srcdir="$ac_given_srcdir" ;;
+          *)  top_srcdir="$ac_dots$ac_given_srcdir" ;;
+        esac
+        if test -f "$ac_given_srcdir/$ac_dir/POTFILES.in"; then
+          rm -f "$ac_dir/POTFILES"
+          test -n "$as_me" && echo "$as_me: creating $ac_dir/POTFILES" || echo "creating $ac_dir/POTFILES"
+          cat "$ac_given_srcdir/$ac_dir/POTFILES.in" | sed -e "/^#/d" -e "/^[  ]*\$/d" -e "s,.*,     $top_srcdir/& \\\\," | sed -e "\$s/\(.*\) \\\\/\1/" > "$ac_dir/POTFILES"
+          # ALL_LINGUAS, POFILES, GMOFILES, UPDATEPOFILES, DUMMYPOFILES depend
+          # on $ac_dir but don't depend on user-specified configuration
+          # parameters.
+          if test -f "$ac_given_srcdir/$ac_dir/LINGUAS"; then
+            # The LINGUAS file contains the set of available languages.
+            if test -n "$ALL_LINGUAS"; then
+              test -n "$as_me" && echo "$as_me: setting ALL_LINGUAS in configure.in is obsolete" || echo "setting ALL_LINGUAS in configure.in is obsolete"
+            fi
+            ALL_LINGUAS_=`sed -e "/^#/d" "$ac_given_srcdir/$ac_dir/LINGUAS"`
+            # Hide the ALL_LINGUAS assigment from automake.
+            eval 'ALL_LINGUAS''=$ALL_LINGUAS_'
+          fi
+          case "$ac_given_srcdir" in
+            .) srcdirpre= ;;
+            *) srcdirpre='$(srcdir)/' ;;
+          esac
+          POFILES=
+          GMOFILES=
+          UPDATEPOFILES=
+          DUMMYPOFILES=
+          for lang in $ALL_LINGUAS; do
+            POFILES="$POFILES $srcdirpre$lang.po"
+            GMOFILES="$GMOFILES $srcdirpre$lang.gmo"
+            UPDATEPOFILES="$UPDATEPOFILES $lang.po-update"
+            DUMMYPOFILES="$DUMMYPOFILES $lang.nop"
+          done
+          # CATALOGS depends on both $ac_dir and the user's LINGUAS
+          # environment variable.
+          INST_LINGUAS=
+          if test -n "$ALL_LINGUAS"; then
+            for presentlang in $ALL_LINGUAS; do
+              useit=no
+              if test "%UNSET%" != "$LINGUAS"; then
+                desiredlanguages="$LINGUAS"
+              else
+                desiredlanguages="$ALL_LINGUAS"
+              fi
+              for desiredlang in $desiredlanguages; do
+                # Use the presentlang catalog if desiredlang is
+                #   a. equal to presentlang, or
+                #   b. a variant of presentlang (because in this case,
+                #      presentlang can be used as a fallback for messages
+                #      which are not translated in the desiredlang catalog).
+                case "$desiredlang" in
+                  "$presentlang"*) useit=yes;;
+                esac
+              done
+              if test $useit = yes; then
+                INST_LINGUAS="$INST_LINGUAS $presentlang"
+              fi
+            done
+          fi
+          CATALOGS=
+          if test -n "$INST_LINGUAS"; then
+            for lang in $INST_LINGUAS; do
+              CATALOGS="$CATALOGS $lang.gmo"
+            done
+          fi
+          test -n "$as_me" && echo "$as_me: creating $ac_dir/Makefile" || echo "creating $ac_dir/Makefile"
+          sed -e "/^POTFILES =/r $ac_dir/POTFILES" -e "/^# Makevars/r $ac_given_srcdir/$ac_dir/Makevars" -e "s|@POFILES@|$POFILES|g" -e "s|@GMOFILES@|$GMOFILES|g" -e "s|@UPDATEPOFILES@|$UPDATEPOFILES|g" -e "s|@DUMMYPOFILES@|$DUMMYPOFILES|g" -e "s|@CATALOGS@|$CATALOGS|g" "$ac_dir/Makefile.in" > "$ac_dir/Makefile"
+          for f in "$ac_given_srcdir/$ac_dir"/Rules-*; do
+            if test -f "$f"; then
+              case "$f" in
+                *.orig | *.bak | *~) ;;
+                *) cat "$f" >> "$ac_dir/Makefile" ;;
+              esac
+            fi
+          done
+        fi
+        ;;
+      esac
+    done],
+   [# Capture the value of obsolete ALL_LINGUAS because we need it to compute
+    # POFILES, GMOFILES, UPDATEPOFILES, DUMMYPOFILES, CATALOGS. But hide it
+    # from automake.
+    eval 'ALL_LINGUAS''="$ALL_LINGUAS"'
+    # Capture the value of LINGUAS because we need it to compute CATALOGS.
+    LINGUAS="${LINGUAS-%UNSET%}"
+   ])
+])
+
+
+dnl Checks for all prerequisites of the intl subdirectory,
+dnl except for INTL_LIBTOOL_SUFFIX_PREFIX (and possibly LIBTOOL), INTLOBJS,
+dnl            USE_INCLUDED_LIBINTL, BUILD_INCLUDED_LIBINTL.
+AC_DEFUN([AM_INTL_SUBDIR],
+[
+  AC_REQUIRE([AC_PROG_INSTALL])dnl
+  AC_REQUIRE([AM_MKINSTALLDIRS])dnl
+  AC_REQUIRE([AC_PROG_CC])dnl
+  AC_REQUIRE([AC_CANONICAL_HOST])dnl
+  AC_REQUIRE([AC_PROG_RANLIB])dnl
+  AC_REQUIRE([AC_ISC_POSIX])dnl
+  AC_REQUIRE([AC_HEADER_STDC])dnl
+  AC_REQUIRE([AC_C_CONST])dnl
+  AC_REQUIRE([AC_C_INLINE])dnl
+  AC_REQUIRE([AC_TYPE_OFF_T])dnl
+  AC_REQUIRE([AC_TYPE_SIZE_T])dnl
+  AC_REQUIRE([AC_FUNC_ALLOCA])dnl
+  AC_REQUIRE([AC_FUNC_MMAP])dnl
+  AC_REQUIRE([jm_GLIBC21])dnl
+  AC_REQUIRE([gt_INTDIV0])dnl
+  AC_REQUIRE([jm_AC_TYPE_UINTMAX_T])dnl
+  AC_REQUIRE([gt_HEADER_INTTYPES_H])dnl
+  AC_REQUIRE([gt_INTTYPES_PRI])dnl
+
+  AC_CHECK_HEADERS([argz.h limits.h locale.h nl_types.h malloc.h stddef.h \
+stdlib.h string.h unistd.h sys/param.h])
+  AC_CHECK_FUNCS([feof_unlocked fgets_unlocked getc_unlocked getcwd getegid \
+geteuid getgid getuid mempcpy munmap putenv setenv setlocale stpcpy \
+strcasecmp strdup strtoul tsearch __argz_count __argz_stringify __argz_next])
+
+  AM_ICONV
+  AM_LANGINFO_CODESET
+  if test $ac_cv_header_locale_h = yes; then
+    AM_LC_MESSAGES
+  fi
+
+  dnl intl/plural.c is generated from intl/plural.y. It requires bison,
+  dnl because plural.y uses bison specific features. It requires at least
+  dnl bison-1.26 because earlier versions generate a plural.c that doesn't
+  dnl compile.
+  dnl bison is only needed for the maintainer (who touches plural.y). But in
+  dnl order to avoid separate Makefiles or --enable-maintainer-mode, we put
+  dnl the rule in general Makefile. Now, some people carelessly touch the
+  dnl files or have a broken "make" program, hence the plural.c rule will
+  dnl sometimes fire. To avoid an error, defines BISON to ":" if it is not
+  dnl present or too old.
+  AC_CHECK_PROGS([INTLBISON], [bison])
+  if test -z "$INTLBISON"; then
+    ac_verc_fail=yes
+  else
+    dnl Found it, now check the version.
+    AC_MSG_CHECKING([version of bison])
+changequote(<<,>>)dnl
+    ac_prog_version=`$INTLBISON --version 2>&1 | sed -n 's/^.*GNU Bison.* \([0-9]*\.[0-9.]*\).*$/\1/p'`
+    case $ac_prog_version in
+      '') ac_prog_version="v. ?.??, bad"; ac_verc_fail=yes;;
+      1.2[6-9]* | 1.[3-9][0-9]* | [2-9].*)
+changequote([,])dnl
+         ac_prog_version="$ac_prog_version, ok"; ac_verc_fail=no;;
+      *) ac_prog_version="$ac_prog_version, bad"; ac_verc_fail=yes;;
+    esac
+    AC_MSG_RESULT([$ac_prog_version])
+  fi
+  if test $ac_verc_fail = yes; then
+    INTLBISON=:
+  fi
+])
+
+
+AC_DEFUN([AM_MKINSTALLDIRS],
+[
+  dnl If the AC_CONFIG_AUX_DIR macro for autoconf is used we possibly
+  dnl find the mkinstalldirs script in another subdir but $(top_srcdir).
+  dnl Try to locate is.
+  MKINSTALLDIRS=
+  if test -n "$ac_aux_dir"; then
+    MKINSTALLDIRS="$ac_aux_dir/mkinstalldirs"
+  fi
+  if test -z "$MKINSTALLDIRS"; then
+    MKINSTALLDIRS="\$(top_srcdir)/mkinstalldirs"
+  fi
+  AC_SUBST(MKINSTALLDIRS)
+])
+
+
+dnl Usage: AM_GNU_GETTEXT_VERSION([gettext-version])
+AC_DEFUN([AM_GNU_GETTEXT_VERSION], [])
diff --git a/common/m4/glib-gettext.m4 b/common/m4/glib-gettext.m4
new file mode 100755 (executable)
index 0000000..5a4ef28
--- /dev/null
@@ -0,0 +1,380 @@
+# Copyright (C) 1995-2002 Free Software Foundation, Inc.
+# Copyright (C) 2001-2003 Red Hat, Inc.
+#
+# This file is free software, distributed under the terms of the GNU
+# General Public License.  As a special exception to the GNU General
+# Public License, this file may be distributed as part of a program
+# that contains a configuration script generated by Autoconf, under
+# the same distribution terms as the rest of that program.
+#
+# This file can be copied and used freely without restrictions.  It can
+# be used in projects which are not available under the GNU Public License
+# but which still want to provide support for the GNU gettext functionality.
+#
+# Macro to add for using GNU gettext.
+# Ulrich Drepper <drepper@cygnus.com>, 1995, 1996
+#
+# Modified to never use included libintl. 
+# Owen Taylor <otaylor@redhat.com>, 12/15/1998
+#
+# Major rework to remove unused code
+# Owen Taylor <otaylor@redhat.com>, 12/11/2002
+#
+# Added better handling of ALL_LINGUAS from GNU gettext version 
+# written by Bruno Haible, Owen Taylor <otaylor.redhat.com> 5/30/3002
+
+#
+# We need this here as well, since someone might use autoconf-2.5x
+# to configure GLib then an older version to configure a package
+# using AM_GLIB_GNU_GETTEXT
+AC_PREREQ(2.53)
+
+dnl
+dnl We go to great lengths to make sure that aclocal won't 
+dnl try to pull in the installed version of these macros
+dnl when running aclocal in the glib directory.
+dnl
+m4_copy([AC_DEFUN],[glib_DEFUN])
+m4_copy([AC_REQUIRE],[glib_REQUIRE])
+dnl
+dnl At the end, if we're not within glib, we'll define the public
+dnl definitions in terms of our private definitions.
+dnl
+
+# GLIB_LC_MESSAGES
+#--------------------
+glib_DEFUN([GLIB_LC_MESSAGES],
+  [AC_CHECK_HEADERS([locale.h])
+    if test $ac_cv_header_locale_h = yes; then
+    AC_CACHE_CHECK([for LC_MESSAGES], am_cv_val_LC_MESSAGES,
+      [AC_TRY_LINK([#include <locale.h>], [return LC_MESSAGES],
+       am_cv_val_LC_MESSAGES=yes, am_cv_val_LC_MESSAGES=no)])
+    if test $am_cv_val_LC_MESSAGES = yes; then
+      AC_DEFINE(HAVE_LC_MESSAGES, 1,
+        [Define if your <locale.h> file defines LC_MESSAGES.])
+    fi
+  fi])
+
+# GLIB_PATH_PROG_WITH_TEST
+#----------------------------
+dnl GLIB_PATH_PROG_WITH_TEST(VARIABLE, PROG-TO-CHECK-FOR,
+dnl   TEST-PERFORMED-ON-FOUND_PROGRAM [, VALUE-IF-NOT-FOUND [, PATH]])
+glib_DEFUN([GLIB_PATH_PROG_WITH_TEST],
+[# Extract the first word of "$2", so it can be a program name with args.
+set dummy $2; ac_word=[$]2
+AC_MSG_CHECKING([for $ac_word])
+AC_CACHE_VAL(ac_cv_path_$1,
+[case "[$]$1" in
+  /*)
+  ac_cv_path_$1="[$]$1" # Let the user override the test with a path.
+  ;;
+  *)
+  IFS="${IFS=  }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+  for ac_dir in ifelse([$5], , $PATH, [$5]); do
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$ac_word; then
+      if [$3]; then
+       ac_cv_path_$1="$ac_dir/$ac_word"
+       break
+      fi
+    fi
+  done
+  IFS="$ac_save_ifs"
+dnl If no 4th arg is given, leave the cache variable unset,
+dnl so AC_PATH_PROGS will keep looking.
+ifelse([$4], , , [  test -z "[$]ac_cv_path_$1" && ac_cv_path_$1="$4"
+])dnl
+  ;;
+esac])dnl
+$1="$ac_cv_path_$1"
+if test ifelse([$4], , [-n "[$]$1"], ["[$]$1" != "$4"]); then
+  AC_MSG_RESULT([$]$1)
+else
+  AC_MSG_RESULT(no)
+fi
+AC_SUBST($1)dnl
+])
+
+# GLIB_WITH_NLS
+#-----------------
+glib_DEFUN([GLIB_WITH_NLS],
+  dnl NLS is obligatory
+  [USE_NLS=yes
+    AC_SUBST(USE_NLS)
+
+    gt_cv_have_gettext=no
+
+    CATOBJEXT=NONE
+    XGETTEXT=:
+    INTLLIBS=
+
+    AC_CHECK_HEADER(libintl.h,
+     [gt_cv_func_dgettext_libintl="no"
+      libintl_extra_libs=""
+
+      #
+      # First check in libc
+      #
+      AC_CACHE_CHECK([for dgettext in libc], gt_cv_func_dgettext_libc,
+        [AC_TRY_LINK([
+#include <libintl.h>
+],
+          [return (int) dgettext ("","")],
+         gt_cv_func_dgettext_libc=yes,
+          gt_cv_func_dgettext_libc=no)
+        ])
+  
+      if test "$gt_cv_func_dgettext_libc" = "yes" ; then
+        AC_CHECK_FUNCS(bind_textdomain_codeset)
+      fi
+
+      #
+      # If we don't have everything we want, check in libintl
+      #
+      if test "$gt_cv_func_dgettext_libc" != "yes" \
+         || test "$ac_cv_func_bind_textdomain_codeset" != "yes" ; then
+        
+        AC_CHECK_LIB(intl, bindtextdomain,
+           [AC_CHECK_LIB(intl, dgettext,
+                         gt_cv_func_dgettext_libintl=yes)])
+
+       if test "$gt_cv_func_dgettext_libintl" != "yes" ; then
+         AC_MSG_CHECKING([if -liconv is needed to use gettext])
+         AC_MSG_RESULT([])
+          AC_CHECK_LIB(intl, dcgettext,
+                      [gt_cv_func_dgettext_libintl=yes
+                       libintl_extra_libs=-liconv],
+                       :,-liconv)
+        fi
+
+        #
+        # If we found libintl, then check in it for bind_textdomain_codeset();
+        # we'll prefer libc if neither have bind_textdomain_codeset(),
+        # and both have dgettext
+        #
+        if test "$gt_cv_func_dgettext_libintl" = "yes" ; then
+          glib_save_LIBS="$LIBS"
+          LIBS="$LIBS -lintl $libintl_extra_libs"
+          unset ac_cv_func_bind_textdomain_codeset
+          AC_CHECK_FUNCS(bind_textdomain_codeset)
+          LIBS="$glib_save_LIBS"
+
+          if test "$ac_cv_func_bind_textdomain_codeset" = "yes" ; then
+            gt_cv_func_dgettext_libc=no
+          else
+            if test "$gt_cv_func_dgettext_libc" = "yes"; then
+              gt_cv_func_dgettext_libintl=no
+            fi
+          fi
+        fi
+      fi
+
+      if test "$gt_cv_func_dgettext_libc" = "yes" \
+       || test "$gt_cv_func_dgettext_libintl" = "yes"; then
+        gt_cv_have_gettext=yes
+      fi
+  
+      if test "$gt_cv_func_dgettext_libintl" = "yes"; then
+        INTLLIBS="-lintl $libintl_extra_libs"
+      fi
+  
+      if test "$gt_cv_have_gettext" = "yes"; then
+       AC_DEFINE(HAVE_GETTEXT,1,
+         [Define if the GNU gettext() function is already present or preinstalled.])
+       GLIB_PATH_PROG_WITH_TEST(MSGFMT, msgfmt,
+         [test -z "`$ac_dir/$ac_word -h 2>&1 | grep 'dv '`"], no)dnl
+       if test "$MSGFMT" != "no"; then
+          glib_save_LIBS="$LIBS"
+          LIBS="$LIBS $INTLLIBS"
+         AC_CHECK_FUNCS(dcgettext)
+         AC_PATH_PROG(GMSGFMT, gmsgfmt, $MSGFMT)
+         GLIB_PATH_PROG_WITH_TEST(XGETTEXT, xgettext,
+           [test -z "`$ac_dir/$ac_word -h 2>&1 | grep '(HELP)'`"], :)
+         AC_TRY_LINK(, [extern int _nl_msg_cat_cntr;
+                        return _nl_msg_cat_cntr],
+           [CATOBJEXT=.gmo 
+             DATADIRNAME=share],
+           [case $host in
+           *-*-solaris*)
+           dnl On Solaris, if bind_textdomain_codeset is in libc,
+           dnl GNU format message catalog is always supported,
+            dnl since both are added to the libc all together.
+           dnl Hence, we'd like to go with DATADIRNAME=share and
+           dnl and CATOBJEXT=.gmo in this case.
+            AC_CHECK_FUNC(bind_textdomain_codeset,
+             [CATOBJEXT=.gmo 
+               DATADIRNAME=share],
+             [CATOBJEXT=.mo
+               DATADIRNAME=lib])
+           ;;
+           *)
+           CATOBJEXT=.mo
+            DATADIRNAME=lib
+           ;;
+           esac])
+          LIBS="$glib_save_LIBS"
+         INSTOBJEXT=.mo
+       else
+         gt_cv_have_gettext=no
+       fi
+      fi
+    ])
+
+    if test "$gt_cv_have_gettext" = "yes" ; then
+      AC_DEFINE(ENABLE_NLS, 1,
+        [always defined to indicate that i18n is enabled])
+    fi
+
+    dnl Test whether we really found GNU xgettext.
+    if test "$XGETTEXT" != ":"; then
+      dnl If it is not GNU xgettext we define it as : so that the
+      dnl Makefiles still can work.
+      if $XGETTEXT --omit-header /dev/null 2> /dev/null; then
+        : ;
+      else
+        AC_MSG_RESULT(
+         [found xgettext program is not GNU xgettext; ignore it])
+        XGETTEXT=":"
+      fi
+    fi
+
+    # We need to process the po/ directory.
+    POSUB=po
+
+    AC_OUTPUT_COMMANDS(
+      [case "$CONFIG_FILES" in *po/Makefile.in*)
+        sed -e "/POTFILES =/r po/POTFILES" po/Makefile.in > po/Makefile
+      esac])
+
+    dnl These rules are solely for the distribution goal.  While doing this
+    dnl we only have to keep exactly one list of the available catalogs
+    dnl in configure.in.
+    for lang in $ALL_LINGUAS; do
+      GMOFILES="$GMOFILES $lang.gmo"
+      POFILES="$POFILES $lang.po"
+    done
+
+    dnl Make all variables we use known to autoconf.
+    AC_SUBST(CATALOGS)
+    AC_SUBST(CATOBJEXT)
+    AC_SUBST(DATADIRNAME)
+    AC_SUBST(GMOFILES)
+    AC_SUBST(INSTOBJEXT)
+    AC_SUBST(INTLLIBS)
+    AC_SUBST(PO_IN_DATADIR_TRUE)
+    AC_SUBST(PO_IN_DATADIR_FALSE)
+    AC_SUBST(POFILES)
+    AC_SUBST(POSUB)
+  ])
+
+# AM_GLIB_GNU_GETTEXT
+# -------------------
+# Do checks necessary for use of gettext. If a suitable implementation 
+# of gettext is found in either in libintl or in the C library,
+# it will set INTLLIBS to the libraries needed for use of gettext
+# and AC_DEFINE() HAVE_GETTEXT and ENABLE_NLS. (The shell variable
+# gt_cv_have_gettext will be set to "yes".) It will also call AC_SUBST()
+# on various variables needed by the Makefile.in.in installed by 
+# glib-gettextize.
+dnl
+glib_DEFUN([GLIB_GNU_GETTEXT],
+  [AC_REQUIRE([AC_PROG_CC])dnl
+   AC_REQUIRE([AC_HEADER_STDC])dnl
+   
+   GLIB_LC_MESSAGES
+   GLIB_WITH_NLS
+
+   if test "$gt_cv_have_gettext" = "yes"; then
+     if test "x$ALL_LINGUAS" = "x"; then
+       LINGUAS=
+     else
+       AC_MSG_CHECKING(for catalogs to be installed)
+       NEW_LINGUAS=
+       for presentlang in $ALL_LINGUAS; do
+         useit=no
+         if test "%UNSET%" != "${LINGUAS-%UNSET%}"; then
+           desiredlanguages="$LINGUAS"
+         else
+           desiredlanguages="$ALL_LINGUAS"
+         fi
+         for desiredlang in $desiredlanguages; do
+          # Use the presentlang catalog if desiredlang is
+           #   a. equal to presentlang, or
+           #   b. a variant of presentlang (because in this case,
+           #      presentlang can be used as a fallback for messages
+           #      which are not translated in the desiredlang catalog).
+           case "$desiredlang" in
+             "$presentlang"*) useit=yes;;
+           esac
+         done
+         if test $useit = yes; then
+           NEW_LINGUAS="$NEW_LINGUAS $presentlang"
+         fi
+       done
+       LINGUAS=$NEW_LINGUAS
+       AC_MSG_RESULT($LINGUAS)
+     fi
+
+     dnl Construct list of names of catalog files to be constructed.
+     if test -n "$LINGUAS"; then
+       for lang in $LINGUAS; do CATALOGS="$CATALOGS $lang$CATOBJEXT"; done
+     fi
+   fi
+
+   dnl If the AC_CONFIG_AUX_DIR macro for autoconf is used we possibly
+   dnl find the mkinstalldirs script in another subdir but ($top_srcdir).
+   dnl Try to locate is.
+   MKINSTALLDIRS=
+   if test -n "$ac_aux_dir"; then
+     MKINSTALLDIRS="$ac_aux_dir/mkinstalldirs"
+   fi
+   if test -z "$MKINSTALLDIRS"; then
+     MKINSTALLDIRS="\$(top_srcdir)/mkinstalldirs"
+   fi
+   AC_SUBST(MKINSTALLDIRS)
+
+   dnl Generate list of files to be processed by xgettext which will
+   dnl be included in po/Makefile.
+   test -d po || mkdir po
+   if test "x$srcdir" != "x."; then
+     if test "x`echo $srcdir | sed 's@/.*@@'`" = "x"; then
+       posrcprefix="$srcdir/"
+     else
+       posrcprefix="../$srcdir/"
+     fi
+   else
+     posrcprefix="../"
+   fi
+   rm -f po/POTFILES
+   sed -e "/^#/d" -e "/^\$/d" -e "s,.*,        $posrcprefix& \\\\," -e "\$s/\(.*\) \\\\/\1/" \
+       < $srcdir/po/POTFILES.in > po/POTFILES
+  ])
+
+# AM_GLIB_DEFINE_LOCALEDIR(VARIABLE)
+# -------------------------------
+# Define VARIABLE to the location where catalog files will
+# be installed by po/Makefile.
+glib_DEFUN([GLIB_DEFINE_LOCALEDIR],
+[glib_REQUIRE([GLIB_GNU_GETTEXT])dnl
+glib_save_prefix="$prefix"
+glib_save_exec_prefix="$exec_prefix"
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+test "x$exec_prefix" = xNONE && exec_prefix=$prefix
+if test "x$CATOBJEXT" = "x.mo" ; then
+  localedir=`eval echo "${libdir}/locale"`
+else
+  localedir=`eval echo "${datadir}/locale"`
+fi
+prefix="$glib_save_prefix"
+exec_prefix="$glib_save_exec_prefix"
+AC_DEFINE_UNQUOTED($1, "$localedir",
+  [Define the location where the catalogs will be installed])
+])
+
+dnl
+dnl Now the definitions that aclocal will find
+dnl
+ifdef(glib_configure_in,[],[
+AC_DEFUN([AM_GLIB_GNU_GETTEXT],[GLIB_GNU_GETTEXT($@)])
+AC_DEFUN([AM_GLIB_DEFINE_LOCALEDIR],[GLIB_DEFINE_LOCALEDIR($@)])
+])dnl
diff --git a/common/m4/gst-arch.m4 b/common/m4/gst-arch.m4
new file mode 100755 (executable)
index 0000000..8a32bd2
--- /dev/null
@@ -0,0 +1,123 @@
+dnl AG_GST_ARCH
+dnl sets up defines and automake conditionals for host architecture
+dnl checks endianness
+dnl defines HOST_CPU
+
+AC_DEFUN([AG_GST_ARCH],
+[
+  AC_REQUIRE([AC_CANONICAL_HOST]) dnl we use host_ variables
+
+  dnl Determine CPU
+  case "x${host_cpu}" in
+    xi?86 | xk? | xi?86_64)
+      HAVE_CPU_I386=yes
+      AC_DEFINE(HAVE_CPU_I386, 1, [Define if the host CPU is an x86])
+  
+      dnl FIXME could use some better detection
+      dnl (ie CPUID)
+      case "x${host_cpu}" in
+        xi386 | xi486) ;;
+        *)
+          AC_DEFINE(HAVE_RDTSC, 1, [Define if RDTSC is available]) ;;
+      esac ;;
+    xpowerpc)
+      HAVE_CPU_PPC=yes
+      AC_DEFINE(HAVE_CPU_PPC, 1, [Define if the host CPU is a PowerPC]) ;;
+    xpowerpc64)
+      HAVE_CPU_PPC64=yes
+      AC_DEFINE(HAVE_CPU_PPC64, 1, [Define if the host CPU is a 64 bit PowerPC]) ;;
+    xalpha*)
+      HAVE_CPU_ALPHA=yes
+      AC_DEFINE(HAVE_CPU_ALPHA, 1, [Define if the host CPU is an Alpha]) ;;
+    xarm*)
+      HAVE_CPU_ARM=yes
+      AC_DEFINE(HAVE_CPU_ARM, 1, [Define if the host CPU is an ARM]) ;;
+    xsparc*)
+      HAVE_CPU_SPARC=yes
+      AC_DEFINE(HAVE_CPU_SPARC, 1, [Define if the host CPU is a SPARC]) ;;
+    xmips*)
+      HAVE_CPU_MIPS=yes
+      AC_DEFINE(HAVE_CPU_MIPS, 1, [Define if the host CPU is a MIPS]) ;;
+    xhppa*)
+      HAVE_CPU_HPPA=yes
+      AC_DEFINE(HAVE_CPU_HPPA, 1, [Define if the host CPU is a HPPA]) ;;
+    xs390*)
+      HAVE_CPU_S390=yes
+      AC_DEFINE(HAVE_CPU_S390, 1, [Define if the host CPU is a S390]) ;;
+    xia64*)
+      HAVE_CPU_IA64=yes
+      AC_DEFINE(HAVE_CPU_IA64, 1, [Define if the host CPU is a IA64]) ;;
+    xm68k*)
+      HAVE_CPU_M68K=yes
+      AC_DEFINE(HAVE_CPU_M68K, 1, [Define if the host CPU is a M68K]) ;;
+    xx86_64)
+      HAVE_CPU_X86_64=yes
+      AC_DEFINE(HAVE_CPU_X86_64, 1, [Define if the host CPU is a x86_64]) ;;
+    xcris)
+      HAVE_CPU_CRIS=yes
+      AC_DEFINE(HAVE_CPU_CRIS, 1, [Define if the host CPU is a CRIS]) ;;
+    xcrisv32)
+      HAVE_CPU_CRISV32=yes
+      AC_DEFINE(HAVE_CPU_CRISV32, 1, [Define if the host CPU is a CRISv32]) ;;
+  esac
+  
+  dnl Determine endianness
+  AC_C_BIGENDIAN
+  
+  AM_CONDITIONAL(HAVE_CPU_I386,       test "x$HAVE_CPU_I386" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_PPC,        test "x$HAVE_CPU_PPC" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_PPC64,      test "x$HAVE_CPU_PPC64" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_ALPHA,      test "x$HAVE_CPU_ALPHA" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_ARM,        test "x$HAVE_CPU_ARM" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_SPARC,      test "x$HAVE_CPU_SPARC" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_HPPA,       test "x$HAVE_CPU_HPPA" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_MIPS,       test "x$HAVE_CPU_MIPS" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_S390,       test "x$HAVE_CPU_S390" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_IA64,       test "x$HAVE_CPU_IA64" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_M68K,       test "x$HAVE_CPU_M68K" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_X86_64,     test "x$HAVE_CPU_X86_64" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_CRIS,       test "x$HAVE_CPU_CRIS" = "xyes")
+  AM_CONDITIONAL(HAVE_CPU_CRISV32,    test "x$HAVE_CPU_CRISV32" = "xyes")
+
+  AC_DEFINE_UNQUOTED(HOST_CPU, "$host_cpu", [the host CPU])
+])
+
+dnl check if unaligned memory access works correctly
+AC_DEFUN([AG_GST_UNALIGNED_ACCESS], [
+  AC_MSG_CHECKING([if unaligned memory access works correctly])
+  if test x"$as_cv_unaligned_access" = x ; then
+    case $host in
+      alpha*|arm*|hp*|mips*|sh*|sparc*|ia64*)
+        _AS_ECHO_N([(blacklisted) ])
+        as_cv_unaligned_access=no
+       ;;
+      i?86*|powerpc*|m68k*|cris*)
+        _AS_ECHO_N([(whitelisted) ])
+        as_cv_unaligned_access=yes
+       ;;
+    esac
+  else
+    _AS_ECHO_N([(cached) ])
+  fi
+  if test x"$as_cv_unaligned_access" = x ; then
+    AC_TRY_RUN([
+int main(int argc, char **argv)
+{
+  char array[] = "ABCDEFGH";
+  unsigned int iarray[2];
+  memcpy(iarray,array,8);
+#define GET(x) (*(unsigned int *)((char *)iarray + (x)))
+  if(GET(0) != 0x41424344 && GET(0) != 0x44434241) return 1;
+  if(GET(1) != 0x42434445 && GET(1) != 0x45444342) return 1;
+  if(GET(2) != 0x43444546 && GET(2) != 0x46454443) return 1;
+  if(GET(3) != 0x44454647 && GET(3) != 0x47464544) return 1;
+  return 0;
+}
+    ], as_cv_unaligned_access="yes", as_cv_unaligned_access="no")
+  fi
+  AC_MSG_RESULT($as_cv_unaligned_access)
+  if test "$as_cv_unaligned_access" = "yes"; then
+    AC_DEFINE_UNQUOTED(HAVE_UNALIGNED_ACCESS, 1,
+      [defined if unaligned memory access works correctly])
+  fi
+])
diff --git a/common/m4/gst-args.m4 b/common/m4/gst-args.m4
new file mode 100755 (executable)
index 0000000..1781af4
--- /dev/null
@@ -0,0 +1,302 @@
+dnl configure-time options shared among gstreamer modules
+
+dnl AG_GST_ARG_DEBUG
+dnl AG_GST_ARG_PROFILING
+dnl AG_GST_ARG_VALGRIND
+dnl AG_GST_ARG_GCOV
+
+dnl AG_GST_ARG_EXAMPLES
+
+dnl AG_GST_ARG_WITH_PKG_CONFIG_PATH
+dnl AG_GST_ARG_WITH_PACKAGE_NAME
+dnl AG_GST_ARG_WITH_PACKAGE_ORIGIN
+
+dnl AG_GST_ARG_WITH_PLUGINS
+dnl AG_GST_CHECK_PLUGIN
+dnl AG_GST_DISABLE_PLUGIN
+
+dnl AG_GST_ARG_ENABLE_EXTERNAL
+dnl AG_GST_ARG_ENABLE_EXPERIMENTAL
+dnl AG_GST_ARG_ENABLE_BROKEN
+
+AC_DEFUN([AG_GST_ARG_DEBUG],
+[
+  dnl debugging stuff
+  AC_ARG_ENABLE(debug,
+    AC_HELP_STRING([--disable-debug],[disable addition of -g debugging info]),
+    [
+      case "${enableval}" in
+        yes) USE_DEBUG=yes ;;
+        no)  USE_DEBUG=no ;;
+        *)   AC_MSG_ERROR(bad value ${enableval} for --enable-debug) ;;
+      esac
+    ],
+    [USE_DEBUG=yes]) dnl Default value
+])
+
+AC_DEFUN([AG_GST_ARG_PROFILING],
+[
+  AC_ARG_ENABLE(profiling,
+    AC_HELP_STRING([--enable-profiling],
+      [adds -pg to compiler commandline, for profiling]),
+    [
+      case "${enableval}" in
+        yes) USE_PROFILING=yes ;;
+        no)  USE_PROFILING=no ;;
+        *)   AC_MSG_ERROR(bad value ${enableval} for --enable-profiling) ;;
+      esac
+    ], 
+    [USE_PROFILING=no]) dnl Default value
+])
+
+AC_DEFUN([AG_GST_ARG_VALGRIND],
+[
+  dnl valgrind inclusion
+  AC_ARG_ENABLE(valgrind,
+    AC_HELP_STRING([--disable-valgrind],[disable run-time valgrind detection]),
+    [
+      case "${enableval}" in
+        yes) USE_VALGRIND="$USE_DEBUG" ;;
+        no)  USE_VALGRIND=no ;;
+        *)   AC_MSG_ERROR(bad value ${enableval} for --enable-valgrind) ;;
+      esac
+    ],
+    [USE_VALGRIND="$USE_DEBUG"]) dnl Default value
+  VALGRIND_REQ="2.1"
+  if test "x$USE_VALGRIND" = xyes; then
+    PKG_CHECK_MODULES(VALGRIND, valgrind > $VALGRIND_REQ,
+      USE_VALGRIND="yes",
+      [
+        USE_VALGRIND="no"
+        AC_MSG_RESULT([no])
+      ])
+  fi
+  if test "x$USE_VALGRIND" = xyes; then
+    AC_DEFINE(HAVE_VALGRIND, 1, [Define if valgrind should be used])
+    AC_MSG_NOTICE(Using extra code paths for valgrind)
+  fi
+])
+
+AC_DEFUN([AG_GST_ARG_GCOV],
+[
+  AC_ARG_ENABLE(gcov,
+    AC_HELP_STRING([--enable-gcov],
+      [compile with coverage profiling instrumentation (gcc only)]),
+    enable_gcov=$enableval,
+    enable_gcov=no)
+  if test x$enable_gcov = xyes ; then
+    if test "x$GCC" != "xyes"
+    then
+      AC_MSG_ERROR([gcov only works if gcc is used])
+    fi
+
+    AS_COMPILER_FLAG(["-fprofile-arcs"],
+      [GCOV_CFLAGS="$GCOV_CFLAGS -fprofile-arcs"],
+      true)
+    AS_COMPILER_FLAG(["-ftest-coverage"],
+      [GCOV_CFLAGS="$GCOV_CFLAGS -ftest-coverage"],
+      true)
+    dnl remove any -O flags - FIXME: is this needed ?
+    GCOV_CFLAGS=`echo "$GCOV_CFLAGS" | sed -e 's/-O[[0-9]]*//g'`
+    dnl libtool 1.5.22 and lower strip -fprofile-arcs from the flags
+    dnl passed to the linker, which is a bug; -fprofile-arcs implicitly
+    dnl links in -lgcov, so we do it explicitly here for the same effect
+    GCOV_LIBS=-lgcov
+    AC_SUBST(GCOV_CFLAGS)
+    AC_SUBST(GCOV_LIBS)
+    GCOV=`echo $CC | sed s/gcc/gcov/g`
+    AC_SUBST(GCOV)
+
+    GST_GCOV_ENABLED=yes
+    AC_DEFINE_UNQUOTED(GST_GCOV_ENABLED, 1,
+      [Defined if gcov is enabled to force a rebuild due to config.h changing])
+    dnl if gcov is used, we do not want default -O2 CFLAGS
+    if test "x$GST_GCOV_ENABLED" = "xyes"
+    then
+      CFLAGS="-O0"
+      AC_SUBST(CFLAGS)
+      CXXFLAGS="-O0"
+      AC_SUBST(CXXFLAGS)
+      FFLAGS="-O0"
+      AC_SUBST(FFLAGS)
+      CCASFLAGS="-O0"
+      AC_SUBST(CCASFLAGS)
+      AC_MSG_NOTICE([gcov enabled, setting CFLAGS and friends to $CFLAGS])
+    fi
+  fi
+  AM_CONDITIONAL(GST_GCOV_ENABLED, test x$enable_gcov = xyes)
+])
+
+AC_DEFUN([AG_GST_ARG_EXAMPLES],
+[
+  AC_ARG_ENABLE(examples,
+    AC_HELP_STRING([--disable-examples], [disable building examples]),
+      [
+        case "${enableval}" in
+          yes) BUILD_EXAMPLES=yes ;;
+          no)  BUILD_EXAMPLES=no ;;
+          *)   AC_MSG_ERROR(bad value ${enableval} for --disable-examples) ;;
+        esac
+      ],
+      [BUILD_EXAMPLES=yes]) dnl Default value
+  AM_CONDITIONAL(BUILD_EXAMPLES,      test "x$BUILD_EXAMPLES" = "xyes")
+])
+
+AC_DEFUN([AG_GST_ARG_WITH_PKG_CONFIG_PATH],
+[
+  dnl possibly modify pkg-config path
+  AC_ARG_WITH(pkg-config-path, 
+     AC_HELP_STRING([--with-pkg-config-path],
+                    [colon-separated list of pkg-config(1) dirs]),
+     [
+       export PKG_CONFIG_PATH=${withval}
+       AC_MSG_NOTICE(Set PKG_CONFIG_PATH to $PKG_CONFIG_PATH)
+     ])
+])
+
+
+dnl This macro requires that GST_CVS is set to yes or no (release)
+AC_DEFUN([AG_GST_ARG_WITH_PACKAGE_NAME],
+[
+  dnl package name in plugins
+  AC_ARG_WITH(package-name,
+    AC_HELP_STRING([--with-package-name],
+      [specify package name to use in plugins]),
+    [
+      case "${withval}" in
+        yes) AC_MSG_ERROR(bad value ${withval} for --with-package-name) ;;
+        no)  AC_MSG_ERROR(bad value ${withval} for --with-package-name) ;;
+        *)   GST_PACKAGE_NAME="${withval}" ;;
+      esac
+    ], 
+    [
+      P=$1
+      if test "x$P" = "x"
+      then
+        P=$PACKAGE_NAME
+      fi
+      
+      dnl default value
+      if test "x$GST_CVS" = "xyes"
+      then
+        dnl nano >= 1
+        GST_PACKAGE_NAME="$P CVS/prerelease"
+      else
+        GST_PACKAGE_NAME="$P source release"
+      fi
+    ]
+  )
+  AC_MSG_NOTICE(Using $GST_PACKAGE_NAME as package name)
+  AC_DEFINE_UNQUOTED(GST_PACKAGE_NAME, "$GST_PACKAGE_NAME",
+      [package name in plugins])
+  AC_SUBST(GST_PACKAGE_NAME)
+])
+
+AC_DEFUN([AG_GST_ARG_WITH_PACKAGE_ORIGIN],
+[
+  dnl package origin URL
+  AC_ARG_WITH(package-origin,
+    AC_HELP_STRING([--with-package-origin],
+      [specify package origin URL to use in plugins]),
+    [
+      case "${withval}" in
+        yes) AC_MSG_ERROR(bad value ${withval} for --with-package-origin) ;;
+        no)  AC_MSG_ERROR(bad value ${withval} for --with-package-origin) ;;
+        *)   GST_PACKAGE_ORIGIN="${withval}" ;;
+      esac
+    ], 
+    [GST_PACKAGE_ORIGIN="[Unknown package origin]"] dnl Default value
+  )
+  AC_MSG_NOTICE(Using $GST_PACKAGE_ORIGIN as package origin)
+  AC_DEFINE_UNQUOTED(GST_PACKAGE_ORIGIN, "$GST_PACKAGE_ORIGIN",
+      [package origin])
+  AC_SUBST(GST_PACKAGE_ORIGIN)
+])
+
+dnl sets WITH_PLUGINS to the list of plug-ins given as an argument
+dnl also clears GST_PLUGINS_ALL and GST_PLUGINS_SELECTED
+AC_DEFUN([AG_GST_ARG_WITH_PLUGINS],
+[
+  AC_ARG_WITH(plugins,
+    AC_HELP_STRING([--with-plugins],
+      [comma-separated list of dependencyless plug-ins to compile]),
+    [WITH_PLUGINS=$withval],
+    [WITH_PLUGINS=])
+
+  GST_PLUGINS_ALL=""
+  GST_PLUGINS_SELECTED=""
+
+  AC_SUBST(GST_PLUGINS_ALL)
+  AC_SUBST(GST_PLUGINS_SELECTED)
+])
+
+dnl AG_GST_CHECK_PLUGIN(PLUGIN-NAME)
+dnl
+dnl This macro adds the plug-in <PLUGIN-NAME> to GST_PLUGINS_ALL. Then it
+dnl checks if the plug-in is present in WITH_PLUGINS, and if so adds it to
+dnl GST_PLUGINS_SELECTED.
+dnl
+dnl The macro will call AM_CONDITIONAL(USE_PLUGIN_<PLUGIN-NAME>, ...) to allow
+dnl control of what is built in Makefile.ams.
+AC_DEFUN([AG_GST_CHECK_PLUGIN],
+[
+  GST_PLUGINS_ALL="$GST_PLUGINS_ALL [$1]"
+  if [[ -z "$WITH_PLUGINS" ]] || echo " [$WITH_PLUGINS] " | tr , ' ' | grep -i " [$1] " > /dev/null; then
+    GST_PLUGINS_SELECTED="$GST_PLUGINS_SELECTED [$1]"
+  fi
+  AM_CONDITIONAL([USE_PLUGIN_]translit([$1], a-z, A-Z), echo " $GST_PLUGINS_SELECTED " | grep -i " [$1] " > /dev/null)
+])
+
+dnl AG_GST_DISABLE_PLUGIN(PLUGIN-NAME)
+dnl
+dnl This macro disables the plug-in <PLUGIN-NAME> by removing it from
+dnl GST_PLUGINS_SELECTED.
+AC_DEFUN([AG_GST_DISABLE_PLUGIN],
+[
+  GST_PLUGINS_SELECTED=`echo " $GST_PLUGINS_SELECTED " | $SED -e 's/ [$1] / /'`
+  AM_CONDITIONAL([USE_PLUGIN_]translit([$1], a-z, A-Z), false)
+])
+
+AC_DEFUN([AG_GST_ARG_ENABLE_EXTERNAL],
+[
+  AG_GST_CHECK_FEATURE(EXTERNAL, [building of plug-ins with external deps],,
+    HAVE_EXTERNAL=yes, enabled,
+    [
+      AC_MSG_NOTICE(building external plug-ins)
+      BUILD_EXTERNAL="yes"
+    ],[
+      AC_MSG_WARN(all plug-ins with external dependencies will not be built)
+      BUILD_EXTERNAL="no"
+    ])
+  # make BUILD_EXTERNAL available to Makefile.am
+  AM_CONDITIONAL(BUILD_EXTERNAL, test "x$BUILD_EXTERNAL" = "xyes")
+])
+
+dnl experimental plug-ins; stuff that hasn't had the dust settle yet
+dnl read 'builds, but might not work'
+AC_DEFUN([AG_GST_ARG_ENABLE_EXPERIMENTAL],
+[
+  AG_GST_CHECK_FEATURE(EXPERIMENTAL, [building of experimental plug-ins],,
+    HAVE_EXPERIMENTAL=yes, disabled,
+    [
+      AC_MSG_WARN(building experimental plug-ins)
+      BUILD_EXPERIMENTAL="yes"
+    ],[
+      AC_MSG_NOTICE(not building experimental plug-ins)
+      BUILD_EXPERIMENTAL="no"
+    ])
+  # make BUILD_EXPERIMENTAL available to Makefile.am
+  AM_CONDITIONAL(BUILD_EXPERIMENTAL, test "x$BUILD_EXPERIMENTAL" = "xyes")
+])
+
+dnl broken plug-ins; stuff that doesn't seem to build at the moment
+AC_DEFUN([AG_GST_ARG_ENABLE_BROKEN],
+[
+  AG_GST_CHECK_FEATURE(BROKEN, [building of broken plug-ins],,
+    HAVE_BROKEN=yes, disabled,
+    [
+      AC_MSG_WARN([building broken plug-ins -- no bug reports on these, only patches ...])
+    ],[
+      AC_MSG_NOTICE([not building broken plug-ins])
+    ])
+])
diff --git a/common/m4/gst-check.m4 b/common/m4/gst-check.m4
new file mode 100755 (executable)
index 0000000..3f6b8ff
--- /dev/null
@@ -0,0 +1,138 @@
+dnl pkg-config-based checks for GStreamer modules and dependency modules
+
+dnl generic:
+dnl AG_GST_PKG_CHECK_MODULES([PREFIX], [WHICH], [REQUIRED])
+dnl sets HAVE_[$PREFIX], [$PREFIX]_*
+dnl AG_GST_CHECK_MODULES([PREFIX], [MODULE], [MINVER], [NAME], [REQUIRED])
+dnl sets HAVE_[$PREFIX], [$PREFIX]_*
+
+dnl specific:
+dnl AG_GST_CHECK_GST([MAJMIN], [MINVER], [REQUIRED])
+dnl   also sets/ACSUBSTs GST_TOOLS_DIR and GST_PLUGINS_DIR
+dnl AG_GST_CHECK_GST_BASE([MAJMIN], [MINVER], [REQUIRED])
+dnl AG_GST_CHECK_GST_GDP([MAJMIN], [MINVER], [REQUIRED])
+dnl AG_GST_CHECK_GST_CONTROLLER([MAJMIN], [MINVER], [REQUIRED])
+dnl AG_GST_CHECK_GST_CHECK([MAJMIN], [MINVER], [REQUIRED])
+dnl AG_GST_CHECK_GST_PLUGINS_BASE([MAJMIN], [MINVER], [REQUIRED])
+dnl   also sets/ACSUBSTs GSTPB_PLUGINS_DIR
+
+AC_DEFUN([AG_GST_PKG_CHECK_MODULES],
+[
+  which="[$2]"
+  dnl not required by default, since we use this mostly for plugin deps
+  required=ifelse([$3], , "no", [$3])
+
+  PKG_CHECK_MODULES([$1], $which,
+    [
+      HAVE_[$1]="yes"
+    ],
+    [
+      HAVE_[$1]="no"
+      AC_MSG_RESULT(no)
+      if test "x$required" = "xyes"; then
+        AC_MSG_ERROR($[$1]_PKG_ERRORS)
+      else
+        AC_MSG_NOTICE($[$1]_PKG_ERRORS)
+      fi
+    ])
+
+  dnl AC_SUBST of CFLAGS and LIBS was not done before automake 1.7
+  dnl It gets done automatically in automake >= 1.7, which we now require
+]))
+
+AC_DEFUN([AG_GST_CHECK_MODULES],
+[
+  module=[$2]
+  minver=[$3]
+  name="[$4]"
+  required=ifelse([$5], , "yes", [$5]) dnl required by default
+
+  PKG_CHECK_MODULES([$1], $module >= $minver,
+    [
+      HAVE_[$1]="yes"
+    ],
+    [
+      HAVE_[$1]="no"
+      AC_MSG_RESULT(no)
+      AC_MSG_NOTICE($[$1]_PKG_ERRORS)
+      if test "x$required" = "xyes"; then
+        AC_MSG_ERROR([no $module >= $minver ($name) found])
+      else
+        AC_MSG_NOTICE([no $module >= $minver ($name) found])
+      fi
+    ])
+
+  dnl AC_SUBST of CFLAGS and LIBS was not done before automake 1.7
+  dnl It gets done automatically in automake >= 1.7, which we now require
+]))
+
+AC_DEFUN([AG_GST_CHECK_GST],
+[
+  AG_GST_CHECK_MODULES(GST, gstreamer-[$1], [$2], [GStreamer], [$3])
+  dnl allow setting before calling this macro to override
+  if test -z $GST_TOOLS_DIR; then
+    GST_TOOLS_DIR=`$PKG_CONFIG --variable=toolsdir gstreamer-[$1]`
+    if test -z $GST_TOOLS_DIR; then
+      AC_MSG_ERROR(
+        [no tools dir set in GStreamer pkg-config file, core upgrade needed.])
+    fi
+  fi
+  AC_MSG_NOTICE([using GStreamer tools in $GST_TOOLS_DIR])
+  AC_SUBST(GST_TOOLS_DIR)
+
+  dnl check for where core plug-ins got installed
+  dnl this is used for unit tests
+  dnl allow setting before calling this macro to override
+  if test -z $GST_PLUGINS_DIR; then
+    GST_PLUGINS_DIR=`$PKG_CONFIG --variable=pluginsdir gstreamer-[$1]`
+    if test -z $GST_PLUGINS_DIR; then
+      AC_MSG_ERROR(
+        [no pluginsdir set in GStreamer pkg-config file, core upgrade needed.])
+    fi
+  fi
+  AC_MSG_NOTICE([using GStreamer plug-ins in $GST_PLUGINS_DIR])
+  AC_SUBST(GST_PLUGINS_DIR)
+])
+
+AC_DEFUN([AG_GST_CHECK_GST_BASE],
+[
+  AG_GST_CHECK_MODULES(GST_BASE, gstreamer-base-[$1], [$2],
+    [GStreamer Base Libraries], [$3])
+])
+  
+AC_DEFUN([AG_GST_CHECK_GST_GDP],
+[
+  AG_GST_CHECK_MODULES(GST_GDP, gstreamer-dataprotocol-[$1], [$2],
+    [GStreamer Data Protocol Library], [$3])
+])
+  
+AC_DEFUN([AG_GST_CHECK_GST_CONTROLLER],
+[
+  AG_GST_CHECK_MODULES(GST_CONTROLLER, gstreamer-controller-[$1], [$2],
+    [GStreamer Controller Library], [$3])
+])  
+
+AC_DEFUN([AG_GST_CHECK_GST_CHECK],
+[
+  AG_GST_CHECK_MODULES(GST_CHECK, gstreamer-check-[$1], [$2],
+    [GStreamer Check unittest Library], [$3])
+])
+
+AC_DEFUN([AG_GST_CHECK_GST_PLUGINS_BASE],
+[
+  AG_GST_CHECK_MODULES(GST_PLUGINS_BASE, gstreamer-plugins-base-[$1], [$2],
+    [GStreamer Base Plug-ins Library], [$3])
+
+  dnl check for where base plug-ins got installed
+  dnl this is used for unit tests
+  dnl allow setting before calling this macro to override
+  if test -z $GSTPB_PLUGINS_DIR; then
+    GSTPB_PLUGINS_DIR=`$PKG_CONFIG --variable=pluginsdir gstreamer-plugins-base-[$1]`
+    if test -z $GSTPB_PLUGINS_DIR; then
+      AC_MSG_ERROR(
+        [no pluginsdir set in GStreamer Base Plug-ins pkg-config file])
+    fi
+  fi
+  AC_MSG_NOTICE([using GStreamer Base Plug-ins in $GSTPB_PLUGINS_DIR])
+  AC_SUBST(GSTPB_PLUGINS_DIR)
+])
diff --git a/common/m4/gst-debuginfo.m4 b/common/m4/gst-debuginfo.m4
new file mode 100755 (executable)
index 0000000..b48854d
--- /dev/null
@@ -0,0 +1,46 @@
+AC_DEFUN([AG_GST_DEBUGINFO], [
+AC_ARG_ENABLE(debug,
+AC_HELP_STRING([--disable-debug],[disable addition of -g debugging info]),
+[case "${enableval}" in
+  yes) USE_DEBUG=yes ;;
+  no)  USE_DEBUG=no ;;
+  *) AC_MSG_ERROR(bad value ${enableval} for --enable-debug) ;;
+esac],
+[USE_DEBUG=yes]) dnl Default value
+
+AC_ARG_ENABLE(DEBUG,
+AC_HELP_STRING([--disable-DEBUG],[disables compilation of debugging messages]),
+[case "${enableval}" in
+  yes) ENABLE_DEBUG=yes ;;
+  no)  ENABLE_DEBUG=no ;;
+  *) AC_MSG_ERROR(bad value ${enableval} for --enable-DEBUG) ;;
+esac],
+[ENABLE_DEBUG=yes]) dnl Default value
+if test x$ENABLE_DEBUG = xyes; then
+  AC_DEFINE(GST_DEBUG_ENABLED, 1, [Define if DEBUG statements should be compiled in])
+fi
+
+AC_ARG_ENABLE(INFO,
+AC_HELP_STRING([--disable-INFO],[disables compilation of informational messages]),
+[case "${enableval}" in
+  yes) ENABLE_INFO=yes ;;
+  no)  ENABLE_INFO=no ;;
+  *) AC_MSG_ERROR(bad value ${enableval} for --enable-INFO) ;;
+esac],
+[ENABLE_INFO=yes]) dnl Default value
+if test x$ENABLE_INFO = xyes; then
+  AC_DEFINE(GST_INFO_ENABLED, 1, [Define if INFO statements should be compiled in])
+fi
+
+AC_ARG_ENABLE(debug-color,
+AC_HELP_STRING([--disable-debug-color],[disables color output of DEBUG and INFO output]),
+[case "${enableval}" in
+  yes) ENABLE_DEBUG_COLOR=yes ;;
+  no)  ENABLE_DEBUG_COLOR=no ;;
+  *) AC_MSG_ERROR(bad value ${enableval} for --enable-debug-color) ;;
+esac],
+[ENABLE_DEBUG_COLOR=yes]) dnl Default value
+if test "x$ENABLE_DEBUG_COLOR" = xyes; then
+  AC_DEFINE(GST_DEBUG_COLOR, 1, [Define if debugging messages should be colorized])
+fi
+])
diff --git a/common/m4/gst-default.m4 b/common/m4/gst-default.m4
new file mode 100755 (executable)
index 0000000..da1a81c
--- /dev/null
@@ -0,0 +1,45 @@
+dnl default elements used for tests and such
+
+dnl AG_GST_DEFAULT_ELEMENTS
+
+AC_DEFUN([AG_GST_DEFAULT_ELEMENTS],
+[
+  dnl decide on default elements
+  dnl FIXME: provide configure-time options for this
+  dnl FIXME: describe where exactly this gets used
+  dnl FIXME: decide if it's a problem that this could point to sinks from
+  dnl        depending plugin modules
+  DEFAULT_AUDIOSINK="autoaudiosink"
+  DEFAULT_VIDEOSINK="autovideosink"
+  DEFAULT_AUDIOSRC="alsasrc"
+  DEFAULT_VIDEOSRC="v4lsrc"
+  DEFAULT_VISUALIZER="goom"
+  case "$host" in
+    *-sun-* | *pc-solaris* )
+      DEFAULT_AUDIOSINK="sunaudiosink"
+      DEFAULT_VIDEOSINK="ximagesink"
+      DEFAULT_AUDIOSRC="sunaudiosrc"
+      ;;
+    *-darwin* )
+      DEFAULT_AUDIOSINK="osxaudiosink"
+      DEFAULT_AUDIOSRC="osxaudiosrc"
+      DEFAULT_VIDEOSINK="osxvideosink"
+      ;;
+  esac
+  
+  AC_SUBST(DEFAULT_AUDIOSINK)
+  AC_DEFINE_UNQUOTED(DEFAULT_AUDIOSINK, "$DEFAULT_AUDIOSINK",
+    [Default audio sink])
+  AC_SUBST(DEFAULT_AUDIOSRC)
+  AC_DEFINE_UNQUOTED(DEFAULT_AUDIOSRC, "$DEFAULT_AUDIOSRC",
+    [Default audio source])
+  AC_SUBST(DEFAULT_VIDEOSINK)
+  AC_DEFINE_UNQUOTED(DEFAULT_VIDEOSINK, "$DEFAULT_VIDEOSINK",
+    [Default video sink])
+  AC_SUBST(DEFAULT_VIDEOSRC)
+  AC_DEFINE_UNQUOTED(DEFAULT_VIDEOSRC, "$DEFAULT_VIDEOSRC",
+    [Default video source])
+  AC_SUBST(DEFAULT_VISUALIZER)
+  AC_DEFINE_UNQUOTED(DEFAULT_VISUALIZER, "$DEFAULT_VISUALIZER",
+    [Default visualizer])
+])
diff --git a/common/m4/gst-doc.m4 b/common/m4/gst-doc.m4
new file mode 100755 (executable)
index 0000000..7000c17
--- /dev/null
@@ -0,0 +1,148 @@
+AC_DEFUN([AG_GST_DOCBOOK_CHECK],
+[
+  dnl choose a location to install docbook docs in
+  if test "x$PACKAGE_TARNAME" = "x"
+  then
+    AC_MSG_ERROR([Internal error - PACKAGE_TARNAME not set])
+  fi
+  docdir="\$(datadir)/doc/$PACKAGE_TARNAME-$GST_MAJORMINOR"
+
+  dnl enable/disable docbook documentation building
+  AC_ARG_ENABLE(docbook,
+  AC_HELP_STRING([--enable-docbook],
+                 [use docbook to build documentation [default=no]]),,
+                 enable_docbook=no)
+
+  have_docbook=no
+
+  if test x$enable_docbook = xyes; then
+    dnl check if we actually have everything we need
+
+    dnl check for docbook tools
+    AC_CHECK_PROG(HAVE_DOCBOOK2PS, docbook2ps, yes, no)
+    AC_CHECK_PROG(HAVE_DOCBOOK2HTML, docbook2html, yes, no)
+    AC_CHECK_PROG(HAVE_JADETEX, jadetex, yes, no)
+    AC_CHECK_PROG(HAVE_PS2PDF, ps2pdf, yes, no)
+
+    # -V option appeared in 0.6.10
+    docbook2html_min_version=0.6.10
+    if test "x$HAVE_DOCBOOK2HTML" != "xno"; then
+      docbook2html_version=`docbook2html --version`
+      AC_MSG_CHECKING([docbook2html version ($docbook2html_version) >= $docbook2html_min_version])
+      if perl -w <<EOF
+        (\$min_version_major, \$min_version_minor, \$min_version_micro ) = "$docbook2html_min_version" =~ /(\d+)\.(\d+)\.(\d+)/;
+        (\$docbook2html_version_major, \$docbook2html_version_minor, \$docbook2html_version_micro ) = "$docbook2html_version" =~ /(\d+)\.(\d+)\.(\d+)/;
+        exit (((\$docbook2html_version_major > \$min_version_major) ||
+            ((\$docbook2html_version_major == \$min_version_major) &&
+             (\$docbook2html_version_minor >= \$min_version_minor)) ||
+            ((\$docbook2html_version_major == \$min_version_major) &&
+             (\$docbook2html_version_minor >= \$min_version_minor) &&
+             (\$docbook2html_version_micro >= \$min_version_micro)))
+            ? 0 : 1);
+EOF
+      then
+        AC_MSG_RESULT(yes)
+      else
+        AC_MSG_RESULT(no)
+        HAVE_DOCBOOK2HTML=no
+      fi
+    fi
+
+    dnl check if we can process docbook stuff
+    AS_DOCBOOK(have_docbook=yes, have_docbook=no)
+    dnl check for extra tools
+    AC_CHECK_PROG(HAVE_DVIPS, dvips, yes, no)
+    AC_CHECK_PROG(HAVE_XMLLINT, xmllint, yes, no)
+    dnl check for image conversion tools
+    AC_CHECK_PROG(HAVE_FIG2DEV, fig2dev, yes, no)
+    if test "x$HAVE_FIG2DEV" = "xno" ; then
+      AC_MSG_WARN([Did not find fig2dev (from xfig), images will not be generated.])
+    fi
+    dnl The following is a hack: if fig2dev doesn't display an error message
+    dnl for the desired type, we assume it supports it.
+    HAVE_FIG2DEV_EPS=no
+    if test "x$HAVE_FIG2DEV" = "xyes" ; then
+      fig2dev_quiet=`fig2dev -L eps </dev/null 2>&1 >/dev/null`
+      if test "x$fig2dev_quiet" = "x" ; then
+        HAVE_FIG2DEV_EPS=yes
+      fi
+    fi
+    HAVE_FIG2DEV_PNG=no
+    if test "x$HAVE_FIG2DEV" = "xyes" ; then
+      fig2dev_quiet=`fig2dev -L png </dev/null 2>&1 >/dev/null`
+      if test "x$fig2dev_quiet" = "x" ; then
+        HAVE_FIG2DEV_PNG=yes
+      fi
+    fi
+    HAVE_FIG2DEV_PDF=no
+    if test "x$HAVE_FIG2DEV" = "xyes" ; then
+      fig2dev_quiet=`fig2dev -L pdf </dev/null 2>&1 >/dev/null`
+      if test "x$fig2dev_quiet" = "x" ; then
+        HAVE_FIG2DEV_PDF=yes
+      fi
+    fi
+  
+    AC_CHECK_PROG(HAVE_PNGTOPNM, pngtopnm, yes, no)
+    AC_CHECK_PROG(HAVE_PNMTOPS,  pnmtops,  yes, no)
+    AC_CHECK_PROG(HAVE_EPSTOPDF, epstopdf, yes, no)
+  
+    dnl check if we can generate HTML
+    if test "x$HAVE_DOCBOOK2HTML" = "xyes" && \
+       test "x$enable_docbook" = "xyes" && \
+       test "x$HAVE_XMLLINT" = "xyes" && \
+       test "x$HAVE_FIG2DEV_PNG" = "xyes"; then
+      DOC_HTML=yes
+      AC_MSG_NOTICE(Will output HTML documentation)
+     else
+      DOC_HTML=no
+      AC_MSG_NOTICE(Will not output HTML documentation)
+    fi
+    
+    dnl check if we can generate PS
+    if test "x$HAVE_DOCBOOK2PS" = "xyes" && \
+       test "x$enable_docbook" = "xyes" && \
+       test "x$HAVE_XMLLINT" = "xyes" && \
+       test "x$HAVE_JADETEX" = "xyes" && \
+       test "x$HAVE_FIG2DEV_EPS" = "xyes" && \
+       test "x$HAVE_DVIPS" = "xyes" && \
+       test "x$HAVE_PNGTOPNM" = "xyes" && \
+       test "x$HAVE_PNMTOPS" = "xyes"; then
+      DOC_PS=yes
+      AC_MSG_NOTICE(Will output PS documentation)
+    else
+      DOC_PS=no
+      AC_MSG_NOTICE(Will not output PS documentation)
+    fi
+    
+    dnl check if we can generate PDF - using only ps2pdf
+    if test "x$DOC_PS" = "xyes" && \
+       test "x$enable_docbook" = "xyes" && \
+       test "x$HAVE_XMLLINT" = "xyes" && \
+       test "x$HAVE_PS2PDF" = "xyes"; then
+      DOC_PDF=yes
+      AC_MSG_NOTICE(Will output PDF documentation)
+    else
+      DOC_PDF=no
+      AC_MSG_NOTICE(Will not output PDF documentation)
+    fi
+
+    dnl if we don't have everything, we should disable
+    if test "x$have_docbook" != "xyes"; then
+      enable_docbook=no
+    fi
+  fi
+
+  dnl if we're going to install documentation, tell us where
+  if test "x$have_docbook" = "xyes"; then
+    AC_MSG_NOTICE(Installing documentation in $docdir)
+    AC_SUBST(docdir)
+  fi
+
+  AM_CONDITIONAL(ENABLE_DOCBOOK,      test x$enable_docbook = xyes)
+  AM_CONDITIONAL(DOC_HTML,            test x$DOC_HTML = xyes)
+  AM_CONDITIONAL(DOC_PDF,             test x$DOC_PDF = xyes)
+  AM_CONDITIONAL(DOC_PS,              test x$DOC_PS = xyes)
+])
diff --git a/common/m4/gst-error.m4 b/common/m4/gst-error.m4
new file mode 100755 (executable)
index 0000000..f97f9a6
--- /dev/null
@@ -0,0 +1,145 @@
+Dnl handle various error-related things
+
+dnl Thomas Vander Stichele <thomas@apestaart.org>
+dnl Tim-Philipp Müller <tim centricular net>
+
+dnl Last modification: 2008-02-18
+
+dnl AG_GST_SET_ERROR_CFLAGS([ADD-WERROR])
+dnl AG_GST_SET_ERROR_CXXFLAGS([ADD-WERROR])
+dnl AG_GST_SET_LEVEL_DEFAULT([IS-CVS-VERSION])
+
+
+dnl Sets ERROR_CFLAGS to something the compiler will accept.
+dnl AC_SUBST them so they are available in Makefile
+
+dnl -Wall is added if it is supported
+dnl -Werror is added if ADD-WERROR is not "no"
+
+dnl These flags can be overridden at make time:
+dnl make ERROR_CFLAGS=
+AC_DEFUN([AG_GST_SET_ERROR_CFLAGS],
+[
+  AC_REQUIRE([AC_PROG_CC])
+  AC_REQUIRE([AS_COMPILER_FLAG])
+
+  
+  dnl if we support -Wall, set it unconditionally
+  AS_COMPILER_FLAG(-Wall,
+                   ERROR_CFLAGS="-Wall",
+                   ERROR_CFLAGS="")
+  
+  dnl if asked for, add -Werror if supported
+  if test "x$1" != "xno"
+  then
+    AS_COMPILER_FLAG(-Werror, ERROR_CFLAGS="$ERROR_CFLAGS -Werror")
+
+    dnl if -Werror isn't suported, try -errwarn=%all (Sun Forte case)
+    if test "x$ERROR_CFLAGS" == "x"
+    then
+      AS_COMPILER_FLAG([-errwarn=%all], [
+          ERROR_CFLAGS="-errwarn=%all"
+          dnl try -errwarn=%all,no%E_EMPTY_DECLARATION,
+          dnl no%E_STATEMENT_NOT_REACHED,no%E_ARGUEMENT_MISMATCH,
+          dnl no%E_MACRO_REDEFINED (Sun Forte case)
+          dnl For Forte we need disable "empty declaration" warning produced by un-needed semicolon 
+          dnl "statement not reached" disabled because there is g_assert_not_reached () in some places
+          dnl "macro redefined" because of gst/gettext.h
+          dnl FIXME: is it really supposed to be 'ARGUEMENT' and not 'ARGUMENT'?
+          for f in 'no%E_EMPTY_DECLARATION' \
+                   'no%E_STATEMENT_NOT_REACHED' \
+                   'no%E_ARGUEMENT_MISMATCH' \
+                   'no%E_MACRO_REDEFINED'
+          do
+            AS_COMPILER_FLAG([-errwarn=%all,$f], [
+              ERROR_CFLAGS="$ERROR_CFLAGS,$f"
+            ])
+          done
+      ])
+    fi
+  fi
+
+  AC_SUBST(ERROR_CFLAGS)
+  AC_MSG_NOTICE([set ERROR_CFLAGS to $ERROR_CFLAGS])
+])
+
+dnl Sets ERROR_CXXFLAGS to something the compiler will accept.
+dnl AC_SUBST them so they are available in Makefile
+
+dnl -Wall is added if it is supported
+dnl -Werror is added if ADD-WERROR is not "no"
+
+dnl These flags can be overridden at make time:
+dnl make ERROR_CXXFLAGS=
+AC_DEFUN([AG_GST_SET_ERROR_CXXFLAGS],
+[
+  AC_REQUIRE([AC_PROG_CXX])
+  AC_REQUIRE([AS_CXX_COMPILER_FLAG])
+
+  
+  dnl if we support -Wall, set it unconditionally
+  AS_CXX_COMPILER_FLAG(-Wall, [
+      ERROR_CXXFLAGS="-Wall"
+  ], [
+      ERROR_CXXFLAGS=""
+  ])
+  
+  dnl if asked for, add -Werror if supported
+  if test "x$1" != "xno"
+  then
+    AS_CXX_COMPILER_FLAG(-Werror, werror_supported=yes, werror_supported=no)
+
+    if test "x$werror_supported" = "xyes"; then
+        ERROR_CXXFLAGS="$ERROR_CXXFLAGS -Werror"
+
+        dnl add exceptions
+        for f in '-Wno-non-virtual-dtor'
+        do
+          AS_CXX_COMPILER_FLAG([$f], ERROR_CXXFLAGS="$ERROR_CXXFLAGS $f")
+        done
+    else
+      dnl if -Werror isn't suported, try -errwarn=%all
+      AS_CXX_COMPILER_FLAG([-errwarn=%all], errwarnall=yes, errwarnall=no)
+      if test "x$errwarnall" = "xyes"; then
+        ERROR_CXXFLAGS="-errwarn=%all"
+        dnl try -errwarn=%all,no%E_EMPTY_DECLARATION,
+        dnl no%E_STATEMENT_NOT_REACHED,no%E_ARGUEMENT_MISMATCH,
+        dnl no%E_MACRO_REDEFINED (Sun Forte case)
+        dnl For Forte we need disable "empty declaration" warning produced by un-needed semicolon 
+        dnl "statement not reached" disabled because there is g_assert_not_reached () in some places
+        dnl "macro redefined" because of gst/gettext.h
+        dnl FIXME: is it really supposed to be 'ARGUEMENT' and not 'ARGUMENT'?
+        dnl FIXME: do any of these work with the c++ compiler? if not, why
+        dnl do we check at all?
+        for f in 'no%E_EMPTY_DECLARATION' \
+                 'no%E_STATEMENT_NOT_REACHED' \
+                 'no%E_ARGUEMENT_MISMATCH' \
+                 'no%E_MACRO_REDEFINED'
+        do
+          AS_CXX_COMPILER_FLAG([-errwarn=%all,$f], [
+            ERROR_CXXFLAGS="$ERROR_CXXFLAGS,$f"
+          ])
+        done
+      fi
+    fi
+  fi
+
+  AC_SUBST(ERROR_CXXFLAGS)
+  AC_MSG_NOTICE([set ERROR_CXXFLAGS to $ERROR_CXXFLAGS])
+])
+
+dnl Sets the default error level for debugging messages
+AC_DEFUN([AG_GST_SET_LEVEL_DEFAULT],
+[
+  dnl define correct errorlevel for debugging messages. We want to have
+  dnl GST_ERROR messages printed when running cvs builds
+  if test "x[$1]" = "xyes"; then
+    GST_LEVEL_DEFAULT=GST_LEVEL_ERROR
+  else
+    GST_LEVEL_DEFAULT=GST_LEVEL_NONE
+  fi
+  AC_DEFINE_UNQUOTED(GST_LEVEL_DEFAULT, $GST_LEVEL_DEFAULT,
+    [Default errorlevel to use])
+  dnl AC_SUBST so we can use it for win32/common/config.h
+  AC_SUBST(GST_LEVEL_DEFAULT)
+])
diff --git a/common/m4/gst-feature.m4 b/common/m4/gst-feature.m4
new file mode 100755 (executable)
index 0000000..c7fe156
--- /dev/null
@@ -0,0 +1,286 @@
+dnl Perform a check for a feature for GStreamer
+dnl Richard Boulton <richard-alsa@tartarus.org>
+dnl Thomas Vander Stichele <thomas@apestaart.org> added useful stuff
+dnl Last modification: 25/06/2001
+dnl
+dnl AG_GST_CHECK_FEATURE(FEATURE-NAME, FEATURE-DESCRIPTION,
+dnl                   DEPENDENT-PLUGINS, TEST-FOR-FEATURE,
+dnl                   DISABLE-BY-DEFAULT, ACTION-IF-USE, ACTION-IF-NOTUSE)
+dnl
+dnl This macro adds a command line argument to allow the user to enable
+dnl or disable a feature, and if the feature is enabled, performs a supplied
+dnl test to check if the feature is available.
+dnl
+dnl The test should define HAVE_<FEATURE-NAME> to "yes" or "no" depending
+dnl on whether the feature is available.
+dnl
+dnl The macro will set USE_<FEATURE-NAME> to "yes" or "no" depending on
+dnl whether the feature is to be used.
+dnl Thomas changed this, so that when USE_<FEATURE-NAME> was already set
+dnl to no, then it stays that way.
+dnl
+dnl The macro will call AM_CONDITIONAL(USE_<FEATURE-NAME>, ...) to allow
+dnl the feature to control what is built in Makefile.ams.  If you want
+dnl additional actions resulting from the test, you can add them with the
+dnl ACTION-IF-USE and ACTION-IF-NOTUSE parameters.
+dnl
+dnl FEATURE-NAME        is the name of the feature, and should be in
+dnl                     purely upper case characters.
+dnl FEATURE-DESCRIPTION is used to describe the feature in help text for
+dnl                     the command line argument.
+dnl DEPENDENT-PLUGINS   lists any plug-ins which depend on this feature.
+dnl TEST-FOR-FEATURE    is a test which sets HAVE_<FEATURE-NAME> to "yes"
+dnl                     or "no" depending on whether the feature is
+dnl                     available.
+dnl DISABLE-BY-DEFAULT  if "disabled", the feature is disabled by default,
+dnl                     if any other value, the feature is enabled by default.
+dnl ACTION-IF-USE       any extra actions to perform if the feature is to be
+dnl                     used.
+dnl ACTION-IF-NOTUSE    any extra actions to perform if the feature is not to
+dnl                     be used.
+dnl
+dnl
+dnl thomas :
+dnl we also added a history.
+dnl GST_PLUGINS_YES will contain all plugins to be built
+dnl                 that were checked through AG_GST_CHECK_FEATURE
+dnl GST_PLUGINS_NO will contain those that won't be built
+
+AC_DEFUN([AG_GST_CHECK_FEATURE],
+[echo
+AC_MSG_NOTICE(*** checking feature: [$2] ***)
+if test "x[$3]" != "x"
+then
+  AC_MSG_NOTICE(*** for plug-ins: [$3] ***)
+fi
+dnl
+builtin(define, [gst_endisable], ifelse($5, [disabled], [enable], [disable]))dnl
+dnl if it is set to NO, then don't even consider it for building
+NOUSE=
+if test "x$USE_[$1]" = "xno"; then
+  NOUSE="yes"
+fi
+AC_ARG_ENABLE(translit([$1], A-Z, a-z),
+  [  ]builtin(format, --%-26s gst_endisable %s, gst_endisable-translit([$1], A-Z, a-z), [$2]ifelse([$3],,,: [$3])),
+  [ case "${enableval}" in
+      yes) USE_[$1]=yes;;
+      no) USE_[$1]=no;;
+      *) AC_MSG_ERROR(bad value ${enableval} for --enable-translit([$1], A-Z, a-z)) ;;
+    esac],
+  [ USE_$1=]ifelse($5, [disabled], [no], [yes]))           dnl DEFAULT
+
+dnl *** set it back to no if it was preset to no
+if test "x$NOUSE" = "xyes"; then
+  USE_[$1]="no"
+  AC_MSG_WARN(*** $3 pre-configured not to be built)
+fi
+NOUSE=
+
+dnl *** If it's enabled
+
+if test x$USE_[$1] = xyes; then
+  dnl save compile variables before the test
+
+  gst_check_save_LIBS=$LIBS
+  gst_check_save_LDFLAGS=$LDFLAGS
+  gst_check_save_CFLAGS=$CFLAGS
+  gst_check_save_CPPFLAGS=$CPPFLAGS
+  gst_check_save_CXXFLAGS=$CXXFLAGS
+
+  HAVE_[$1]=no
+  dnl TEST_FOR_FEATURE
+  $4
+
+  LIBS=$gst_check_save_LIBS
+  LDFLAGS=$gst_check_save_LDFLAGS
+  CFLAGS=$gst_check_save_CFLAGS
+  CPPFLAGS=$gst_check_save_CPPFLAGS
+  CXXFLAGS=$gst_check_save_CXXFLAGS
+
+  dnl If it isn't found, unset USE_[$1]
+  if test x$HAVE_[$1] = xno; then
+    USE_[$1]=no
+  else
+    ifelse([$3], , :, [AC_MSG_NOTICE(*** These plugins will be built: [$3])])
+  fi
+fi
+dnl *** Warn if it's disabled or not found
+if test x$USE_[$1] = xyes; then
+  ifelse([$6], , :, [$6])
+  if test "x$3" != "x"; then
+    GST_PLUGINS_YES="\t[$3]\n$GST_PLUGINS_YES"
+  fi
+  AC_DEFINE(HAVE_[$1], , [Define to enable $2]ifelse($3,,, [ (used by $3)]).)
+else
+  ifelse([$3], , :, [AC_MSG_NOTICE(*** These plugins will not be built: [$3])])
+  if test "x$3" != "x"; then
+    GST_PLUGINS_NO="\t[$3]\n$GST_PLUGINS_NO"
+  fi
+  ifelse([$7], , :, [$7])
+fi
+dnl *** Define the conditional as appropriate
+AM_CONDITIONAL(USE_[$1], test x$USE_[$1] = xyes)
+])
+
+dnl Use a -config program which accepts --cflags and --libs parameters
+dnl to set *_CFLAGS and *_LIBS and check existence of a feature.
+dnl Richard Boulton <richard-alsa@tartarus.org>
+dnl Last modification: 26/06/2001
+dnl AG_GST_CHECK_CONFIGPROG(FEATURE-NAME, CONFIG-PROG-FILENAME, MODULES)
+dnl
+dnl This check was written for GStreamer: it should be renamed and checked
+dnl for portability if you decide to use it elsewhere.
+dnl
+AC_DEFUN([AG_GST_CHECK_CONFIGPROG],
+[
+  AC_PATH_PROG([$1]_CONFIG, [$2], no)
+  if test x$[$1]_CONFIG = xno; then
+    [$1]_LIBS=
+    [$1]_CFLAGS=
+    HAVE_[$1]=no
+  else
+    if [$2] --plugin-libs [$3] &> /dev/null; then
+      [$1]_LIBS=`[$2] --plugin-libs [$3]`
+    else
+      [$1]_LIBS=`[$2] --libs [$3]`
+    fi
+    [$1]_CFLAGS=`[$2] --cflags [$3]`
+    HAVE_[$1]=yes
+  fi
+  AC_SUBST([$1]_LIBS)
+  AC_SUBST([$1]_CFLAGS)
+])
+
+dnl Use AC_CHECK_LIB and AC_CHECK_HEADER to do both tests at once
+dnl sets HAVE_module if we have it
+dnl Richard Boulton <richard-alsa@tartarus.org>
+dnl Last modification: 26/06/2001
+dnl AG_GST_CHECK_LIBHEADER(FEATURE-NAME, LIB NAME, LIB FUNCTION, EXTRA LD FLAGS,
+dnl                     HEADER NAME, ACTION-IF-FOUND, ACTION-IF-NOT-FOUND)
+dnl
+dnl This check was written for GStreamer: it should be renamed and checked
+dnl for portability if you decide to use it elsewhere.
+dnl
+AC_DEFUN([AG_GST_CHECK_LIBHEADER],
+[
+  AC_CHECK_LIB([$2], [$3], HAVE_[$1]=yes, HAVE_[$1]=no,[$4])
+  if test "x$HAVE_[$1]" = "xyes"; then
+    AC_CHECK_HEADER([$5], :, HAVE_[$1]=no)
+    if test "x$HAVE_[$1]" = "xyes"; then
+      dnl execute what needs to be
+      ifelse([$6], , :, [$6])
+    else
+      ifelse([$7], , :, [$7])
+    fi
+  else
+    ifelse([$7], , :, [$7])
+  fi
+  AC_SUBST(HAVE_[$1])
+]
+)
+
+dnl 2004-02-14 Thomas - changed to get set properly and use proper output
+dnl 2003-06-27 Benjamin Otte - changed to make this work with gstconfig.h
+dnl
+dnl Add a subsystem --disable flag and all the necessary symbols and substitions
+dnl
+dnl AG_GST_CHECK_SUBSYSTEM_DISABLE(SYSNAME, [subsystem name])
+dnl
+AC_DEFUN([AG_GST_CHECK_SUBSYSTEM_DISABLE],
+[
+  dnl this define will replace each literal subsys_def occurrence with
+  dnl the lowercase hyphen-separated subsystem
+  dnl e.g. if $1 is GST_DEBUG then subsys_def will be a macro with gst-debug
+  define([subsys_def],translit([$1], _A-Z, -a-z))
+
+  AC_ARG_ENABLE(subsys_def,
+    AC_HELP_STRING(--disable-subsys_def, [disable $2]),
+    [
+      case "${enableval}" in
+        yes) GST_DISABLE_[$1]=no ;;
+        no) GST_DISABLE_[$1]=yes ;;
+        *) AC_MSG_ERROR([bad value ${enableval} for --enable-subsys_def]) ;;
+       esac
+    ],
+    [GST_DISABLE_[$1]=no]) dnl Default value
+
+  if test x$GST_DISABLE_[$1] = xyes; then
+    AC_MSG_NOTICE([disabled subsystem [$2]])
+    GST_DISABLE_[$1]_DEFINE="#define GST_DISABLE_$1 1"
+  else
+    GST_DISABLE_[$1]_DEFINE="/* #undef GST_DISABLE_$1 */"
+  fi
+  AC_SUBST(GST_DISABLE_[$1]_DEFINE)
+  undefine([subsys_def])
+])
+
+
+dnl Parse gstconfig.h for feature and defines add the symbols and substitions
+dnl
+dnl AG_GST_PARSE_SUBSYSTEM_DISABLE(GST_CONFIGPATH, FEATURE)
+dnl
+AC_DEFUN([AG_GST_PARSE_SUBSYSTEM_DISABLE],
+[
+  grep >/dev/null "#undef GST_DISABLE_$2" $1
+  if test $? = 0; then
+    GST_DISABLE_[$2]=0
+  else
+    GST_DISABLE_[$2]=1
+  fi
+  AC_SUBST(GST_DISABLE_[$2])
+])
+
+dnl Parse gstconfig.h and defines add the symbols and substitions
+dnl
+dnl GST_CONFIGPATH=`$PKG_CONFIG --variable=includedir gstreamer-1.0`"/gst/gstconfig.h"
+dnl AG_GST_PARSE_SUBSYSTEM_DISABLES(GST_CONFIGPATH)
+dnl
+AC_DEFUN([AG_GST_PARSE_SUBSYSTEM_DISABLES],
+[
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,GST_DEBUG)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,LOADSAVE)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,PARSE)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,TRACE)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,ALLOC_TRACE)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,REGISTRY)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,ENUMTYPES)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,INDEX)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,PLUGIN)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,URI)
+  AG_GST_PARSE_SUBSYSTEM_DISABLE($1,XML)
+])
+
+
+
+dnl relies on GST_PLUGINS_ALL, GST_PLUGINS_SELECTED, GST_PLUGINS_YES,
+dnl GST_PLUGINS_NO, and BUILD_EXTERNAL
+AC_DEFUN([AG_GST_OUTPUT_PLUGINS], [
+
+printf "configure: *** Plug-ins without external dependencies that will be built:\n"
+( for i in $GST_PLUGINS_SELECTED; do printf '\t'$i'\n'; done ) | sort
+printf "\n"
+
+printf "configure: *** Plug-ins without external dependencies that will NOT be built:\n"
+( for i in $GST_PLUGINS_ALL; do
+    case $GST_PLUGINS_SELECTED in
+      *$i*)
+       ;;
+      *)
+       printf '\t'$i'\n'
+       ;;
+    esac
+  done ) | sort
+printf "\n"
+
+if test "x$BUILD_EXTERNAL" = "xno"; then
+  printf "configure: *** No plug-ins with external dependencies will be built\n"
+else
+  printf "configure: *** Plug-ins with dependencies that will be built:"
+  printf "$GST_PLUGINS_YES\n" | sort
+  printf "\n"
+  printf "configure: *** Plug-ins with dependencies that will NOT be built:"
+  printf "$GST_PLUGINS_NO\n" | sort
+  printf "\n"
+fi
+])
+
diff --git a/common/m4/gst-function.m4 b/common/m4/gst-function.m4
new file mode 100755 (executable)
index 0000000..1216621
--- /dev/null
@@ -0,0 +1,63 @@
+dnl
+dnl Check for compiler mechanism to show functions in debugging
+dnl copied from an Ali patch floating on the internet
+dnl
+AC_DEFUN([AG_GST_CHECK_FUNCTION],[
+  dnl #1: __PRETTY_FUNCTION__
+  AC_MSG_CHECKING(whether $CC implements __PRETTY_FUNCTION__)
+  AC_CACHE_VAL(have_pretty_function,[
+    AC_TRY_LINK([#include <stdio.h>],
+                [printf("%s", __PRETTY_FUNCTION__);],
+                have_pretty_function=yes,
+                have_pretty_function=no)
+  ])
+  AC_MSG_RESULT($have_pretty_function)
+  if test "$have_pretty_function" = yes; then
+    AC_DEFINE(HAVE_PRETTY_FUNCTION, 1,
+              [defined if the compiler implements __PRETTY_FUNCTION__])
+  fi
+
+dnl #2: __FUNCTION__
+  AC_MSG_CHECKING(whether $CC implements __FUNCTION__)
+  AC_CACHE_VAL(have_function,[
+    AC_TRY_LINK([#include <stdio.h>],
+                [printf("%s", __FUNCTION__);],
+                have_function=yes,
+                have_function=no)
+  ])
+  AC_MSG_RESULT($have_function)
+  if test "$have_function" = yes; then
+    AC_DEFINE(HAVE_FUNCTION, 1,
+              [defined if the compiler implements __FUNCTION__])
+  fi
+
+dnl #3: __func__
+  AC_MSG_CHECKING(whether $CC implements __func__)
+  AC_CACHE_VAL(have_func,[
+    AC_TRY_LINK([#include <stdio.h>],
+                [printf("%s", __func__);],
+                have_func=yes,
+                have_func=no)
+  ])
+  AC_MSG_RESULT($have_func)
+  if test "$have_func" = yes; then
+    AC_DEFINE(HAVE_FUNC, 1,
+              [defined if the compiler implements __func__])
+  fi
+
+dnl now define FUNCTION to whatever works, and fallback to ""
+  if test "$have_pretty_function" = yes; then
+    function=__PRETTY_FUNCTION__
+  else
+    if test "$have_function" = yes; then
+      function=__FUNCTION__
+    else
+      if test "$have_func" = yes; then
+        function=__func__
+      else
+        function=\"\"
+      fi
+    fi
+  fi
+  AC_DEFINE_UNQUOTED(GST_FUNCTION, $function, [macro to use to show function name])
+])
diff --git a/common/m4/gst-gettext.m4 b/common/m4/gst-gettext.m4
new file mode 100755 (executable)
index 0000000..a63651b
--- /dev/null
@@ -0,0 +1,21 @@
+dnl gettext setup
+
+dnl AG_GST_GETTEXT([gettext-package])
+dnl defines GETTEXT_PACKAGE and LOCALEDIR
+
+AC_DEFUN([AG_GST_GETTEXT],
+[
+  if test "$USE_NLS" = "yes"; then
+    GETTEXT_PACKAGE=[$1]
+  else
+    GETTEXT_PACKAGE=[NULL]
+  fi
+  AC_SUBST(GETTEXT_PACKAGE)
+  AC_DEFINE_UNQUOTED([GETTEXT_PACKAGE], "$GETTEXT_PACKAGE",
+                     [gettext package name])
+
+  dnl define LOCALEDIR in config.h
+  AS_AC_EXPAND(LOCALEDIR, $datadir/locale)
+  AC_DEFINE_UNQUOTED([LOCALEDIR], "$LOCALEDIR",
+                     [gettext locale dir])
+])
diff --git a/common/m4/gst-glib2.m4 b/common/m4/gst-glib2.m4
new file mode 100755 (executable)
index 0000000..3060e5e
--- /dev/null
@@ -0,0 +1,25 @@
+dnl check for a minimum version of GLib
+
+dnl AG_GST_GLIB_CHECK([minimum-version-required])
+
+AC_DEFUN([AG_GST_GLIB_CHECK],
+[
+  dnl Minimum required version of GLib
+  GLIB_REQ=[$1]
+  if test "x$GLIB_REQ" = "x"
+  then
+    AC_MSG_ERROR([Please specify a required version for GLib 2.0])
+  fi
+  AC_SUBST(GLIB_REQ)
+
+  dnl Check for glib with everything
+  AG_GST_PKG_CHECK_MODULES(GLIB,
+    glib-2.0 >= $GLIB_REQ gobject-2.0 gthread-2.0 gmodule-no-export-2.0)
+
+  if test "x$HAVE_GLIB" = "xno"; then
+    AC_MSG_ERROR([This package requires GLib >= $GLIB_REQ to compile.])
+  fi
+
+  dnl for the poor souls who for example have glib in /usr/local
+  AS_SCRUB_INCLUDE(GLIB_CFLAGS)
+])
diff --git a/common/m4/gst-libxml2.m4 b/common/m4/gst-libxml2.m4
new file mode 100755 (executable)
index 0000000..7d978d3
--- /dev/null
@@ -0,0 +1,46 @@
+dnl call this macro with the minimum required version as an argument
+dnl this macro sets and AC_SUBSTs XML_CFLAGS and XML_LIBS
+dnl it also sets LIBXML_PKG, used for the pkg-config file
+
+AC_DEFUN([AG_GST_LIBXML2_CHECK],
+[
+  dnl Minimum required version of libxml2
+  dnl default to 2.4.9 if not specified
+  LIBXML2_REQ=ifelse([$1],,2.4.9,[$1])
+  AC_SUBST(LIBXML2_REQ)
+
+  dnl check for libxml2
+  PKG_CHECK_MODULES(XML, libxml-2.0 >= $LIBXML2_REQ, 
+                    HAVE_LIBXML2=yes, [
+                      AC_MSG_RESULT(no)
+                      HAVE_LIBXML2=no
+                    ])
+  if test "x$HAVE_LIBXML2" = "xyes"; then
+    AC_DEFINE(HAVE_LIBXML2, 1, [Define if libxml2 is available])
+  else
+    AC_MSG_ERROR([Need libxml2 for glib2 builds -- you should be able to do without it -- this needs fixing])
+  fi
+  dnl this is for the .pc file
+  LIBXML_PKG=', libxml-2.0' 
+  AC_SUBST(LIBXML_PKG)
+  AC_SUBST(XML_LIBS)
+  AC_SUBST(XML_CFLAGS)
+
+  dnl XML_LIBS might pull in -lz without zlib actually being on the system, so
+  dnl try linking with these LIBS and CFLAGS
+  ac_save_CFLAGS=$CFLAGS
+  ac_save_LIBS=$LIBS
+  CFLAGS="$CFLAGS $XML_CFLAGS"
+  LIBS="$LIBS $XML_LIBS"
+  AC_TRY_LINK([
+#include <libxml/tree.h>
+#include <stdio.h>
+],[ 
+/* function body */
+],
+    AC_MSG_NOTICE([Test xml2 program linked]),
+    AC_MSG_ERROR([Could not link libxml2 test program.  Check if you have the necessary dependencies.])
+  )
+  CFLAGS="$ac_save_CFLAGS"
+  LIBS="$ac_save_LIBS"
+])
diff --git a/common/m4/gst-parser.m4 b/common/m4/gst-parser.m4
new file mode 100755 (executable)
index 0000000..9cc0981
--- /dev/null
@@ -0,0 +1,63 @@
+AC_DEFUN([AG_GST_BISON_CHECK],
+[
+  dnl FIXME: check if AC_PROG_YACC is suitable here
+  dnl FIXME: make precious
+  AC_PATH_PROG(BISON_PATH, bison, no)
+  if test x$BISON_PATH = xno; then
+    AC_MSG_ERROR(Could not find bison)
+  fi
+
+  dnl check bison version
+  dnl FIXME 0.11: we need version >= 1.875 for the reentrancy support
+  dnl in the parser. If an older version is installed pre-generated
+  dnl sources are used. This should become a hard dependency for 0.11!
+  bison_min_version=1.875
+  bison_version=`$BISON_PATH --version | head -n 1 | sed 's/^.*) //' | sed 's/[[a-zA-Z]]*$//' | cut -d' ' -f1`
+  AC_MSG_CHECKING([bison version $bison_version >= $bison_min_version])
+
+  if perl -w <<EOF
+    exit ($bison_version < $bison_min_version) ? 0 : 1;
+EOF 
+  then 
+    AC_MSG_RESULT([yes])
+    AM_CONDITIONAL(GENERATE_PARSER, test -z $GENERATE_PARSER_TRUE)
+  else 
+    AC_MSG_RESULT([no, using pre-generated parser sources])
+    AM_CONDITIONAL(GENERATE_PARSER, false)
+  fi
+])
+
+AC_DEFUN([AG_GST_FLEX_CHECK],
+[
+  dnl we require flex for building the parser
+  AC_PATH_PROG(FLEX_PATH, flex, no)
+  if test x$FLEX_PATH = xno; then
+    AC_MSG_ERROR(Could not find flex)
+  fi
+  
+  dnl check flex version
+  dnl FIXME 0.11: we need version >= 2.5.31 for the reentrancy support
+  dnl in the parser. If an older version is installed pre-generated
+  dnl sources are used. This should become a hard dependency for 0.11!
+  flex_min_version=2.5.31
+  flex_version=`$FLEX_PATH --version | head -n 1 | sed 's/^.* //' | sed 's/[[a-zA-Z]]*$//' | cut -d' ' -f1`
+  AC_MSG_CHECKING([flex version $flex_version >= $flex_min_version])
+  if perl -w <<EOF
+    (\$min_version_major, \$min_version_minor, \$min_version_micro ) = "$flex_min_version" =~ /(\d+)\.(\d+)\.(\d+)/;
+    (\$flex_version_major, \$flex_version_minor, \$flex_version_micro ) = "$flex_version" =~ /(\d+)\.(\d+)\.(\d+)/;
+    exit (((\$flex_version_major > \$min_version_major) ||
+     ((\$flex_version_major == \$min_version_major) &&
+      (\$flex_version_minor > \$min_version_minor)) ||
+     ((\$flex_version_major == \$min_version_major) &&
+      (\$flex_version_minor == \$min_version_minor) &&
+      (\$flex_version_micro >= \$min_version_micro)))
+     ? 0 : 1);
+EOF
+  then
+    AC_MSG_RESULT(yes)
+    AM_CONDITIONAL(GENERATE_PARSER, test -z $GENERATE_PARSER_TRUE)
+  else
+    AC_MSG_RESULT([no, using pre-generated parser sources])
+    AM_CONDITIONAL(GENERATE_PARSER, false)
+  fi
+])
diff --git a/common/m4/gst-plugin-docs.m4 b/common/m4/gst-plugin-docs.m4
new file mode 100755 (executable)
index 0000000..29ebbd6
--- /dev/null
@@ -0,0 +1,47 @@
+dnl AG_GST_PYXML_CHECK([MINIMUM-PYTHON-VERSION])
+
+AC_DEFUN([AG_GST_PYXML_CHECK],
+[
+  AC_BEFORE([AS_PATH_PYTHON],[$0])dnl find python first
+
+  have_pyxml=no
+  if test "x$PYTHON" != x; then
+    AC_MSG_CHECKING([pyxml])
+    if $PYTHON -c "from xml.dom.ext.reader import Sax2" 2>/dev/null \
+      && $PYTHON -c "from xml.dom.NodeFilter import NodeFilter" 2>/dev/null; then
+      AC_MSG_RESULT(yes)
+      have_pyxml=yes
+    else
+      AC_MSG_RESULT(no)
+    fi
+  fi
+])
+
+dnl AG_GST_PLUGIN_DOCS([MINIMUM-GTK-DOC-VERSION],[MINIMUM-PYTHON-VERSION])
+dnl 
+dnl checks for prerequisites for the common/mangle-tmpl.py script
+dnl used when building the plugin documentation
+
+AC_DEFUN([AG_GST_PLUGIN_DOCS],
+[
+  AC_BEFORE([GTK_DOC_CHECK],[$0])dnl check for gtk-doc first
+
+  if test x$enable_gtk_doc = xyes -a x$have_gtk_doc = xyes; then
+    AG_GST_PYXML_CHECK([$1])
+  fi
+
+  build_plugin_docs=no
+  AC_MSG_CHECKING([whether to build plugin documentation])
+  if test x$enable_gtk_doc = xyes -a x$have_gtk_doc = xyes; then
+    if test "x$have_pyxml" != xyes; then
+      AC_MSG_RESULT([no (pyxml not installed)])
+    else
+      build_plugin_docs=yes
+      AC_MSG_RESULT([yes])
+    fi
+  else
+    AC_MSG_RESULT([no (gtk-doc disabled or not available)])
+  fi
+
+  AM_CONDITIONAL(ENABLE_PLUGIN_DOCS, test x$build_plugin_docs = xyes)
+])
diff --git a/common/m4/gst-plugindir.m4 b/common/m4/gst-plugindir.m4
new file mode 100755 (executable)
index 0000000..09989d0
--- /dev/null
@@ -0,0 +1,17 @@
+dnl AG_GST_SET_PLUGINDIR
+
+dnl AC_DEFINE PLUGINDIR to the full location where plug-ins will be installed
+dnl AC_SUBST plugindir, to be used in Makefile.am's
+
+AC_DEFUN([AG_GST_SET_PLUGINDIR],
+[
+  dnl define location of plugin directory
+  AS_AC_EXPAND(PLUGINDIR, ${libdir}/gstreamer-$GST_MAJORMINOR)
+  AC_DEFINE_UNQUOTED(PLUGINDIR, "$PLUGINDIR",
+    [directory where plugins are located])
+  AC_MSG_NOTICE([Using $PLUGINDIR as the plugin install location])
+
+  dnl plugin directory configure-time variable for use in Makefile.am
+  plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
+  AC_SUBST(plugindir)
+])
diff --git a/common/m4/gst-valgrind.m4 b/common/m4/gst-valgrind.m4
new file mode 100755 (executable)
index 0000000..93c2635
--- /dev/null
@@ -0,0 +1,35 @@
+AC_DEFUN([AG_GST_VALGRIND_CHECK],
+[
+  dnl valgrind inclusion
+  AC_ARG_ENABLE(valgrind,
+    AC_HELP_STRING([--disable-valgrind], [disable run-time valgrind detection]),
+    [
+      case "${enableval}" in
+        yes) USE_VALGRIND="$USE_DEBUG" ;;
+        no)  USE_VALGRIND=no ;;
+        *) AC_MSG_ERROR(bad value ${enableval} for --enable-valgrind) ;;
+      esac],
+    [
+      USE_VALGRIND="$USE_DEBUG"
+    ]) dnl Default value
+
+  VALGRIND_REQ="2.1"
+  if test "x$USE_VALGRIND" = xyes; then
+    PKG_CHECK_MODULES(VALGRIND, valgrind > $VALGRIND_REQ,
+      USE_VALGRIND="yes",
+      [
+        USE_VALGRIND="no"
+        AC_MSG_RESULT([no])
+      ])
+  fi
+
+  if test "x$USE_VALGRIND" = xyes; then
+    AC_DEFINE(HAVE_VALGRIND, 1, [Define if valgrind should be used])
+    AC_MSG_NOTICE(Using extra code paths for valgrind)
+  fi
+  AC_SUBST(VALGRIND_CFLAGS)
+  AC_SUBST(VALGRIND_LIBS)
+  
+  AC_PATH_PROG(VALGRIND_PATH, valgrind, no)
+  AM_CONDITIONAL(HAVE_VALGRIND, test ! "x$VALGRIND_PATH" = "xno")
+])
diff --git a/common/m4/gst-x11.m4 b/common/m4/gst-x11.m4
new file mode 100644 (file)
index 0000000..d3baf2d
--- /dev/null
@@ -0,0 +1,70 @@
+dnl macros for X-related detections
+dnl AC_SUBST's HAVE_X, X_CFLAGS, X_LIBS
+AC_DEFUN([AG_GST_CHECK_X],
+[
+  AC_PATH_XTRA
+  ac_cflags_save="$CFLAGS"
+  ac_cppflags_save="$CPPFLAGS"
+  CFLAGS="$CFLAGS $X_CFLAGS"
+  CPPFLAGS="$CPPFLAGS $X_CFLAGS"
+
+  dnl now try to find the HEADER
+  AC_CHECK_HEADER(X11/Xlib.h, HAVE_X="yes", HAVE_X="no")
+
+  if test "x$HAVE_X" = "xno"
+  then
+    AC_MSG_NOTICE([cannot find X11 development files])
+  else
+    dnl this is much more than we want
+    X_LIBS="$X_LIBS $X_PRE_LIBS $X_EXTRA_LIBS"
+    dnl AC_PATH_XTRA only defines the path needed to find the X libs,
+    dnl it does not add the libs; therefore we add them here
+    X_LIBS="$X_LIBS -lX11"
+    AC_SUBST(X_CFLAGS)
+    AC_SUBST(X_LIBS)
+  fi
+  AC_SUBST(HAVE_X)
+
+  CFLAGS="$ac_cflags_save"
+  CPPFLAGS="$ac_cppflags_save"
+])
+
+dnl *** XVideo ***
+dnl Look for the PIC library first, Debian requires it.
+dnl Check debian-devel archives for gory details.
+dnl 20020110:
+dnl At the moment XFree86 doesn't distribute shared libXv due
+dnl to unstable API.  On many platforms you CAN NOT link a shared
+dnl lib to a static non-PIC lib.  This is what the xvideo GStreamer
+dnl plug-in wants to do.  So Debian distributes a PIC compiled
+dnl version of the static lib for plug-ins to link to when it is
+dnl inappropriate to link the main application to libXv directly.
+dnl FIXME: add check if this platform can support linking to a
+dnl        non-PIC libXv, if not then don not use Xv.
+dnl FIXME: perhaps warn user if they have a shared libXv since
+dnl        this is an error until XFree86 starts shipping one
+AC_DEFUN([AG_GST_CHECK_XV],
+[
+  if test x$HAVE_X = xyes; then
+    AC_CHECK_LIB(Xv_pic, XvQueryExtension,
+                 HAVE_XVIDEO="yes", HAVE_XVIDEO="no",
+                 $X_LIBS -lXext)
+
+    if test x$HAVE_XVIDEO = xyes; then
+      XVIDEO_LIBS="-lXv_pic -lXext"
+      AC_SUBST(XVIDEO_LIBS)
+    else
+      dnl try again using something else if we didn't find it first
+      if test x$HAVE_XVIDEO = xno; then
+        AC_CHECK_LIB(Xv, XvQueryExtension,
+                   HAVE_XVIDEO="yes", HAVE_XVIDEO="no",
+                   $X_LIBS -lXext)
+
+        if test x$HAVE_XVIDEO = xyes; then
+          XVIDEO_LIBS="-lXv -lXext"
+          AC_SUBST(XVIDEO_LIBS)
+        fi
+      fi
+    fi
+  fi
+])
diff --git a/common/m4/gst.m4 b/common/m4/gst.m4
new file mode 100755 (executable)
index 0000000..04b466f
--- /dev/null
@@ -0,0 +1,10 @@
+dnl AG_GST_INIT
+dnl sets up use of GStreamer configure.ac macros
+dnl all GStreamer autoconf macros are prefixed
+dnl with AG_GST_ for public macros
+dnl with _AG_GST_ for private macros
+
+AC_DEFUN([AG_GST_INIT],
+[
+  m4_pattern_forbid(^_?AG_GST_)
+])
diff --git a/common/m4/gtk-doc.m4 b/common/m4/gtk-doc.m4
new file mode 100755 (executable)
index 0000000..57040aa
--- /dev/null
@@ -0,0 +1,56 @@
+dnl -*- mode: autoconf -*-
+
+# serial 1
+
+dnl Usage:
+dnl   GTK_DOC_CHECK([minimum-gtk-doc-version])
+AC_DEFUN([GTK_DOC_CHECK],
+[
+  AC_BEFORE([AC_PROG_LIBTOOL],[$0])dnl setup libtool first
+  AC_BEFORE([AM_PROG_LIBTOOL],[$0])dnl setup libtool first
+  dnl for overriding the documentation installation directory
+  AC_ARG_WITH(html-dir,
+    AC_HELP_STRING([--with-html-dir=PATH], [path to installed docs]),,
+    [with_html_dir='${datadir}/gtk-doc/html'])
+  HTML_DIR="$with_html_dir"
+  AC_SUBST(HTML_DIR)
+
+  dnl enable/disable documentation building
+  AC_ARG_ENABLE(gtk-doc,
+    AC_HELP_STRING([--enable-gtk-doc],
+                   [use gtk-doc to build documentation [default=no]]),,
+    enable_gtk_doc=no)
+
+  have_gtk_doc=no
+  if test x$enable_gtk_doc = xyes; then
+    if test -z "$PKG_CONFIG"; then
+      AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
+    fi
+    if test "$PKG_CONFIG" != "no" && $PKG_CONFIG --exists gtk-doc; then
+      have_gtk_doc=yes
+    fi
+    if test -z "$SED"; then
+      AC_PROG_SED
+    fi
+
+dnl do we want to do a version check?
+ifelse([$1],[],,
+    [gtk_doc_min_version=$1
+    if test "$have_gtk_doc" = yes; then
+      AC_MSG_CHECKING([gtk-doc version >= $gtk_doc_min_version])
+      if $PKG_CONFIG --atleast-version $gtk_doc_min_version gtk-doc; then
+        AC_MSG_RESULT(yes)
+      else
+        AC_MSG_RESULT(no)
+        have_gtk_doc=no
+      fi
+    fi
+])
+    if test "$have_gtk_doc" != yes; then
+      enable_gtk_doc=no
+    fi
+  fi
+
+  AM_CONDITIONAL(ENABLE_GTK_DOC, test x$enable_gtk_doc = xyes)
+  AM_CONDITIONAL(GTK_DOC_USE_LIBTOOL, test -n "$LIBTOOL")
+])
diff --git a/common/m4/iconv.m4 b/common/m4/iconv.m4
new file mode 100755 (executable)
index 0000000..c5f3579
--- /dev/null
@@ -0,0 +1,103 @@
+# iconv.m4 serial AM4 (gettext-0.11.3)
+dnl Copyright (C) 2000-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([AM_ICONV_LINKFLAGS_BODY],
+[
+  dnl Prerequisites of AC_LIB_LINKFLAGS_BODY.
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+
+  dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV
+  dnl accordingly.
+  AC_LIB_LINKFLAGS_BODY([iconv])
+])
+
+AC_DEFUN([AM_ICONV_LINK],
+[
+  dnl Some systems have iconv in libc, some have it in libiconv (OSF/1 and
+  dnl those with the standalone portable GNU libiconv installed).
+
+  dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV
+  dnl accordingly.
+  AC_REQUIRE([AM_ICONV_LINKFLAGS_BODY])
+
+  dnl Add $INCICONV to CPPFLAGS before performing the following checks,
+  dnl because if the user has installed libiconv and not disabled its use
+  dnl via --without-libiconv-prefix, he wants to use it. The first
+  dnl AC_TRY_LINK will then fail, the second AC_TRY_LINK will succeed.
+  am_save_CPPFLAGS="$CPPFLAGS"
+  AC_LIB_APPENDTOVAR([CPPFLAGS], [$INCICONV])
+
+  AC_CACHE_CHECK(for iconv, am_cv_func_iconv, [
+    am_cv_func_iconv="no, consider installing GNU libiconv"
+    am_cv_lib_iconv=no
+    AC_TRY_LINK([#include <stdlib.h>
+#include <iconv.h>],
+      [iconv_t cd = iconv_open("","");
+       iconv(cd,NULL,NULL,NULL,NULL);
+       iconv_close(cd);],
+      am_cv_func_iconv=yes)
+    if test "$am_cv_func_iconv" != yes; then
+      am_save_LIBS="$LIBS"
+      LIBS="$LIBS $LIBICONV"
+      AC_TRY_LINK([#include <stdlib.h>
+#include <iconv.h>],
+        [iconv_t cd = iconv_open("","");
+         iconv(cd,NULL,NULL,NULL,NULL);
+         iconv_close(cd);],
+        am_cv_lib_iconv=yes
+        am_cv_func_iconv=yes)
+      LIBS="$am_save_LIBS"
+    fi
+  ])
+  if test "$am_cv_func_iconv" = yes; then
+    AC_DEFINE(HAVE_ICONV, 1, [Define if you have the iconv() function.])
+  fi
+  if test "$am_cv_lib_iconv" = yes; then
+    AC_MSG_CHECKING([how to link with libiconv])
+    AC_MSG_RESULT([$LIBICONV])
+  else
+    dnl If $LIBICONV didn't lead to a usable library, we don't need $INCICONV
+    dnl either.
+    CPPFLAGS="$am_save_CPPFLAGS"
+    LIBICONV=
+    LTLIBICONV=
+  fi
+  AC_SUBST(LIBICONV)
+  AC_SUBST(LTLIBICONV)
+])
+
+AC_DEFUN([AM_ICONV],
+[
+  AM_ICONV_LINK
+  if test "$am_cv_func_iconv" = yes; then
+    AC_MSG_CHECKING([for iconv declaration])
+    AC_CACHE_VAL(am_cv_proto_iconv, [
+      AC_TRY_COMPILE([
+#include <stdlib.h>
+#include <iconv.h>
+extern
+#ifdef __cplusplus
+"C"
+#endif
+#if defined(__STDC__) || defined(__cplusplus)
+size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
+#else
+size_t iconv();
+#endif
+], [], am_cv_proto_iconv_arg1="", am_cv_proto_iconv_arg1="const")
+      am_cv_proto_iconv="extern size_t iconv (iconv_t cd, $am_cv_proto_iconv_arg1 char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);"])
+    am_cv_proto_iconv=`echo "[$]am_cv_proto_iconv" | tr -s ' ' | sed -e 's/( /(/'`
+    AC_MSG_RESULT([$]{ac_t:-
+         }[$]am_cv_proto_iconv)
+    AC_DEFINE_UNQUOTED(ICONV_CONST, $am_cv_proto_iconv_arg1,
+      [Define as const if the declaration of iconv() needs const.])
+  fi
+])
diff --git a/common/m4/isc-posix.m4 b/common/m4/isc-posix.m4
new file mode 100755 (executable)
index 0000000..1319dd1
--- /dev/null
@@ -0,0 +1,26 @@
+# isc-posix.m4 serial 2 (gettext-0.11.2)
+dnl Copyright (C) 1995-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+# This file is not needed with autoconf-2.53 and newer.  Remove it in 2005.
+
+# This test replaces the one in autoconf.
+# Currently this macro should have the same name as the autoconf macro
+# because gettext's gettext.m4 (distributed in the automake package)
+# still uses it.  Otherwise, the use in gettext.m4 makes autoheader
+# give these diagnostics:
+#   configure.in:556: AC_TRY_COMPILE was called before AC_ISC_POSIX
+#   configure.in:556: AC_TRY_RUN was called before AC_ISC_POSIX
+
+undefine([AC_ISC_POSIX])
+
+AC_DEFUN([AC_ISC_POSIX],
+  [
+    dnl This test replaces the obsolescent AC_ISC_POSIX kludge.
+    AC_CHECK_LIB(cposix, strerror, [LIBS="$LIBS -lcposix"])
+  ]
+)
diff --git a/common/m4/lib-ld.m4 b/common/m4/lib-ld.m4
new file mode 100755 (executable)
index 0000000..ddb5732
--- /dev/null
@@ -0,0 +1,97 @@
+# lib-ld.m4 serial 1 (gettext-0.11)
+dnl Copyright (C) 1996-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl Subroutines of libtool.m4,
+dnl with replacements s/AC_/AC_LIB/ and s/lt_cv/acl_cv/ to avoid collision
+dnl with libtool.m4.
+
+dnl From libtool-1.4. Sets the variable with_gnu_ld to yes or no.
+AC_DEFUN([AC_LIB_PROG_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], acl_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU ld's only accept -v.
+if $LD -v 2>&1 </dev/null | egrep '(GNU|with BFD)' 1>&5; then
+  acl_cv_prog_gnu_ld=yes
+else
+  acl_cv_prog_gnu_ld=no
+fi])
+with_gnu_ld=$acl_cv_prog_gnu_ld
+])
+
+dnl From libtool-1.4. Sets the variable LD.
+AC_DEFUN([AC_LIB_PROG_LD],
+[AC_ARG_WITH(gnu-ld,
+[  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]],
+test "$withval" = no || with_gnu_ld=yes, with_gnu_ld=no)
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  AC_MSG_CHECKING([for ld used by GCC])
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [[\\/]* | [A-Za-z]:[\\/]*)]
+      [re_direlt='/[^/][^/]*/\.\./']
+      # Canonicalize the path of ld
+      ac_prog=`echo $ac_prog| sed 's%\\\\%/%g'`
+      while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
+       ac_prog=`echo $ac_prog| sed "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(acl_cv_path_LD,
+[if test -z "$LD"; then
+  IFS="${IFS=  }"; ac_save_ifs="$IFS"; IFS="${IFS}${PATH_SEPARATOR-:}"
+  for ac_dir in $PATH; do
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      acl_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some GNU ld's only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      if "$acl_cv_path_LD" -v 2>&1 < /dev/null | egrep '(GNU|with BFD)' > /dev/null; then
+       test "$with_gnu_ld" != no && break
+      else
+       test "$with_gnu_ld" != yes && break
+      fi
+    fi
+  done
+  IFS="$ac_save_ifs"
+else
+  acl_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$acl_cv_path_LD"
+if test -n "$LD"; then
+  AC_MSG_RESULT($LD)
+else
+  AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+AC_LIB_PROG_LD_GNU
+])
diff --git a/common/m4/lib-link.m4 b/common/m4/lib-link.m4
new file mode 100755 (executable)
index 0000000..6b94251
--- /dev/null
@@ -0,0 +1,554 @@
+# lib-link.m4 serial 3 (gettext-0.11.3)
+dnl Copyright (C) 2001-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+dnl AC_LIB_LINKFLAGS(name [, dependencies]) searches for libname and
+dnl the libraries corresponding to explicit and implicit dependencies.
+dnl Sets and AC_SUBSTs the LIB${NAME} and LTLIB${NAME} variables and
+dnl augments the CPPFLAGS variable.
+AC_DEFUN([AC_LIB_LINKFLAGS],
+[
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+  define([Name],[translit([$1],[./-], [___])])
+  define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+                               [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
+  AC_CACHE_CHECK([how to link with lib[]$1], [ac_cv_lib[]Name[]_libs], [
+    AC_LIB_LINKFLAGS_BODY([$1], [$2])
+    ac_cv_lib[]Name[]_libs="$LIB[]NAME"
+    ac_cv_lib[]Name[]_ltlibs="$LTLIB[]NAME"
+    ac_cv_lib[]Name[]_cppflags="$INC[]NAME"
+  ])
+  LIB[]NAME="$ac_cv_lib[]Name[]_libs"
+  LTLIB[]NAME="$ac_cv_lib[]Name[]_ltlibs"
+  INC[]NAME="$ac_cv_lib[]Name[]_cppflags"
+  AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME)
+  AC_SUBST([LIB]NAME)
+  AC_SUBST([LTLIB]NAME)
+  dnl Also set HAVE_LIB[]NAME so that AC_LIB_HAVE_LINKFLAGS can reuse the
+  dnl results of this search when this library appears as a dependency.
+  HAVE_LIB[]NAME=yes
+  undefine([Name])
+  undefine([NAME])
+])
+
+dnl AC_LIB_HAVE_LINKFLAGS(name, dependencies, includes, testcode)
+dnl searches for libname and the libraries corresponding to explicit and
+dnl implicit dependencies, together with the specified include files and
+dnl the ability to compile and link the specified testcode. If found, it
+dnl sets and AC_SUBSTs HAVE_LIB${NAME}=yes and the LIB${NAME} and
+dnl LTLIB${NAME} variables and augments the CPPFLAGS variable, and
+dnl #defines HAVE_LIB${NAME} to 1. Otherwise, it sets and AC_SUBSTs
+dnl HAVE_LIB${NAME}=no and LIB${NAME} and LTLIB${NAME} to empty.
+AC_DEFUN([AC_LIB_HAVE_LINKFLAGS],
+[
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  AC_REQUIRE([AC_LIB_RPATH])
+  define([Name],[translit([$1],[./-], [___])])
+  define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+                               [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
+
+  dnl Search for lib[]Name and define LIB[]NAME, LTLIB[]NAME and INC[]NAME
+  dnl accordingly.
+  AC_LIB_LINKFLAGS_BODY([$1], [$2])
+
+  dnl Add $INC[]NAME to CPPFLAGS before performing the following checks,
+  dnl because if the user has installed lib[]Name and not disabled its use
+  dnl via --without-lib[]Name-prefix, he wants to use it.
+  ac_save_CPPFLAGS="$CPPFLAGS"
+  AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME)
+
+  AC_CACHE_CHECK([for lib[]$1], [ac_cv_lib[]Name], [
+    ac_save_LIBS="$LIBS"
+    LIBS="$LIBS $LIB[]NAME"
+    AC_TRY_LINK([$3], [$4], [ac_cv_lib[]Name=yes], [ac_cv_lib[]Name=no])
+    LIBS="$ac_save_LIBS"
+  ])
+  if test "$ac_cv_lib[]Name" = yes; then
+    HAVE_LIB[]NAME=yes
+    AC_DEFINE([HAVE_LIB]NAME, 1, [Define if you have the $1 library.])
+    AC_MSG_CHECKING([how to link with lib[]$1])
+    AC_MSG_RESULT([$LIB[]NAME])
+  else
+    HAVE_LIB[]NAME=no
+    dnl If $LIB[]NAME didn't lead to a usable library, we don't need
+    dnl $INC[]NAME either.
+    CPPFLAGS="$ac_save_CPPFLAGS"
+    LIB[]NAME=
+    LTLIB[]NAME=
+  fi
+  AC_SUBST([HAVE_LIB]NAME)
+  AC_SUBST([LIB]NAME)
+  AC_SUBST([LTLIB]NAME)
+  undefine([Name])
+  undefine([NAME])
+])
+
+dnl Determine the platform dependent parameters needed to use rpath:
+dnl libext, shlibext, hardcode_libdir_flag_spec, hardcode_libdir_separator,
+dnl hardcode_direct, hardcode_minus_L,
+dnl sys_lib_search_path_spec, sys_lib_dlsearch_path_spec.
+AC_DEFUN([AC_LIB_RPATH],
+[
+  AC_REQUIRE([AC_PROG_CC])                dnl we use $CC, $GCC, $LDFLAGS
+  AC_REQUIRE([AC_LIB_PROG_LD])            dnl we use $LD, $with_gnu_ld
+  AC_REQUIRE([AC_CANONICAL_HOST])         dnl we use $host
+  AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT]) dnl we use $ac_aux_dir
+  AC_CACHE_CHECK([for shared library run path origin], acl_cv_rpath, [
+    CC="$CC" GCC="$GCC" LDFLAGS="$LDFLAGS" LD="$LD" with_gnu_ld="$with_gnu_ld" \
+    ${CONFIG_SHELL-/bin/sh} "$ac_aux_dir/config.rpath" "$host" > conftest.sh
+    . ./conftest.sh
+    rm -f ./conftest.sh
+    acl_cv_rpath=done
+  ])
+  wl="$acl_cv_wl"
+  libext="$acl_cv_libext"
+  shlibext="$acl_cv_shlibext"
+  hardcode_libdir_flag_spec="$acl_cv_hardcode_libdir_flag_spec"
+  hardcode_libdir_separator="$acl_cv_hardcode_libdir_separator"
+  hardcode_direct="$acl_cv_hardcode_direct"
+  hardcode_minus_L="$acl_cv_hardcode_minus_L"
+  sys_lib_search_path_spec="$acl_cv_sys_lib_search_path_spec"
+  sys_lib_dlsearch_path_spec="$acl_cv_sys_lib_dlsearch_path_spec"
+  dnl Determine whether the user wants rpath handling at all.
+  AC_ARG_ENABLE(rpath,
+    [  --disable-rpath         do not hardcode runtime library paths],
+    :, enable_rpath=yes)
+])
+
+dnl AC_LIB_LINKFLAGS_BODY(name [, dependencies]) searches for libname and
+dnl the libraries corresponding to explicit and implicit dependencies.
+dnl Sets the LIB${NAME}, LTLIB${NAME} and INC${NAME} variables.
+AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
+[
+  define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+                               [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
+  dnl By default, look in $includedir and $libdir.
+  use_additional=yes
+  AC_LIB_WITH_FINAL_PREFIX([
+    eval additional_includedir=\"$includedir\"
+    eval additional_libdir=\"$libdir\"
+  ])
+  AC_ARG_WITH([lib$1-prefix],
+[  --with-lib$1-prefix[=DIR]  search for lib$1 in DIR/include and DIR/lib
+  --without-lib$1-prefix     don't search for lib$1 in includedir and libdir],
+[
+    if test "X$withval" = "Xno"; then
+      use_additional=no
+    else
+      if test "X$withval" = "X"; then
+        AC_LIB_WITH_FINAL_PREFIX([
+          eval additional_includedir=\"$includedir\"
+          eval additional_libdir=\"$libdir\"
+        ])
+      else
+        additional_includedir="$withval/include"
+        additional_libdir="$withval/lib"
+      fi
+    fi
+])
+  dnl Search the library and its dependencies in $additional_libdir and
+  dnl $LDFLAGS. Using breadth-first-seach.
+  LIB[]NAME=
+  LTLIB[]NAME=
+  INC[]NAME=
+  rpathdirs=
+  ltrpathdirs=
+  names_already_handled=
+  names_next_round='$1 $2'
+  while test -n "$names_next_round"; do
+    names_this_round="$names_next_round"
+    names_next_round=
+    for name in $names_this_round; do
+      already_handled=
+      for n in $names_already_handled; do
+        if test "$n" = "$name"; then
+          already_handled=yes
+          break
+        fi
+      done
+      if test -z "$already_handled"; then
+        names_already_handled="$names_already_handled $name"
+        dnl See if it was already located by an earlier AC_LIB_LINKFLAGS
+        dnl or AC_LIB_HAVE_LINKFLAGS call.
+        uppername=`echo "$name" | sed -e 'y|abcdefghijklmnopqrstuvwxyz./-|ABCDEFGHIJKLMNOPQRSTUVWXYZ___|'`
+        eval value=\"\$HAVE_LIB$uppername\"
+        if test -n "$value"; then
+          if test "$value" = yes; then
+            eval value=\"\$LIB$uppername\"
+            test -z "$value" || LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$value"
+            eval value=\"\$LTLIB$uppername\"
+            test -z "$value" || LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$value"
+          else
+            dnl An earlier call to AC_LIB_HAVE_LINKFLAGS has determined
+            dnl that this library doesn't exist. So just drop it.
+            :
+          fi
+        else
+          dnl Search the library lib$name in $additional_libdir and $LDFLAGS
+          dnl and the already constructed $LIBNAME/$LTLIBNAME.
+          found_dir=
+          found_la=
+          found_so=
+          found_a=
+          if test $use_additional = yes; then
+            if test -n "$shlibext" && test -f "$additional_libdir/lib$name.$shlibext"; then
+              found_dir="$additional_libdir"
+              found_so="$additional_libdir/lib$name.$shlibext"
+              if test -f "$additional_libdir/lib$name.la"; then
+                found_la="$additional_libdir/lib$name.la"
+              fi
+            else
+              if test -f "$additional_libdir/lib$name.$libext"; then
+                found_dir="$additional_libdir"
+                found_a="$additional_libdir/lib$name.$libext"
+                if test -f "$additional_libdir/lib$name.la"; then
+                  found_la="$additional_libdir/lib$name.la"
+                fi
+              fi
+            fi
+          fi
+          if test "X$found_dir" = "X"; then
+            for x in $LDFLAGS $LTLIB[]NAME; do
+              AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+              case "$x" in
+                -L*)
+                  dir=`echo "X$x" | sed -e 's/^X-L//'`
+                  if test -n "$shlibext" && test -f "$dir/lib$name.$shlibext"; then
+                    found_dir="$dir"
+                    found_so="$dir/lib$name.$shlibext"
+                    if test -f "$dir/lib$name.la"; then
+                      found_la="$dir/lib$name.la"
+                    fi
+                  else
+                    if test -f "$dir/lib$name.$libext"; then
+                      found_dir="$dir"
+                      found_a="$dir/lib$name.$libext"
+                      if test -f "$dir/lib$name.la"; then
+                        found_la="$dir/lib$name.la"
+                      fi
+                    fi
+                  fi
+                  ;;
+              esac
+              if test "X$found_dir" != "X"; then
+                break
+              fi
+            done
+          fi
+          if test "X$found_dir" != "X"; then
+            dnl Found the library.
+            LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$found_dir -l$name"
+            if test "X$found_so" != "X"; then
+              dnl Linking with a shared library. We attempt to hardcode its
+              dnl directory into the executable's runpath, unless it's the
+              dnl standard /usr/lib.
+              if test "$enable_rpath" = no || test "X$found_dir" = "X/usr/lib"; then
+                dnl No hardcoding is needed.
+                LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+              else
+                dnl Use an explicit option to hardcode DIR into the resulting
+                dnl binary.
+                dnl Potentially add DIR to ltrpathdirs.
+                dnl The ltrpathdirs will be appended to $LTLIBNAME at the end.
+                haveit=
+                for x in $ltrpathdirs; do
+                  if test "X$x" = "X$found_dir"; then
+                    haveit=yes
+                    break
+                  fi
+                done
+                if test -z "$haveit"; then
+                  ltrpathdirs="$ltrpathdirs $found_dir"
+                fi
+                dnl The hardcoding into $LIBNAME is system dependent.
+                if test "$hardcode_direct" = yes; then
+                  dnl Using DIR/libNAME.so during linking hardcodes DIR into the
+                  dnl resulting binary.
+                  LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+                else
+                  if test -n "$hardcode_libdir_flag_spec" && test "$hardcode_minus_L" = no; then
+                    dnl Use an explicit option to hardcode DIR into the resulting
+                    dnl binary.
+                    LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+                    dnl Potentially add DIR to rpathdirs.
+                    dnl The rpathdirs will be appended to $LIBNAME at the end.
+                    haveit=
+                    for x in $rpathdirs; do
+                      if test "X$x" = "X$found_dir"; then
+                        haveit=yes
+                        break
+                      fi
+                    done
+                    if test -z "$haveit"; then
+                      rpathdirs="$rpathdirs $found_dir"
+                    fi
+                  else
+                    dnl Rely on "-L$found_dir".
+                    dnl But don't add it if it's already contained in the LDFLAGS
+                    dnl or the already constructed $LIBNAME
+                    haveit=
+                    for x in $LDFLAGS $LIB[]NAME; do
+                      AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                      if test "X$x" = "X-L$found_dir"; then
+                        haveit=yes
+                        break
+                      fi
+                    done
+                    if test -z "$haveit"; then
+                      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir"
+                    fi
+                    if test "$hardcode_minus_L" != no; then
+                      dnl FIXME: Not sure whether we should use
+                      dnl "-L$found_dir -l$name" or "-L$found_dir $found_so"
+                      dnl here.
+                      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+                    else
+                      dnl We cannot use $hardcode_runpath_var and LD_RUN_PATH
+                      dnl here, because this doesn't fit in flags passed to the
+                      dnl compiler. So give up. No hardcoding. This affects only
+                      dnl very old systems.
+                      dnl FIXME: Not sure whether we should use
+                      dnl "-L$found_dir -l$name" or "-L$found_dir $found_so"
+                      dnl here.
+                      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name"
+                    fi
+                  fi
+                fi
+              fi
+            else
+              if test "X$found_a" != "X"; then
+                dnl Linking with a static library.
+                LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_a"
+              else
+                dnl We shouldn't come here, but anyway it's good to have a
+                dnl fallback.
+                LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir -l$name"
+              fi
+            fi
+            dnl Assume the include files are nearby.
+            additional_includedir=
+            case "$found_dir" in
+              */lib | */lib/)
+                basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e 's,/lib/*$,,'`
+                additional_includedir="$basedir/include"
+                ;;
+            esac
+            if test "X$additional_includedir" != "X"; then
+              dnl Potentially add $additional_includedir to $INCNAME.
+              dnl But don't add it
+              dnl   1. if it's the standard /usr/include,
+              dnl   2. if it's /usr/local/include and we are using GCC on Linux,
+              dnl   3. if it's already present in $CPPFLAGS or the already
+              dnl      constructed $INCNAME,
+              dnl   4. if it doesn't exist as a directory.
+              if test "X$additional_includedir" != "X/usr/include"; then
+                haveit=
+                if test "X$additional_includedir" = "X/usr/local/include"; then
+                  if test -n "$GCC"; then
+                    case $host_os in
+                      linux*) haveit=yes;;
+                    esac
+                  fi
+                fi
+                if test -z "$haveit"; then
+                  for x in $CPPFLAGS $INC[]NAME; do
+                    AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                    if test "X$x" = "X-I$additional_includedir"; then
+                      haveit=yes
+                      break
+                    fi
+                  done
+                  if test -z "$haveit"; then
+                    if test -d "$additional_includedir"; then
+                      dnl Really add $additional_includedir to $INCNAME.
+                      INC[]NAME="${INC[]NAME}${INC[]NAME:+ }-I$additional_includedir"
+                    fi
+                  fi
+                fi
+              fi
+            fi
+            dnl Look for dependencies.
+            if test -n "$found_la"; then
+              dnl Read the .la file. It defines the variables
+              dnl dlname, library_names, old_library, dependency_libs, current,
+              dnl age, revision, installed, dlopen, dlpreopen, libdir.
+              save_libdir="$libdir"
+              case "$found_la" in
+                */* | *\\*) . "$found_la" ;;
+                *) . "./$found_la" ;;
+              esac
+              libdir="$save_libdir"
+              dnl We use only dependency_libs.
+              for dep in $dependency_libs; do
+                case "$dep" in
+                  -L*)
+                    additional_libdir=`echo "X$dep" | sed -e 's/^X-L//'`
+                    dnl Potentially add $additional_libdir to $LIBNAME and $LTLIBNAME.
+                    dnl But don't add it
+                    dnl   1. if it's the standard /usr/lib,
+                    dnl   2. if it's /usr/local/lib and we are using GCC on Linux,
+                    dnl   3. if it's already present in $LDFLAGS or the already
+                    dnl      constructed $LIBNAME,
+                    dnl   4. if it doesn't exist as a directory.
+                    if test "X$additional_libdir" != "X/usr/lib"; then
+                      haveit=
+                      if test "X$additional_libdir" = "X/usr/local/lib"; then
+                        if test -n "$GCC"; then
+                          case $host_os in
+                            linux*) haveit=yes;;
+                          esac
+                        fi
+                      fi
+                      if test -z "$haveit"; then
+                        haveit=
+                        for x in $LDFLAGS $LIB[]NAME; do
+                          AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                          if test "X$x" = "X-L$additional_libdir"; then
+                            haveit=yes
+                            break
+                          fi
+                        done
+                        if test -z "$haveit"; then
+                          if test -d "$additional_libdir"; then
+                            dnl Really add $additional_libdir to $LIBNAME.
+                            LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$additional_libdir"
+                          fi
+                        fi
+                        haveit=
+                        for x in $LDFLAGS $LTLIB[]NAME; do
+                          AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+                          if test "X$x" = "X-L$additional_libdir"; then
+                            haveit=yes
+                            break
+                          fi
+                        done
+                        if test -z "$haveit"; then
+                          if test -d "$additional_libdir"; then
+                            dnl Really add $additional_libdir to $LTLIBNAME.
+                            LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$additional_libdir"
+                          fi
+                        fi
+                      fi
+                    fi
+                    ;;
+                  -R*)
+                    dir=`echo "X$dep" | sed -e 's/^X-R//'`
+                    if test "$enable_rpath" != no; then
+                      dnl Potentially add DIR to rpathdirs.
+                      dnl The rpathdirs will be appended to $LIBNAME at the end.
+                      haveit=
+                      for x in $rpathdirs; do
+                        if test "X$x" = "X$dir"; then
+                          haveit=yes
+                          break
+                        fi
+                      done
+                      if test -z "$haveit"; then
+                        rpathdirs="$rpathdirs $dir"
+                      fi
+                      dnl Potentially add DIR to ltrpathdirs.
+                      dnl The ltrpathdirs will be appended to $LTLIBNAME at the end.
+                      haveit=
+                      for x in $ltrpathdirs; do
+                        if test "X$x" = "X$dir"; then
+                          haveit=yes
+                          break
+                        fi
+                      done
+                      if test -z "$haveit"; then
+                        ltrpathdirs="$ltrpathdirs $dir"
+                      fi
+                    fi
+                    ;;
+                  -l*)
+                    dnl Handle this in the next round.
+                    names_next_round="$names_next_round "`echo "X$dep" | sed -e 's/^X-l//'`
+                    ;;
+                  *.la)
+                    dnl Handle this in the next round. Throw away the .la's
+                    dnl directory; it is already contained in a preceding -L
+                    dnl option.
+                    names_next_round="$names_next_round "`echo "X$dep" | sed -e 's,^X.*/,,' -e 's,^lib,,' -e 's,\.la$,,'`
+                    ;;
+                  *)
+                    dnl Most likely an immediate library name.
+                    LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$dep"
+                    LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$dep"
+                    ;;
+                esac
+              done
+            fi
+          else
+            dnl Didn't find the library; assume it is in the system directories
+            dnl known to the linker and runtime loader. (All the system
+            dnl directories known to the linker should also be known to the
+            dnl runtime loader, otherwise the system is severely misconfigured.)
+            LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name"
+            LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-l$name"
+          fi
+        fi
+      fi
+    done
+  done
+  if test "X$rpathdirs" != "X"; then
+    if test -n "$hardcode_libdir_separator"; then
+      dnl Weird platform: only the last -rpath option counts, the user must
+      dnl pass all path elements in one option. We can arrange that for a
+      dnl single library, but not when more than one $LIBNAMEs are used.
+      alldirs=
+      for found_dir in $rpathdirs; do
+        alldirs="${alldirs}${alldirs:+$hardcode_libdir_separator}$found_dir"
+      done
+      dnl Note: hardcode_libdir_flag_spec uses $libdir and $wl.
+      acl_save_libdir="$libdir"
+      libdir="$alldirs"
+      eval flag=\"$hardcode_libdir_flag_spec\"
+      libdir="$acl_save_libdir"
+      LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag"
+    else
+      dnl The -rpath options are cumulative.
+      for found_dir in $rpathdirs; do
+        acl_save_libdir="$libdir"
+        libdir="$found_dir"
+        eval flag=\"$hardcode_libdir_flag_spec\"
+        libdir="$acl_save_libdir"
+        LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag"
+      done
+    fi
+  fi
+  if test "X$ltrpathdirs" != "X"; then
+    dnl When using libtool, the option that works for both libraries and
+    dnl executables is -R. The -R options are cumulative.
+    for found_dir in $ltrpathdirs; do
+      LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-R$found_dir"
+    done
+  fi
+])
+
+dnl AC_LIB_APPENDTOVAR(VAR, CONTENTS) appends the elements of CONTENTS to VAR,
+dnl unless already present in VAR.
+dnl Works only for CPPFLAGS, not for LIB* variables because that sometimes
+dnl contains two or three consecutive elements that belong together.
+AC_DEFUN([AC_LIB_APPENDTOVAR],
+[
+  for element in [$2]; do
+    haveit=
+    for x in $[$1]; do
+      AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+      if test "X$x" = "X$element"; then
+        haveit=yes
+        break
+      fi
+    done
+    if test -z "$haveit"; then
+      [$1]="${[$1]}${[$1]:+ }$element"
+    fi
+  done
+])
diff --git a/common/m4/lib-prefix.m4 b/common/m4/lib-prefix.m4
new file mode 100755 (executable)
index 0000000..b8b79ab
--- /dev/null
@@ -0,0 +1,148 @@
+# lib-prefix.m4 serial 1 (gettext-0.11)
+dnl Copyright (C) 2001-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+dnl AC_LIB_PREFIX adds to the CPPFLAGS and LDFLAGS the flags that are needed
+dnl to access previously installed libraries. The basic assumption is that
+dnl a user will want packages to use other packages he previously installed
+dnl with the same --prefix option.
+dnl This macro is not needed if only AC_LIB_LINKFLAGS is used to locate
+dnl libraries, but is otherwise very convenient.
+AC_DEFUN([AC_LIB_PREFIX],
+[
+  AC_BEFORE([$0], [AC_LIB_LINKFLAGS])
+  AC_REQUIRE([AC_PROG_CC])
+  AC_REQUIRE([AC_CANONICAL_HOST])
+  AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+  dnl By default, look in $includedir and $libdir.
+  use_additional=yes
+  AC_LIB_WITH_FINAL_PREFIX([
+    eval additional_includedir=\"$includedir\"
+    eval additional_libdir=\"$libdir\"
+  ])
+  AC_ARG_WITH([lib-prefix],
+[  --with-lib-prefix[=DIR] search for libraries in DIR/include and DIR/lib
+  --without-lib-prefix    don't search for libraries in includedir and libdir],
+[
+    if test "X$withval" = "Xno"; then
+      use_additional=no
+    else
+      if test "X$withval" = "X"; then
+        AC_LIB_WITH_FINAL_PREFIX([
+          eval additional_includedir=\"$includedir\"
+          eval additional_libdir=\"$libdir\"
+        ])
+      else
+        additional_includedir="$withval/include"
+        additional_libdir="$withval/lib"
+      fi
+    fi
+])
+  if test $use_additional = yes; then
+    dnl Potentially add $additional_includedir to $CPPFLAGS.
+    dnl But don't add it
+    dnl   1. if it's the standard /usr/include,
+    dnl   2. if it's already present in $CPPFLAGS,
+    dnl   3. if it's /usr/local/include and we are using GCC on Linux,
+    dnl   4. if it doesn't exist as a directory.
+    if test "X$additional_includedir" != "X/usr/include"; then
+      haveit=
+      for x in $CPPFLAGS; do
+        AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+        if test "X$x" = "X-I$additional_includedir"; then
+          haveit=yes
+          break
+        fi
+      done
+      if test -z "$haveit"; then
+        if test "X$additional_includedir" = "X/usr/local/include"; then
+          if test -n "$GCC"; then
+            case $host_os in
+              linux*) haveit=yes;;
+            esac
+          fi
+        fi
+        if test -z "$haveit"; then
+          if test -d "$additional_includedir"; then
+            dnl Really add $additional_includedir to $CPPFLAGS.
+            CPPFLAGS="${CPPFLAGS}${CPPFLAGS:+ }-I$additional_includedir"
+          fi
+        fi
+      fi
+    fi
+    dnl Potentially add $additional_libdir to $LDFLAGS.
+    dnl But don't add it
+    dnl   1. if it's the standard /usr/lib,
+    dnl   2. if it's already present in $LDFLAGS,
+    dnl   3. if it's /usr/local/lib and we are using GCC on Linux,
+    dnl   4. if it doesn't exist as a directory.
+    if test "X$additional_libdir" != "X/usr/lib"; then
+      haveit=
+      for x in $LDFLAGS; do
+        AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+        if test "X$x" = "X-L$additional_libdir"; then
+          haveit=yes
+          break
+        fi
+      done
+      if test -z "$haveit"; then
+        if test "X$additional_libdir" = "X/usr/local/lib"; then
+          if test -n "$GCC"; then
+            case $host_os in
+              linux*) haveit=yes;;
+            esac
+          fi
+        fi
+        if test -z "$haveit"; then
+          if test -d "$additional_libdir"; then
+            dnl Really add $additional_libdir to $LDFLAGS.
+            LDFLAGS="${LDFLAGS}${LDFLAGS:+ }-L$additional_libdir"
+          fi
+        fi
+      fi
+    fi
+  fi
+])
+
+dnl AC_LIB_PREPARE_PREFIX creates variables acl_final_prefix,
+dnl acl_final_exec_prefix, containing the values to which $prefix and
+dnl $exec_prefix will expand at the end of the configure script.
+AC_DEFUN([AC_LIB_PREPARE_PREFIX],
+[
+  dnl Unfortunately, prefix and exec_prefix get only finally determined
+  dnl at the end of configure.
+  if test "X$prefix" = "XNONE"; then
+    acl_final_prefix="$ac_default_prefix"
+  else
+    acl_final_prefix="$prefix"
+  fi
+  if test "X$exec_prefix" = "XNONE"; then
+    acl_final_exec_prefix='${prefix}'
+  else
+    acl_final_exec_prefix="$exec_prefix"
+  fi
+  acl_save_prefix="$prefix"
+  prefix="$acl_final_prefix"
+  eval acl_final_exec_prefix=\"$acl_final_exec_prefix\"
+  prefix="$acl_save_prefix"
+])
+
+dnl AC_LIB_WITH_FINAL_PREFIX([statement]) evaluates statement, with the
+dnl variables prefix and exec_prefix bound to the values they will have
+dnl at the end of the configure script.
+AC_DEFUN([AC_LIB_WITH_FINAL_PREFIX],
+[
+  acl_save_prefix="$prefix"
+  prefix="$acl_final_prefix"
+  acl_save_exec_prefix="$exec_prefix"
+  exec_prefix="$acl_final_exec_prefix"
+  $1
+  exec_prefix="$acl_save_exec_prefix"
+  prefix="$acl_save_prefix"
+])
diff --git a/common/m4/libtool.m4 b/common/m4/libtool.m4
new file mode 100644 (file)
index 0000000..a3fee53
--- /dev/null
@@ -0,0 +1,7377 @@
+# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008 Free Software Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+# 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.
+
+m4_define([_LT_COPYING], [dnl
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008 Free Software Foundation, Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool 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 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool 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 GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+])
+
+# serial 56 LT_INIT
+
+
+# LT_PREREQ(VERSION)
+# ------------------
+# Complain and exit if this libtool version is less that VERSION.
+m4_defun([LT_PREREQ],
+[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1,
+       [m4_default([$3],
+                  [m4_fatal([Libtool version $1 or higher is required],
+                            63)])],
+       [$2])])
+
+
+# _LT_CHECK_BUILDDIR
+# ------------------
+# Complain if the absolute build directory name contains unusual characters
+m4_defun([_LT_CHECK_BUILDDIR],
+[case `pwd` in
+  *\ * | *\    *)
+    AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;;
+esac
+])
+
+
+# LT_INIT([OPTIONS])
+# ------------------
+AC_DEFUN([LT_INIT],
+[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT
+AC_BEFORE([$0], [LT_LANG])dnl
+AC_BEFORE([$0], [LT_OUTPUT])dnl
+AC_BEFORE([$0], [LTDL_INIT])dnl
+m4_require([_LT_CHECK_BUILDDIR])dnl
+
+dnl Autoconf doesn't catch unexpanded LT_ macros by default:
+m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl
+m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl
+dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4
+dnl unless we require an AC_DEFUNed macro:
+AC_REQUIRE([LTOPTIONS_VERSION])dnl
+AC_REQUIRE([LTSUGAR_VERSION])dnl
+AC_REQUIRE([LTVERSION_VERSION])dnl
+AC_REQUIRE([LTOBSOLETE_VERSION])dnl
+m4_require([_LT_PROG_LTMAIN])dnl
+
+dnl Parse OPTIONS
+_LT_SET_OPTIONS([$0], [$1])
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS="$ltmain"
+
+# Always use our own libtool.
+LIBTOOL='$(SHELL) $(top_builddir)/libtool'
+AC_SUBST(LIBTOOL)dnl
+
+_LT_SETUP
+
+# Only expand once:
+m4_define([LT_INIT])
+])# LT_INIT
+
+# Old names:
+AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT])
+AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PROG_LIBTOOL], [])
+dnl AC_DEFUN([AM_PROG_LIBTOOL], [])
+
+
+# _LT_CC_BASENAME(CC)
+# -------------------
+# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
+m4_defun([_LT_CC_BASENAME],
+[for cc_temp in $1""; do
+  case $cc_temp in
+    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
+    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
+    \-*) ;;
+    *) break;;
+  esac
+done
+cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"`
+])
+
+
+# _LT_FILEUTILS_DEFAULTS
+# ----------------------
+# It is okay to use these file commands and assume they have been set
+# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'.
+m4_defun([_LT_FILEUTILS_DEFAULTS],
+[: ${CP="cp -f"}
+: ${MV="mv -f"}
+: ${RM="rm -f"}
+])# _LT_FILEUTILS_DEFAULTS
+
+
+# _LT_SETUP
+# ---------
+m4_defun([_LT_SETUP],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+_LT_DECL([], [host_alias], [0], [The host system])dnl
+_LT_DECL([], [host], [0])dnl
+_LT_DECL([], [host_os], [0])dnl
+dnl
+_LT_DECL([], [build_alias], [0], [The build system])dnl
+_LT_DECL([], [build], [0])dnl
+_LT_DECL([], [build_os], [0])dnl
+dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+dnl
+AC_REQUIRE([AC_PROG_LN_S])dnl
+test -z "$LN_S" && LN_S="ln -s"
+_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl
+dnl
+AC_REQUIRE([LT_CMD_MAX_LEN])dnl
+_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl
+_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl
+dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_CHECK_SHELL_FEATURES])dnl
+m4_require([_LT_CMD_RELOAD])dnl
+m4_require([_LT_CHECK_MAGIC_METHOD])dnl
+m4_require([_LT_CMD_OLD_ARCHIVE])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+
+_LT_CONFIG_LIBTOOL_INIT([
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+])
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+_LT_CHECK_OBJDIR
+
+m4_require([_LT_TAG_COMPILER])dnl
+_LT_PROG_ECHO_BACKSLASH
+
+case $host_os in
+aix3*)
+  # AIX sometimes has problems with the GCC collect2 program.  For some
+  # reason, if we set the COLLECT_NAMES environment variable, the problems
+  # vanish in a puff of smoke.
+  if test "X${COLLECT_NAMES+set}" != Xset; then
+    COLLECT_NAMES=
+    export COLLECT_NAMES
+  fi
+  ;;
+esac
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst='s/\([["`$\\]]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst='s/\([["`\\]]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst='s/\*/\\\*/g'
+
+# Global variables:
+ofile=libtool
+can_build_shared=yes
+
+# All known linkers require a `.a' archive for static linking (except MSVC,
+# which needs '.lib').
+libext=a
+
+with_gnu_ld="$lt_cv_prog_gnu_ld"
+
+old_CC="$CC"
+old_CFLAGS="$CFLAGS"
+
+# Set sane defaults for various variables
+test -z "$CC" && CC=cc
+test -z "$LTCC" && LTCC=$CC
+test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS
+test -z "$LD" && LD=ld
+test -z "$ac_objext" && ac_objext=o
+
+_LT_CC_BASENAME([$compiler])
+
+# Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=file
+case $deplibs_check_method in
+file_magic*)
+  if test "$file_magic_cmd" = '$MAGIC_CMD'; then
+    _LT_PATH_MAGIC
+  fi
+  ;;
+esac
+
+# Use C for the default configuration in the libtool script
+LT_SUPPORTED_TAG([CC])
+_LT_LANG_C_CONFIG
+_LT_LANG_DEFAULT_CONFIG
+_LT_CONFIG_COMMANDS
+])# _LT_SETUP
+
+
+# _LT_PROG_LTMAIN
+# ---------------
+# Note that this code is called both from `configure', and `config.status'
+# now that we use AC_CONFIG_COMMANDS to generate libtool.  Notably,
+# `config.status' has no value for ac_aux_dir unless we are using Automake,
+# so we pass a copy along to make sure it has a sensible value anyway.
+m4_defun([_LT_PROG_LTMAIN],
+[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl
+_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir'])
+ltmain="$ac_aux_dir/ltmain.sh"
+])# _LT_PROG_LTMAIN
+
+
+## ------------------------------------- ##
+## Accumulate code for creating libtool. ##
+## ------------------------------------- ##
+
+# So that we can recreate a full libtool script including additional
+# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS
+# in macros and then make a single call at the end using the `libtool'
+# label.
+
+
+# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS])
+# ----------------------------------------
+# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL_INIT],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_INIT],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_INIT])
+
+
+# _LT_CONFIG_LIBTOOL([COMMANDS])
+# ------------------------------
+# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later.
+m4_define([_LT_CONFIG_LIBTOOL],
+[m4_ifval([$1],
+          [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS],
+                     [$1
+])])])
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS])
+
+
+# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS])
+# -----------------------------------------------------
+m4_defun([_LT_CONFIG_SAVE_COMMANDS],
+[_LT_CONFIG_LIBTOOL([$1])
+_LT_CONFIG_LIBTOOL_INIT([$2])
+])
+
+
+# _LT_FORMAT_COMMENT([COMMENT])
+# -----------------------------
+# Add leading comment marks to the start of each line, and a trailing
+# full-stop to the whole comment if one is not present already.
+m4_define([_LT_FORMAT_COMMENT],
+[m4_ifval([$1], [
+m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])],
+              [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.])
+)])
+
+
+
+## ------------------------ ##
+## FIXME: Eliminate VARNAME ##
+## ------------------------ ##
+
+
+# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?])
+# -------------------------------------------------------------------
+# CONFIGNAME is the name given to the value in the libtool script.
+# VARNAME is the (base) name used in the configure script.
+# VALUE may be 0, 1 or 2 for a computed quote escaped value based on
+# VARNAME.  Any other value will be used directly.
+m4_define([_LT_DECL],
+[lt_if_append_uniq([lt_decl_varnames], [$2], [, ],
+    [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name],
+       [m4_ifval([$1], [$1], [$2])])
+    lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3])
+    m4_ifval([$4],
+       [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])])
+    lt_dict_add_subkey([lt_decl_dict], [$2],
+       [tagged?], [m4_ifval([$5], [yes], [no])])])
+])
+
+
+# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION])
+# --------------------------------------------------------
+m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])])
+
+
+# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_tag_varnames],
+[_lt_decl_filter([tagged?], [yes], $@)])
+
+
+# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..])
+# ---------------------------------------------------------
+m4_define([_lt_decl_filter],
+[m4_case([$#],
+  [0], [m4_fatal([$0: too few arguments: $#])],
+  [1], [m4_fatal([$0: too few arguments: $#: $1])],
+  [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)],
+  [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)],
+  [lt_dict_filter([lt_decl_dict], $@)])[]dnl
+])
+
+
+# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...])
+# --------------------------------------------------
+m4_define([lt_decl_quote_varnames],
+[_lt_decl_filter([value], [1], $@)])
+
+
+# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_dquote_varnames],
+[_lt_decl_filter([value], [2], $@)])
+
+
+# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...])
+# ---------------------------------------------------
+m4_define([lt_decl_varnames_tagged],
+[m4_assert([$# <= 2])dnl
+_$0(m4_quote(m4_default([$1], [[, ]])),
+    m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]),
+    m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))])
+m4_define([_lt_decl_varnames_tagged],
+[m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])])
+
+
+# lt_decl_all_varnames([SEPARATOR], [VARNAME1...])
+# ------------------------------------------------
+m4_define([lt_decl_all_varnames],
+[_$0(m4_quote(m4_default([$1], [[, ]])),
+     m4_if([$2], [],
+          m4_quote(lt_decl_varnames),
+       m4_quote(m4_shift($@))))[]dnl
+])
+m4_define([_lt_decl_all_varnames],
+[lt_join($@, lt_decl_varnames_tagged([$1],
+                       lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl
+])
+
+
+# _LT_CONFIG_STATUS_DECLARE([VARNAME])
+# ------------------------------------
+# Quote a variable value, and forward it to `config.status' so that its
+# declaration there will have the same value as in `configure'.  VARNAME
+# must have a single quote delimited value for this to work.
+m4_define([_LT_CONFIG_STATUS_DECLARE],
+[$1='`$ECHO "X$][$1" | $Xsed -e "$delay_single_quote_subst"`'])
+
+
+# _LT_CONFIG_STATUS_DECLARATIONS
+# ------------------------------
+# We delimit libtool config variables with single quotes, so when
+# we write them to config.status, we have to be sure to quote all
+# embedded single quotes properly.  In configure, this macro expands
+# each variable declared with _LT_DECL (and _LT_TAGDECL) into:
+#
+#    <var>='`$ECHO "X$<var>" | $Xsed -e "$delay_single_quote_subst"`'
+m4_defun([_LT_CONFIG_STATUS_DECLARATIONS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames),
+    [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAGS
+# ----------------
+# Output comment and list of tags supported by the script
+m4_defun([_LT_LIBTOOL_TAGS],
+[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl
+available_tags="_LT_TAGS"dnl
+])
+
+
+# _LT_LIBTOOL_DECLARE(VARNAME, [TAG])
+# -----------------------------------
+# Extract the dictionary values for VARNAME (optionally with TAG) and
+# expand to a commented shell variable setting:
+#
+#    # Some comment about what VAR is for.
+#    visible_name=$lt_internal_name
+m4_define([_LT_LIBTOOL_DECLARE],
+[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1],
+                                          [description])))[]dnl
+m4_pushdef([_libtool_name],
+    m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl
+m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])),
+    [0], [_libtool_name=[$]$1],
+    [1], [_libtool_name=$lt_[]$1],
+    [2], [_libtool_name=$lt_[]$1],
+    [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl
+m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl
+])
+
+
+# _LT_LIBTOOL_CONFIG_VARS
+# -----------------------
+# Produce commented declarations of non-tagged libtool config variables
+# suitable for insertion in the LIBTOOL CONFIG section of the `libtool'
+# script.  Tagged libtool config variables (even for the LIBTOOL CONFIG
+# section) are produced by _LT_LIBTOOL_TAG_VARS.
+m4_defun([_LT_LIBTOOL_CONFIG_VARS],
+[m4_foreach([_lt_var],
+    m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])])
+
+
+# _LT_LIBTOOL_TAG_VARS(TAG)
+# -------------------------
+m4_define([_LT_LIBTOOL_TAG_VARS],
+[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames),
+    [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])])
+
+
+# _LT_TAGVAR(VARNAME, [TAGNAME])
+# ------------------------------
+m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])])
+
+
+# _LT_CONFIG_COMMANDS
+# -------------------
+# Send accumulated output to $CONFIG_STATUS.  Thanks to the lists of
+# variables for single and double quote escaping we saved from calls
+# to _LT_DECL, we can put quote escaped variables declarations
+# into `config.status', and then the shell code to quote escape them in
+# for loops in `config.status'.  Finally, any additional code accumulated
+# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded.
+m4_defun([_LT_CONFIG_COMMANDS],
+[AC_PROVIDE_IFELSE([LT_OUTPUT],
+       dnl If the libtool generation code has been placed in $CONFIG_LT,
+       dnl instead of duplicating it all over again into config.status,
+       dnl then we will have config.status run $CONFIG_LT later, so it
+       dnl needs to know what name is stored there:
+        [AC_CONFIG_COMMANDS([libtool],
+            [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])],
+    dnl If the libtool generation code is destined for config.status,
+    dnl expand the accumulated commands and init code now:
+    [AC_CONFIG_COMMANDS([libtool],
+        [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])])
+])#_LT_CONFIG_COMMANDS
+
+
+# Initialize.
+m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT],
+[
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+sed_quote_subst='$sed_quote_subst'
+double_quote_subst='$double_quote_subst'
+delay_variable_subst='$delay_variable_subst'
+_LT_CONFIG_STATUS_DECLARATIONS
+LTCC='$LTCC'
+LTCFLAGS='$LTCFLAGS'
+compiler='$compiler_DEFAULT'
+
+# Quote evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_quote_varnames); do
+    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Double-quote double-evaled strings.
+for var in lt_decl_all_varnames([[ \
+]], lt_decl_dquote_varnames); do
+    case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in
+    *[[\\\\\\\`\\"\\\$]]*)
+      eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Fix-up fallback echo if it was mangled by the above quoting rules.
+case \$lt_ECHO in
+*'\\\[$]0 --fallback-echo"')dnl "
+  lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\[$]0 --fallback-echo"\[$]/\[$]0 --fallback-echo"/'\`
+  ;;
+esac
+
+_LT_OUTPUT_LIBTOOL_INIT
+])
+
+
+# LT_OUTPUT
+# ---------
+# This macro allows early generation of the libtool script (before
+# AC_OUTPUT is called), incase it is used in configure for compilation
+# tests.
+AC_DEFUN([LT_OUTPUT],
+[: ${CONFIG_LT=./config.lt}
+AC_MSG_NOTICE([creating $CONFIG_LT])
+cat >"$CONFIG_LT" <<_LTEOF
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate a libtool stub with the current configuration.
+
+lt_cl_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AS_SHELL_SANITIZE
+_AS_PREPARE
+
+exec AS_MESSAGE_FD>&1
+exec AS_MESSAGE_LOG_FD>>config.log
+{
+  echo
+  AS_BOX([Running $as_me.])
+} >&AS_MESSAGE_LOG_FD
+
+lt_cl_help="\
+\`$as_me' creates a local libtool stub from the current configuration,
+for use in further configure time tests before the real libtool is
+generated.
+
+Usage: $[0] [[OPTIONS]]
+
+  -h, --help      print this help, then exit
+  -V, --version   print version number, then exit
+  -q, --quiet     do not print progress messages
+  -d, --debug     don't remove temporary files
+
+Report bugs to <bug-libtool@gnu.org>."
+
+lt_cl_version="\
+m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl
+m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION])
+configured by $[0], generated by m4_PACKAGE_STRING.
+
+Copyright (C) 2008 Free Software Foundation, Inc.
+This config.lt script is free software; the Free Software Foundation
+gives unlimited permision to copy, distribute and modify it."
+
+while test $[#] != 0
+do
+  case $[1] in
+    --version | --v* | -V )
+      echo "$lt_cl_version"; exit 0 ;;
+    --help | --h* | -h )
+      echo "$lt_cl_help"; exit 0 ;;
+    --debug | --d* | -d )
+      debug=: ;;
+    --quiet | --q* | --silent | --s* | -q )
+      lt_cl_silent=: ;;
+
+    -*) AC_MSG_ERROR([unrecognized option: $[1]
+Try \`$[0] --help' for more information.]) ;;
+
+    *) AC_MSG_ERROR([unrecognized argument: $[1]
+Try \`$[0] --help' for more information.]) ;;
+  esac
+  shift
+done
+
+if $lt_cl_silent; then
+  exec AS_MESSAGE_FD>/dev/null
+fi
+_LTEOF
+
+cat >>"$CONFIG_LT" <<_LTEOF
+_LT_OUTPUT_LIBTOOL_COMMANDS_INIT
+_LTEOF
+
+cat >>"$CONFIG_LT" <<\_LTEOF
+AC_MSG_NOTICE([creating $ofile])
+_LT_OUTPUT_LIBTOOL_COMMANDS
+AS_EXIT(0)
+_LTEOF
+chmod +x "$CONFIG_LT"
+
+# configure is writing to config.log, but config.lt does its own redirection,
+# appending to config.log, which fails on DOS, as config.log is still kept
+# open by configure.  Here we exec the FD to /dev/null, effectively closing
+# config.log, so it can be properly (re)opened and appended to by config.lt.
+if test "$no_create" != yes; then
+  lt_cl_success=:
+  test "$silent" = yes &&
+    lt_config_lt_args="$lt_config_lt_args --quiet"
+  exec AS_MESSAGE_LOG_FD>/dev/null
+  $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false
+  exec AS_MESSAGE_LOG_FD>>config.log
+  $lt_cl_success || AS_EXIT(1)
+fi
+])# LT_OUTPUT
+
+
+# _LT_CONFIG(TAG)
+# ---------------
+# If TAG is the built-in tag, create an initial libtool script with a
+# default configuration from the untagged config vars.  Otherwise add code
+# to config.status for appending the configuration named by TAG from the
+# matching tagged config vars.
+m4_defun([_LT_CONFIG],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_CONFIG_SAVE_COMMANDS([
+  m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl
+  m4_if(_LT_TAG, [C], [
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
+    fi
+
+    cfgfile="${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
+
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
+
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+_LT_COPYING
+_LT_LIBTOOL_TAGS
+
+# ### BEGIN LIBTOOL CONFIG
+_LT_LIBTOOL_CONFIG_VARS
+_LT_LIBTOOL_TAG_VARS
+# ### END LIBTOOL CONFIG
+
+_LT_EOF
+
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" != Xset; then
+  COLLECT_NAMES=
+  export COLLECT_NAMES
+fi
+_LT_EOF
+    ;;
+  esac
+
+  _LT_PROG_LTMAIN
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \
+    || (rm -f "$cfgfile"; exit 1)
+
+  _LT_PROG_XSI_SHELLFNS
+
+  sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \
+    || (rm -f "$cfgfile"; exit 1)
+
+  mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
+],
+[cat <<_LT_EOF >> "$ofile"
+
+dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded
+dnl in a comment (ie after a #).
+# ### BEGIN LIBTOOL TAG CONFIG: $1
+_LT_LIBTOOL_TAG_VARS(_LT_TAG)
+# ### END LIBTOOL TAG CONFIG: $1
+_LT_EOF
+])dnl /m4_if
+],
+[m4_if([$1], [], [
+    PACKAGE='$PACKAGE'
+    VERSION='$VERSION'
+    TIMESTAMP='$TIMESTAMP'
+    RM='$RM'
+    ofile='$ofile'], [])
+])dnl /_LT_CONFIG_SAVE_COMMANDS
+])# _LT_CONFIG
+
+
+# LT_SUPPORTED_TAG(TAG)
+# ---------------------
+# Trace this macro to discover what tags are supported by the libtool
+# --tag option, using:
+#    autoconf --trace 'LT_SUPPORTED_TAG:$1'
+AC_DEFUN([LT_SUPPORTED_TAG], [])
+
+
+# C support is built-in for now
+m4_define([_LT_LANG_C_enabled], [])
+m4_define([_LT_TAGS], [])
+
+
+# LT_LANG(LANG)
+# -------------
+# Enable libtool support for the given language if not already enabled.
+AC_DEFUN([LT_LANG],
+[AC_BEFORE([$0], [LT_OUTPUT])dnl
+m4_case([$1],
+  [C],                 [_LT_LANG(C)],
+  [C++],               [_LT_LANG(CXX)],
+  [Java],              [_LT_LANG(GCJ)],
+  [Fortran 77],                [_LT_LANG(F77)],
+  [Fortran],           [_LT_LANG(FC)],
+  [Windows Resource],  [_LT_LANG(RC)],
+  [m4_ifdef([_LT_LANG_]$1[_CONFIG],
+    [_LT_LANG($1)],
+    [m4_fatal([$0: unsupported language: "$1"])])])dnl
+])# LT_LANG
+
+
+# _LT_LANG(LANGNAME)
+# ------------------
+m4_defun([_LT_LANG],
+[m4_ifdef([_LT_LANG_]$1[_enabled], [],
+  [LT_SUPPORTED_TAG([$1])dnl
+  m4_append([_LT_TAGS], [$1 ])dnl
+  m4_define([_LT_LANG_]$1[_enabled], [])dnl
+  _LT_LANG_$1_CONFIG($1)])dnl
+])# _LT_LANG
+
+
+# _LT_LANG_DEFAULT_CONFIG
+# -----------------------
+m4_defun([_LT_LANG_DEFAULT_CONFIG],
+[AC_PROVIDE_IFELSE([AC_PROG_CXX],
+  [LT_LANG(CXX)],
+  [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_F77],
+  [LT_LANG(F77)],
+  [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])])
+
+AC_PROVIDE_IFELSE([AC_PROG_FC],
+  [LT_LANG(FC)],
+  [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])])
+
+dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal
+dnl pulling things in needlessly.
+AC_PROVIDE_IFELSE([AC_PROG_GCJ],
+  [LT_LANG(GCJ)],
+  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
+    [LT_LANG(GCJ)],
+    [AC_PROVIDE_IFELSE([LT_PROG_GCJ],
+      [LT_LANG(GCJ)],
+      [m4_ifdef([AC_PROG_GCJ],
+       [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([A][M_PROG_GCJ],
+       [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])])
+       m4_ifdef([LT_PROG_GCJ],
+       [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])])
+
+AC_PROVIDE_IFELSE([LT_PROG_RC],
+  [LT_LANG(RC)],
+  [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])])
+])# _LT_LANG_DEFAULT_CONFIG
+
+# Obsolete macros:
+AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)])
+AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)])
+AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)])
+AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_CXX], [])
+dnl AC_DEFUN([AC_LIBTOOL_F77], [])
+dnl AC_DEFUN([AC_LIBTOOL_FC], [])
+dnl AC_DEFUN([AC_LIBTOOL_GCJ], [])
+
+
+# _LT_TAG_COMPILER
+# ----------------
+m4_defun([_LT_TAG_COMPILER],
+[AC_REQUIRE([AC_PROG_CC])dnl
+
+_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl
+_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl
+_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl
+_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl
+
+# If no C compiler was specified, use CC.
+LTCC=${LTCC-"$CC"}
+
+# If no C compiler flags were specified, use CFLAGS.
+LTCFLAGS=${LTCFLAGS-"$CFLAGS"}
+
+# Allow CC to be a program name with arguments.
+compiler=$CC
+])# _LT_TAG_COMPILER
+
+
+# _LT_COMPILER_BOILERPLATE
+# ------------------------
+# Check for compiler boilerplate output or warnings with
+# the simple compiler test code.
+m4_defun([_LT_COMPILER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
+eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_compiler_boilerplate=`cat conftest.err`
+$RM conftest*
+])# _LT_COMPILER_BOILERPLATE
+
+
+# _LT_LINKER_BOILERPLATE
+# ----------------------
+# Check for linker boilerplate output or warnings with
+# the simple link test code.
+m4_defun([_LT_LINKER_BOILERPLATE],
+[m4_require([_LT_DECL_SED])dnl
+ac_outfile=conftest.$ac_objext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
+eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
+_lt_linker_boilerplate=`cat conftest.err`
+$RM -r conftest*
+])# _LT_LINKER_BOILERPLATE
+
+# _LT_REQUIRED_DARWIN_CHECKS
+# -------------------------
+m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[
+  case $host_os in
+    rhapsody* | darwin*)
+    AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:])
+    AC_CHECK_TOOL([NMEDIT], [nmedit], [:])
+    AC_CHECK_TOOL([LIPO], [lipo], [:])
+    AC_CHECK_TOOL([OTOOL], [otool], [:])
+    AC_CHECK_TOOL([OTOOL64], [otool64], [:])
+    _LT_DECL([], [DSYMUTIL], [1],
+      [Tool to manipulate archived DWARF debug symbol files on Mac OS X])
+    _LT_DECL([], [NMEDIT], [1],
+      [Tool to change global to local symbols on Mac OS X])
+    _LT_DECL([], [LIPO], [1],
+      [Tool to manipulate fat objects and archives on Mac OS X])
+    _LT_DECL([], [OTOOL], [1],
+      [ldd/readelf like tool for Mach-O binaries on Mac OS X])
+    _LT_DECL([], [OTOOL64], [1],
+      [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4])
+
+    AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod],
+      [lt_cv_apple_cc_single_mod=no
+      if test -z "${LT_MULTI_MODULE}"; then
+       # By default we will add the -single_module flag. You can override
+       # by either setting the environment variable LT_MULTI_MODULE
+       # non-empty at configure time, or by adding -multi_module to the
+       # link flags.
+       rm -rf libconftest.dylib*
+       echo "int foo(void){return 1;}" > conftest.c
+       echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD
+       $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+         -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=$?
+       if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then
+         lt_cv_apple_cc_single_mod=yes
+       else
+         cat conftest.err >&AS_MESSAGE_LOG_FD
+       fi
+       rm -rf libconftest.dylib*
+       rm -f conftest.*
+      fi])
+    AC_CACHE_CHECK([for -exported_symbols_list linker flag],
+      [lt_cv_ld_exported_symbols_list],
+      [lt_cv_ld_exported_symbols_list=no
+      save_LDFLAGS=$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+       [lt_cv_ld_exported_symbols_list=yes],
+       [lt_cv_ld_exported_symbols_list=no])
+       LDFLAGS="$save_LDFLAGS"
+    ])
+    case $host_os in
+    rhapsody* | darwin1.[[012]])
+      _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+       10.0,*86*-darwin8*|10.0,*-darwin[[91]]*)
+         _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+       10.[[012]]*)
+         _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;;
+       10.*)
+         _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
+    ;;
+  esac
+    if test "$lt_cv_apple_cc_single_mod" = "yes"; then
+      _lt_dar_single_mod='$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" = "yes"; then
+      _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym'
+    else
+      _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}'
+    fi
+    if test "$DSYMUTIL" != ":"; then
+      _lt_dsymutil='~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=
+    fi
+    ;;
+  esac
+])
+
+
+# _LT_DARWIN_LINKER_FEATURES
+# --------------------------
+# Checks for linker and compiler features on darwin
+m4_defun([_LT_DARWIN_LINKER_FEATURES],
+[
+  m4_require([_LT_REQUIRED_DARWIN_CHECKS])
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_automatic, $1)=yes
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=''
+  _LT_TAGVAR(link_all_deplibs, $1)=yes
+  _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=yes ;;
+     *) _lt_dar_can_shared=$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" = "yes"; then
+    output_verbose_link_cmd=echo
+    _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}"
+    _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}"
+    _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+    m4_if([$1], [CXX],
+[   if test "$lt_cv_apple_cc_single_mod" != "yes"; then
+      _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}"
+      _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}"
+    fi
+],[])
+  else
+  _LT_TAGVAR(ld_shlibs, $1)=no
+  fi
+])
+
+# _LT_SYS_MODULE_PATH_AIX
+# -----------------------
+# Links a minimal program and checks the executable
+# for the system default hardcoded library path. In most cases,
+# this is /usr/lib:/lib, but when the MPI compilers are used
+# the location of the communication and MPI libs are included too.
+# If we don't find anything, use the default library path according
+# to the aix ld manual.
+m4_defun([_LT_SYS_MODULE_PATH_AIX],
+[m4_require([_LT_DECL_SED])dnl
+AC_LINK_IFELSE(AC_LANG_PROGRAM,[
+lt_aix_libpath_sed='
+    /Import File Strings/,/^$/ {
+       /^0/ {
+           s/^0  *\(.*\)$/\1/
+           p
+       }
+    }'
+aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+# Check for a 64-bit object if we didn't find anything.
+if test -z "$aix_libpath"; then
+  aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"`
+fi],[])
+if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi
+])# _LT_SYS_MODULE_PATH_AIX
+
+
+# _LT_SHELL_INIT(ARG)
+# -------------------
+m4_define([_LT_SHELL_INIT],
+[ifdef([AC_DIVERSION_NOTICE],
+            [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
+        [AC_DIVERT_PUSH(NOTICE)])
+$1
+AC_DIVERT_POP
+])# _LT_SHELL_INIT
+
+
+# _LT_PROG_ECHO_BACKSLASH
+# -----------------------
+# Add some code to the start of the generated configure script which
+# will find an echo command which doesn't interpret backslashes.
+m4_defun([_LT_PROG_ECHO_BACKSLASH],
+[_LT_SHELL_INIT([
+# Check that we are running under the correct shell.
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+case X$lt_ECHO in
+X*--fallback-echo)
+  # Remove one level of quotation (which was required for Make).
+  ECHO=`echo "$lt_ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
+  ;;
+esac
+
+ECHO=${lt_ECHO-echo}
+if test "X[$]1" = X--no-reexec; then
+  # Discard the --no-reexec flag, and continue.
+  shift
+elif test "X[$]1" = X--fallback-echo; then
+  # Avoid inline document here, it may be left over
+  :
+elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then
+  # Yippee, $ECHO works!
+  :
+else
+  # Restart under the correct shell.
+  exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
+fi
+
+if test "X[$]1" = X--fallback-echo; then
+  # used as fallback echo
+  shift
+  cat <<_LT_EOF
+[$]*
+_LT_EOF
+  exit 0
+fi
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test -z "$lt_ECHO"; then
+  if test "X${echo_test_string+set}" != Xset; then
+    # find a string as large as possible, as long as the shell can cope with it
+    for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do
+      # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
+      if { echo_test_string=`eval $cmd`; } 2>/dev/null &&
+        { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null
+      then
+        break
+      fi
+    done
+  fi
+
+  if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
+     echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
+     test "X$echo_testing_string" = "X$echo_test_string"; then
+    :
+  else
+    # The Solaris, AIX, and Digital Unix default echo programs unquote
+    # backslashes.  This makes it impossible to quote backslashes using
+    #   echo "$something" | sed 's/\\/\\\\/g'
+    #
+    # So, first we look for a working echo in the user's PATH.
+
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for dir in $PATH /usr/ucb; do
+      IFS="$lt_save_ifs"
+      if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
+         test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' &&
+         echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` &&
+         test "X$echo_testing_string" = "X$echo_test_string"; then
+        ECHO="$dir/echo"
+        break
+      fi
+    done
+    IFS="$lt_save_ifs"
+
+    if test "X$ECHO" = Xecho; then
+      # We didn't find a better echo, so look for alternatives.
+      if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' &&
+         echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` &&
+         test "X$echo_testing_string" = "X$echo_test_string"; then
+        # This shell has a builtin print -r that does the trick.
+        ECHO='print -r'
+      elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } &&
+          test "X$CONFIG_SHELL" != X/bin/ksh; then
+        # If we have ksh, try running configure again with it.
+        ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh}
+        export ORIGINAL_CONFIG_SHELL
+        CONFIG_SHELL=/bin/ksh
+        export CONFIG_SHELL
+        exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
+      else
+        # Try using printf.
+        ECHO='printf %s\n'
+        if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' &&
+          echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` &&
+          test "X$echo_testing_string" = "X$echo_test_string"; then
+         # Cool, printf works
+         :
+        elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+            test "X$echo_testing_string" = 'X\t' &&
+            echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+            test "X$echo_testing_string" = "X$echo_test_string"; then
+         CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL
+         export CONFIG_SHELL
+         SHELL="$CONFIG_SHELL"
+         export SHELL
+         ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
+        elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` &&
+            test "X$echo_testing_string" = 'X\t' &&
+            echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` &&
+            test "X$echo_testing_string" = "X$echo_test_string"; then
+         ECHO="$CONFIG_SHELL [$]0 --fallback-echo"
+        else
+         # maybe with a smaller string...
+         prev=:
+
+         for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do
+           if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null
+           then
+             break
+           fi
+           prev="$cmd"
+         done
+
+         if test "$prev" != 'sed 50q "[$]0"'; then
+           echo_test_string=`eval $prev`
+           export echo_test_string
+           exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
+         else
+           # Oops.  We lost completely, so just stick with echo.
+           ECHO=echo
+         fi
+        fi
+      fi
+    fi
+  fi
+fi
+
+# Copy echo and quote the copy suitably for passing to libtool from
+# the Makefile, instead of quoting the original, which is used later.
+lt_ECHO=$ECHO
+if test "X$lt_ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then
+   lt_ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
+fi
+
+AC_SUBST(lt_ECHO)
+])
+_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts])
+_LT_DECL([], [ECHO], [1],
+    [An echo program that does not interpret backslashes])
+])# _LT_PROG_ECHO_BACKSLASH
+
+
+# _LT_ENABLE_LOCK
+# ---------------
+m4_defun([_LT_ENABLE_LOCK],
+[AC_ARG_ENABLE([libtool-lock],
+  [AS_HELP_STRING([--disable-libtool-lock],
+    [avoid locking (might break parallel builds)])])
+test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes
+
+# Some flags need to be propagated to the compiler or linker for good
+# libtool support.
+case $host in
+ia64-*-hpux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.$ac_objext` in
+      *ELF-32*)
+       HPUX_IA64_MODE="32"
+       ;;
+      *ELF-64*)
+       HPUX_IA64_MODE="64"
+       ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+*-*-irix6*)
+  # Find out which ABI we are using.
+  echo '[#]line __oline__ "configure"' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    if test "$lt_cv_prog_gnu_ld" = yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+       *32-bit*)
+         LD="${LD-ld} -melf32bsmip"
+         ;;
+       *N32*)
+         LD="${LD-ld} -melf32bmipn32"
+         ;;
+       *64-bit*)
+         LD="${LD-ld} -melf64bmip"
+       ;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+       *32-bit*)
+         LD="${LD-ld} -32"
+         ;;
+       *N32*)
+         LD="${LD-ld} -n32"
+         ;;
+       *64-bit*)
+         LD="${LD-ld} -64"
+         ;;
+      esac
+    fi
+  fi
+  rm -rf conftest*
+  ;;
+
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+      *32-bit*)
+       case $host in
+         x86_64-*kfreebsd*-gnu)
+           LD="${LD-ld} -m elf_i386_fbsd"
+           ;;
+         x86_64-*linux*)
+           LD="${LD-ld} -m elf_i386"
+           ;;
+         ppc64-*linux*|powerpc64-*linux*)
+           LD="${LD-ld} -m elf32ppclinux"
+           ;;
+         s390x-*linux*)
+           LD="${LD-ld} -m elf_s390"
+           ;;
+         sparc64-*linux*)
+           LD="${LD-ld} -m elf32_sparc"
+           ;;
+       esac
+       ;;
+      *64-bit*)
+       case $host in
+         x86_64-*kfreebsd*-gnu)
+           LD="${LD-ld} -m elf_x86_64_fbsd"
+           ;;
+         x86_64-*linux*)
+           LD="${LD-ld} -m elf_x86_64"
+           ;;
+         ppc*-*linux*|powerpc*-*linux*)
+           LD="${LD-ld} -m elf64ppc"
+           ;;
+         s390*-*linux*|s390*-*tpf*)
+           LD="${LD-ld} -m elf64_s390"
+           ;;
+         sparc*-*linux*)
+           LD="${LD-ld} -m elf64_sparc"
+           ;;
+       esac
+       ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+
+*-*-sco3.2v5*)
+  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
+  SAVE_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS -belf"
+  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
+    [AC_LANG_PUSH(C)
+     AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no])
+     AC_LANG_POP])
+  if test x"$lt_cv_cc_needs_belf" != x"yes"; then
+    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
+    CFLAGS="$SAVE_CFLAGS"
+  fi
+  ;;
+sparc*-*solaris*)
+  # Find out which ABI we are using.
+  echo 'int i;' > conftest.$ac_ext
+  if AC_TRY_EVAL(ac_compile); then
+    case `/usr/bin/file conftest.o` in
+    *64-bit*)
+      case $lt_cv_prog_gnu_ld in
+      yes*) LD="${LD-ld} -m elf64_sparc" ;;
+      *)
+       if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+         LD="${LD-ld} -64"
+       fi
+       ;;
+      esac
+      ;;
+    esac
+  fi
+  rm -rf conftest*
+  ;;
+esac
+
+need_locks="$enable_libtool_lock"
+])# _LT_ENABLE_LOCK
+
+
+# _LT_CMD_OLD_ARCHIVE
+# -------------------
+m4_defun([_LT_CMD_OLD_ARCHIVE],
+[AC_CHECK_TOOL(AR, ar, false)
+test -z "$AR" && AR=ar
+test -z "$AR_FLAGS" && AR_FLAGS=cru
+_LT_DECL([], [AR], [1], [The archiver])
+_LT_DECL([], [AR_FLAGS], [1])
+
+AC_CHECK_TOOL(STRIP, strip, :)
+test -z "$STRIP" && STRIP=:
+_LT_DECL([], [STRIP], [1], [A symbol stripping program])
+
+AC_CHECK_TOOL(RANLIB, ranlib, :)
+test -z "$RANLIB" && RANLIB=:
+_LT_DECL([], [RANLIB], [1],
+    [Commands used to install an old-style archive])
+
+# Determine commands to create old-style static archives.
+old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds='chmod 644 $oldlib'
+old_postuninstall_cmds=
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+    ;;
+  *)
+    old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib"
+    ;;
+  esac
+  old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib"
+fi
+_LT_DECL([], [old_postinstall_cmds], [2])
+_LT_DECL([], [old_postuninstall_cmds], [2])
+_LT_TAGDECL([], [old_archive_cmds], [2],
+    [Commands used to build an old-style archive])
+])# _LT_CMD_OLD_ARCHIVE
+
+
+# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#              [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------------------
+# Check whether the given compiler option works
+AC_DEFUN([_LT_COMPILER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4])
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+   lt_compiler_flag="$3"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   # The option is referenced via a variable to avoid confusing sed.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>conftest.err)
+   ac_status=$?
+   cat conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s "$ac_outfile"; then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings other than the usual output.
+     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
+       $2=yes
+     fi
+   fi
+   $RM conftest*
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$5], , :, [$5])
+else
+    m4_if([$6], , :, [$6])
+fi
+])# _LT_COMPILER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], [])
+
+
+# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
+#                  [ACTION-SUCCESS], [ACTION-FAILURE])
+# ----------------------------------------------------
+# Check whether the given linker option works
+AC_DEFUN([_LT_LINKER_OPTION],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_CACHE_CHECK([$1], [$2],
+  [$2=no
+   save_LDFLAGS="$LDFLAGS"
+   LDFLAGS="$LDFLAGS $3"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&AS_MESSAGE_LOG_FD
+       $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         $2=yes
+       fi
+     else
+       $2=yes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS="$save_LDFLAGS"
+])
+
+if test x"[$]$2" = xyes; then
+    m4_if([$4], , :, [$4])
+else
+    m4_if([$5], , :, [$5])
+fi
+])# _LT_LINKER_OPTION
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], [])
+
+
+# LT_CMD_MAX_LEN
+#---------------
+AC_DEFUN([LT_CMD_MAX_LEN],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+# find the maximum length of command line arguments
+AC_MSG_CHECKING([the maximum length of command line arguments])
+AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
+  i=0
+  teststring="ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=65536      # usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BSD)
+    lt_cv_sys_max_cmd_len=196608
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[        ]]//'`
+    else
+      lt_cv_sys_max_cmd_len=32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=$teststring$teststring
+      done
+      SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`$SHELL [$]0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \
+                = "XX$teststring$teststring"; } >/dev/null 2>&1 &&
+             test $i != 17 # 1/2 MB should be enough
+      do
+        i=`expr $i + 1`
+        teststring=$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1`
+      teststring=
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+])
+if test -n $lt_cv_sys_max_cmd_len ; then
+  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
+else
+  AC_MSG_RESULT(none)
+fi
+max_cmd_len=$lt_cv_sys_max_cmd_len
+_LT_DECL([], [max_cmd_len], [0],
+    [What is the maximum length of a command?])
+])# LT_CMD_MAX_LEN
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], [])
+
+
+# _LT_HEADER_DLFCN
+# ----------------
+m4_defun([_LT_HEADER_DLFCN],
+[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl
+])# _LT_HEADER_DLFCN
+
+
+# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
+#                      ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
+# ----------------------------------------------------------------
+m4_defun([_LT_TRY_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "$cross_compiling" = yes; then :
+  [$4]
+else
+  lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
+  lt_status=$lt_dlunknown
+  cat > conftest.$ac_ext <<_LT_EOF
+[#line __oline__ "configure"
+#include "confdefs.h"
+
+#if HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef RTLD_GLOBAL
+#  define LT_DLGLOBAL          RTLD_GLOBAL
+#else
+#  ifdef DL_GLOBAL
+#    define LT_DLGLOBAL                DL_GLOBAL
+#  else
+#    define LT_DLGLOBAL                0
+#  endif
+#endif
+
+/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
+   find out it does not work in some platform. */
+#ifndef LT_DLLAZY_OR_NOW
+#  ifdef RTLD_LAZY
+#    define LT_DLLAZY_OR_NOW           RTLD_LAZY
+#  else
+#    ifdef DL_LAZY
+#      define LT_DLLAZY_OR_NOW         DL_LAZY
+#    else
+#      ifdef RTLD_NOW
+#        define LT_DLLAZY_OR_NOW       RTLD_NOW
+#      else
+#        ifdef DL_NOW
+#          define LT_DLLAZY_OR_NOW     DL_NOW
+#        else
+#          define LT_DLLAZY_OR_NOW     0
+#        endif
+#      endif
+#    endif
+#  endif
+#endif
+
+void fnord() { int i=42;}
+int main ()
+{
+  void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
+  int status = $lt_dlunknown;
+
+  if (self)
+    {
+      if (dlsym (self,"fnord"))       status = $lt_dlno_uscore;
+      else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore;
+      /* dlclose (self); */
+    }
+  else
+    puts (dlerror ());
+
+  return status;
+}]
+_LT_EOF
+  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
+    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
+    lt_status=$?
+    case x$lt_status in
+      x$lt_dlno_uscore) $1 ;;
+      x$lt_dlneed_uscore) $2 ;;
+      x$lt_dlunknown|x*) $3 ;;
+    esac
+  else :
+    # compilation failed
+    $3
+  fi
+fi
+rm -fr conftest*
+])# _LT_TRY_DLOPEN_SELF
+
+
+# LT_SYS_DLOPEN_SELF
+# ------------------
+AC_DEFUN([LT_SYS_DLOPEN_SELF],
+[m4_require([_LT_HEADER_DLFCN])dnl
+if test "x$enable_dlopen" != xyes; then
+  enable_dlopen=unknown
+  enable_dlopen_self=unknown
+  enable_dlopen_self_static=unknown
+else
+  lt_cv_dlopen=no
+  lt_cv_dlopen_libs=
+
+  case $host_os in
+  beos*)
+    lt_cv_dlopen="load_add_on"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ;;
+
+  mingw* | pw32* | cegcc*)
+    lt_cv_dlopen="LoadLibrary"
+    lt_cv_dlopen_libs=
+    ;;
+
+  cygwin*)
+    lt_cv_dlopen="dlopen"
+    lt_cv_dlopen_libs=
+    ;;
+
+  darwin*)
+  # if libdl is installed we need to link against it
+    AC_CHECK_LIB([dl], [dlopen],
+               [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[
+    lt_cv_dlopen="dyld"
+    lt_cv_dlopen_libs=
+    lt_cv_dlopen_self=yes
+    ])
+    ;;
+
+  *)
+    AC_CHECK_FUNC([shl_load],
+         [lt_cv_dlopen="shl_load"],
+      [AC_CHECK_LIB([dld], [shl_load],
+           [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"],
+       [AC_CHECK_FUNC([dlopen],
+             [lt_cv_dlopen="dlopen"],
+         [AC_CHECK_LIB([dl], [dlopen],
+               [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],
+           [AC_CHECK_LIB([svld], [dlopen],
+                 [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"],
+             [AC_CHECK_LIB([dld], [dld_link],
+                   [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"])
+             ])
+           ])
+         ])
+       ])
+      ])
+    ;;
+  esac
+
+  if test "x$lt_cv_dlopen" != xno; then
+    enable_dlopen=yes
+  else
+    enable_dlopen=no
+  fi
+
+  case $lt_cv_dlopen in
+  dlopen)
+    save_CPPFLAGS="$CPPFLAGS"
+    test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H"
+
+    save_LDFLAGS="$LDFLAGS"
+    wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
+
+    save_LIBS="$LIBS"
+    LIBS="$lt_cv_dlopen_libs $LIBS"
+
+    AC_CACHE_CHECK([whether a program can dlopen itself],
+         lt_cv_dlopen_self, [dnl
+         _LT_TRY_DLOPEN_SELF(
+           lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes,
+           lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross)
+    ])
+
+    if test "x$lt_cv_dlopen_self" = xyes; then
+      wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
+      AC_CACHE_CHECK([whether a statically linked program can dlopen itself],
+         lt_cv_dlopen_self_static, [dnl
+         _LT_TRY_DLOPEN_SELF(
+           lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes,
+           lt_cv_dlopen_self_static=no,  lt_cv_dlopen_self_static=cross)
+      ])
+    fi
+
+    CPPFLAGS="$save_CPPFLAGS"
+    LDFLAGS="$save_LDFLAGS"
+    LIBS="$save_LIBS"
+    ;;
+  esac
+
+  case $lt_cv_dlopen_self in
+  yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;;
+  *) enable_dlopen_self=unknown ;;
+  esac
+
+  case $lt_cv_dlopen_self_static in
+  yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;;
+  *) enable_dlopen_self_static=unknown ;;
+  esac
+fi
+_LT_DECL([dlopen_support], [enable_dlopen], [0],
+        [Whether dlopen is supported])
+_LT_DECL([dlopen_self], [enable_dlopen_self], [0],
+        [Whether dlopen of programs is supported])
+_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0],
+        [Whether dlopen of statically linked programs is supported])
+])# LT_SYS_DLOPEN_SELF
+
+# Old name:
+AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], [])
+
+
+# _LT_COMPILER_C_O([TAGNAME])
+# ---------------------------
+# Check to see if options -c and -o are simultaneously supported by compiler.
+# This macro does not hard code the compiler like AC_PROG_CC_C_O.
+m4_defun([_LT_COMPILER_C_O],
+[m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
+  [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag="-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=$?
+   cat out/conftest.err >&AS_MESSAGE_LOG_FD
+   echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
+       _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+     fi
+   fi
+   chmod u+w . 2>&AS_MESSAGE_LOG_FD
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+])
+_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1],
+       [Does compiler simultaneously support -c and -o options?])
+])# _LT_COMPILER_C_O
+
+
+# _LT_COMPILER_FILE_LOCKS([TAGNAME])
+# ----------------------------------
+# Check to see if we can do hard links to lock some files if needed
+m4_defun([_LT_COMPILER_FILE_LOCKS],
+[m4_require([_LT_ENABLE_LOCK])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+_LT_COMPILER_C_O([$1])
+
+hard_links="nottested"
+if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then
+  # do not overwrite the value of need_locks provided by the user
+  AC_MSG_CHECKING([if we can lock with hard links])
+  hard_links=yes
+  $RM conftest*
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  touch conftest.a
+  ln conftest.a conftest.b 2>&5 || hard_links=no
+  ln conftest.a conftest.b 2>/dev/null && hard_links=no
+  AC_MSG_RESULT([$hard_links])
+  if test "$hard_links" = no; then
+    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe])
+    need_locks=warn
+  fi
+else
+  need_locks=no
+fi
+_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?])
+])# _LT_COMPILER_FILE_LOCKS
+
+
+# _LT_CHECK_OBJDIR
+# ----------------
+m4_defun([_LT_CHECK_OBJDIR],
+[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
+[rm -f .libs 2>/dev/null
+mkdir .libs 2>/dev/null
+if test -d .libs; then
+  lt_cv_objdir=.libs
+else
+  # MS-DOS does not allow filenames that begin with a dot.
+  lt_cv_objdir=_libs
+fi
+rmdir .libs 2>/dev/null])
+objdir=$lt_cv_objdir
+_LT_DECL([], [objdir], [0],
+         [The name of the directory that contains temporary libtool files])dnl
+m4_pattern_allow([LT_OBJDIR])dnl
+AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/",
+  [Define to the sub-directory in which libtool stores uninstalled libraries.])
+])# _LT_CHECK_OBJDIR
+
+
+# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME])
+# --------------------------------------
+# Check hardcoding attributes.
+m4_defun([_LT_LINKER_HARDCODE_LIBPATH],
+[AC_MSG_CHECKING([how to hardcode library paths into programs])
+_LT_TAGVAR(hardcode_action, $1)=
+if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" ||
+   test -n "$_LT_TAGVAR(runpath_var, $1)" ||
+   test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then
+
+  # We can hardcode non-existent directories.
+  if test "$_LT_TAGVAR(hardcode_direct, $1)" != no &&
+     # If the only mechanism to avoid hardcoding is shlibpath_var, we
+     # have to relink, otherwise we might link with an installed library
+     # when we should be linking with a yet-to-be-installed one
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no &&
+     test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then
+    # Linking always hardcodes the temporary library directory.
+    _LT_TAGVAR(hardcode_action, $1)=relink
+  else
+    # We can link without hardcoding, and we can hardcode nonexisting dirs.
+    _LT_TAGVAR(hardcode_action, $1)=immediate
+  fi
+else
+  # We cannot hardcode anything, or else we can only hardcode existing
+  # directories.
+  _LT_TAGVAR(hardcode_action, $1)=unsupported
+fi
+AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)])
+
+if test "$_LT_TAGVAR(hardcode_action, $1)" = relink ||
+   test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then
+  # Fast installation is not supported
+  enable_fast_install=no
+elif test "$shlibpath_overrides_runpath" = yes ||
+     test "$enable_shared" = no; then
+  # Fast installation is not necessary
+  enable_fast_install=needless
+fi
+_LT_TAGDECL([], [hardcode_action], [0],
+    [How to hardcode a shared library path into an executable])
+])# _LT_LINKER_HARDCODE_LIBPATH
+
+
+# _LT_CMD_STRIPLIB
+# ----------------
+m4_defun([_LT_CMD_STRIPLIB],
+[m4_require([_LT_DECL_EGREP])
+striplib=
+old_striplib=
+AC_MSG_CHECKING([whether stripping libraries is possible])
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib="$STRIP --strip-debug"
+  test -z "$striplib" && striplib="$STRIP --strip-unneeded"
+  AC_MSG_RESULT([yes])
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib="$STRIP -x"
+      old_striplib="$STRIP -S"
+      AC_MSG_RESULT([yes])
+    else
+      AC_MSG_RESULT([no])
+    fi
+    ;;
+  *)
+    AC_MSG_RESULT([no])
+    ;;
+  esac
+fi
+_LT_DECL([], [old_striplib], [1], [Commands to strip libraries])
+_LT_DECL([], [striplib], [1])
+])# _LT_CMD_STRIPLIB
+
+
+# _LT_SYS_DYNAMIC_LINKER([TAG])
+# -----------------------------
+# PORTME Fill in your ld.so characteristics
+m4_defun([_LT_SYS_DYNAMIC_LINKER],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_OBJDUMP])dnl
+m4_require([_LT_DECL_SED])dnl
+AC_MSG_CHECKING([dynamic linker characteristics])
+m4_if([$1],
+       [], [
+if test "$GCC" = yes; then
+  case $host_os in
+    darwin*) lt_awk_arg="/^libraries:/,/LR/" ;;
+    *) lt_awk_arg="/^libraries:/" ;;
+  esac
+  lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+  if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that should
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'`
+  else
+    lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+  fi
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=
+  lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+       lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk '
+BEGIN {RS=" "; FS="/|\n";} {
+  lt_foo="";
+  lt_count=0;
+  for (lt_i = NF; lt_i > 0; lt_i--) {
+    if ($lt_i != "" && $lt_i != ".") {
+      if ($lt_i == "..") {
+        lt_count++;
+      } else {
+        if (lt_count == 0) {
+          lt_foo="/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo != "") { lt_freq[[lt_foo]]++; }
+  if (lt_freq[[lt_foo]] == 1) { print lt_foo; }
+}'`
+  sys_lib_search_path_spec=`$ECHO $lt_search_path_spec`
+else
+  sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib"
+fi])
+library_names_spec=
+libname_spec='lib$name'
+soname_spec=
+shrext_cmds=".so"
+postinstall_cmds=
+postuninstall_cmds=
+finish_cmds=
+finish_eval=
+shlibpath_var=
+shlibpath_overrides_runpath=unknown
+version_type=none
+dynamic_linker="$host_os ld.so"
+sys_lib_dlsearch_path_spec="/lib /usr/lib"
+need_lib_prefix=unknown
+hardcode_into_libs=no
+
+# when you set need_version to no, make sure it does not cause -set_version
+# flags to be left without arguments
+need_version=unknown
+
+case $host_os in
+aix3*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a'
+  shlibpath_var=LIBPATH
+
+  # AIX 3 has no versioning support, so we append a major version to the name.
+  soname_spec='${libname}${release}${shared_ext}$major'
+  ;;
+
+aix[[4-9]]*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  hardcode_into_libs=yes
+  if test "$host_cpu" = ia64; then
+    # AIX 5 supports IA64
+    library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}'
+    shlibpath_var=LD_LIBRARY_PATH
+  else
+    # With GCC up to 2.95.x, collect2 would create an import file
+    # for dependence libraries.  The import file would start with
+    # the line `#! .'.  This would cause the generated library to
+    # depend on `.', always an invalid library.  This was fixed in
+    # development snapshots of GCC prior to 3.0.
+    case $host_os in
+      aix4 | aix4.[[01]] | aix4.[[01]].*)
+      if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)'
+          echo ' yes '
+          echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
+       :
+      else
+       can_build_shared=no
+      fi
+      ;;
+    esac
+    # AIX (on Power*) has no versioning support, so currently we can not hardcode correct
+    # soname into executable. Probably we can add versioning support to
+    # collect2, so additional links can be useful in future.
+    if test "$aix_use_runtimelinking" = yes; then
+      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
+      # instead of lib<name>.a to let people know that these are not
+      # typical AIX shared libraries.
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    else
+      # We preserve .a as extension for shared libraries through AIX4.2
+      # and later when we are not doing run time linking.
+      library_names_spec='${libname}${release}.a $libname.a'
+      soname_spec='${libname}${release}${shared_ext}$major'
+    fi
+    shlibpath_var=LIBPATH
+  fi
+  ;;
+
+amigaos*)
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compileline.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec='$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done'
+    ;;
+  esac
+  ;;
+
+beos*)
+  library_names_spec='${libname}${shared_ext}'
+  dynamic_linker="$host_os ld.so"
+  shlibpath_var=LIBRARY_PATH
+  ;;
+
+bsdi[[45]]*)
+  version_type=linux
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib"
+  sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib"
+  # the default ld.so.conf also contains /usr/contrib/lib and
+  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
+  # libtool to hard-code these into programs
+  ;;
+
+cygwin* | mingw* | pw32* | cegcc*)
+  version_type=windows
+  shrext_cmds=".dll"
+  need_version=no
+  need_lib_prefix=no
+
+  case $GCC,$host_os in
+  yes,cygwin* | yes,mingw* | yes,pw32* | yes,cegcc*)
+    library_names_spec='$libname.dll.a'
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds='base_file=`basename \${file}`~
+      dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~
+      dldir=$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname~
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
+    postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~
+      dlpath=$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=yes
+
+    case $host_os in
+    cygwin*)
+      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
+      soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib"
+      ;;
+    mingw* | cegcc*)
+      # MinGW DLLs use traditional 'lib' prefix
+      soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"`
+      if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then
+        # It is most probably a Windows format PATH printed by
+        # mingw gcc, but we are running on Cygwin. Gcc prints its search
+        # path with ; separators, and with drive letters. We can handle the
+        # drive letters (cygwin fileutils understands them), so leave them,
+        # especially as we might pass files found there to a mingw objdump,
+        # which wouldn't understand a cygwinified path. Ahh.
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED  -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      ;;
+    pw32*)
+      # pw32 DLLs use 'pw' prefix rather than 'lib'
+      library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
+      ;;
+    esac
+    ;;
+
+  *)
+    library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib'
+    ;;
+  esac
+  dynamic_linker='Win32 ld.exe'
+  # FIXME: first we should search . and the directory the executable is in
+  shlibpath_var=PATH
+  ;;
+
+darwin* | rhapsody*)
+  dynamic_linker="$host_os dyld"
+  version_type=darwin
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext'
+  soname_spec='${libname}${release}${major}$shared_ext'
+  shlibpath_overrides_runpath=yes
+  shlibpath_var=DYLD_LIBRARY_PATH
+  shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`'
+m4_if([$1], [],[
+  sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"])
+  sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib'
+  ;;
+
+dgux*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+freebsd1*)
+  dynamic_linker=no
+  ;;
+
+freebsd* | dragonfly*)
+  # DragonFly does not have aout.  When/if they implement a new
+  # versioning mechanism, adjust this.
+  if test -x /usr/bin/objformat; then
+    objformat=`/usr/bin/objformat`
+  else
+    case $host_os in
+    freebsd[[123]]*) objformat=aout ;;
+    *) objformat=elf ;;
+    esac
+  fi
+  version_type=freebsd-$objformat
+  case $version_type in
+    freebsd-elf*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+      need_version=no
+      need_lib_prefix=no
+      ;;
+    freebsd-*)
+      library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix'
+      need_version=yes
+      ;;
+  esac
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_os in
+  freebsd2*)
+    shlibpath_overrides_runpath=yes
+    ;;
+  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
+  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
+    shlibpath_overrides_runpath=no
+    hardcode_into_libs=yes
+    ;;
+  *) # from 4.6 on, and DragonFly
+    shlibpath_overrides_runpath=yes
+    hardcode_into_libs=yes
+    ;;
+  esac
+  ;;
+
+gnu*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  hardcode_into_libs=yes
+  ;;
+
+hpux9* | hpux10* | hpux11*)
+  # Give a soname corresponding to the major version so that dld.sl refuses to
+  # link against other versions.
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  case $host_cpu in
+  ia64*)
+    shrext_cmds='.so'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.so"
+    shlibpath_var=LD_LIBRARY_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    if test "X$HPUX_IA64_MODE" = X32; then
+      sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib"
+    else
+      sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64"
+    fi
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  hppa*64*)
+    shrext_cmds='.sl'
+    hardcode_into_libs=yes
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=yes # Unless +noenvvar is specified.
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec
+    ;;
+  *)
+    shrext_cmds='.sl'
+    dynamic_linker="$host_os dld.sl"
+    shlibpath_var=SHLIB_PATH
+    shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    ;;
+  esac
+  # HP-UX runs *really* slowly unless shared libraries are mode 555.
+  postinstall_cmds='chmod 555 $lib'
+  ;;
+
+interix[[3-9]]*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $host_os in
+    nonstopux*) version_type=nonstopux ;;
+    *)
+       if test "$lt_cv_prog_gnu_ld" = yes; then
+               version_type=linux
+       else
+               version_type=irix
+       fi ;;
+  esac
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}'
+  case $host_os in
+  irix5* | nonstopux*)
+    libsuff= shlibsuff=
+    ;;
+  *)
+    case $LD in # libtool.m4 will add one of these switches to LD
+    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
+      libsuff= shlibsuff= libmagic=32-bit;;
+    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
+      libsuff=32 shlibsuff=N32 libmagic=N32;;
+    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
+      libsuff=64 shlibsuff=64 libmagic=64-bit;;
+    *) libsuff= shlibsuff= libmagic=never-match;;
+    esac
+    ;;
+  esac
+  shlibpath_var=LD_LIBRARY${shlibsuff}_PATH
+  shlibpath_overrides_runpath=no
+  sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}"
+  sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}"
+  hardcode_into_libs=yes
+  ;;
+
+# No shared lib support for Linux oldld, aout, or coff.
+linux*oldld* | linux*aout* | linux*coff*)
+  dynamic_linker=no
+  ;;
+
+# This must be Linux ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  # Some binutils ld are patched to set DT_RUNPATH
+  save_LDFLAGS=$LDFLAGS
+  save_libdir=$libdir
+  eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \
+       LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\""
+  AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])],
+    [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null],
+       [shlibpath_overrides_runpath=yes])])
+  LDFLAGS=$save_LDFLAGS
+  libdir=$save_libdir
+
+  # This implies no fast_install, which is unacceptable.
+  # Some rework will be needed to allow for fast_install
+  # before this can be enabled.
+  hardcode_into_libs=yes
+
+  # Append ld.so.conf contents to the search path
+  if test -f /etc/ld.so.conf; then
+    lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[  ]*hwcap[        ]/d;s/[:,      ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '`
+    sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra"
+  fi
+
+  # We used to test for /lib/ld.so.1 and disable shared libraries on
+  # powerpc, because MkLinux only supported shared libraries with the
+  # GNU dynamic linker.  Since this was broken with cross compilers,
+  # most powerpc-linux boxes support dynamic linking these days and
+  # people can always --disable-shared, the test was removed, and we
+  # assume the GNU/Linux dynamic linker is in use.
+  dynamic_linker='GNU/Linux ld.so'
+  ;;
+
+netbsdelf*-gnu)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='NetBSD ld.elf_so'
+  ;;
+
+netbsd*)
+  version_type=sunos
+  need_lib_prefix=no
+  need_version=no
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+    finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+    dynamic_linker='NetBSD (a.out) ld.so'
+  else
+    library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}'
+    soname_spec='${libname}${release}${shared_ext}$major'
+    dynamic_linker='NetBSD ld.elf_so'
+  fi
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  ;;
+
+newsos6)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  ;;
+
+*nto* | *qnx*)
+  version_type=qnx
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  dynamic_linker='ldqnx.so'
+  ;;
+
+openbsd*)
+  version_type=sunos
+  sys_lib_dlsearch_path_spec="/usr/lib"
+  need_lib_prefix=no
+  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
+  case $host_os in
+    openbsd3.3 | openbsd3.3.*) need_version=yes ;;
+    *)                         need_version=no  ;;
+  esac
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    case $host_os in
+      openbsd2.[[89]] | openbsd2.[[89]].*)
+       shlibpath_overrides_runpath=no
+       ;;
+      *)
+       shlibpath_overrides_runpath=yes
+       ;;
+      esac
+  else
+    shlibpath_overrides_runpath=yes
+  fi
+  ;;
+
+os2*)
+  libname_spec='$name'
+  shrext_cmds=".dll"
+  need_lib_prefix=no
+  library_names_spec='$libname${shared_ext} $libname.a'
+  dynamic_linker='OS/2 ld.exe'
+  shlibpath_var=LIBPATH
+  ;;
+
+osf3* | osf4* | osf5*)
+  version_type=osf
+  need_lib_prefix=no
+  need_version=no
+  soname_spec='${libname}${release}${shared_ext}$major'
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib"
+  sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec"
+  ;;
+
+rdos*)
+  dynamic_linker=no
+  ;;
+
+solaris*)
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  # ldd complains unless libraries are executable
+  postinstall_cmds='chmod +x $lib'
+  ;;
+
+sunos4*)
+  version_type=sunos
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix'
+  finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  if test "$with_gnu_ld" = yes; then
+    need_lib_prefix=no
+  fi
+  need_version=yes
+  ;;
+
+sysv4 | sysv4.3*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  case $host_vendor in
+    sni)
+      shlibpath_overrides_runpath=no
+      need_lib_prefix=no
+      runpath_var=LD_RUN_PATH
+      ;;
+    siemens)
+      need_lib_prefix=no
+      ;;
+    motorola)
+      need_lib_prefix=no
+      need_version=no
+      shlibpath_overrides_runpath=no
+      sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib'
+      ;;
+  esac
+  ;;
+
+sysv4*MP*)
+  if test -d /usr/nec ;then
+    version_type=linux
+    library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}'
+    soname_spec='$libname${shared_ext}.$major'
+    shlibpath_var=LD_LIBRARY_PATH
+  fi
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  version_type=freebsd-elf
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=yes
+  hardcode_into_libs=yes
+  if test "$with_gnu_ld" = yes; then
+    sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib'
+  else
+    sys_lib_search_path_spec='/usr/ccs/lib /usr/lib'
+    case $host_os in
+      sco3.2v5*)
+        sys_lib_search_path_spec="$sys_lib_search_path_spec /lib"
+       ;;
+    esac
+  fi
+  sys_lib_dlsearch_path_spec='/usr/lib'
+  ;;
+
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host = GNU/Linux.
+  version_type=linux
+  need_lib_prefix=no
+  need_version=no
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=LD_LIBRARY_PATH
+  shlibpath_overrides_runpath=no
+  hardcode_into_libs=yes
+  ;;
+
+uts4*)
+  version_type=linux
+  library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}'
+  soname_spec='${libname}${release}${shared_ext}$major'
+  shlibpath_var=LD_LIBRARY_PATH
+  ;;
+
+*)
+  dynamic_linker=no
+  ;;
+esac
+AC_MSG_RESULT([$dynamic_linker])
+test "$dynamic_linker" = no && can_build_shared=no
+
+variables_saved_for_relink="PATH $shlibpath_var $runpath_var"
+if test "$GCC" = yes; then
+  variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH"
+fi
+
+if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then
+  sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then
+  sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+_LT_DECL([], [variables_saved_for_relink], [1],
+    [Variables whose values should be saved in libtool wrapper scripts and
+    restored at link time])
+_LT_DECL([], [need_lib_prefix], [0],
+    [Do we need the "lib" prefix for modules?])
+_LT_DECL([], [need_version], [0], [Do we need a version for libraries?])
+_LT_DECL([], [version_type], [0], [Library versioning type])
+_LT_DECL([], [runpath_var], [0],  [Shared library runtime path variable])
+_LT_DECL([], [shlibpath_var], [0],[Shared library path variable])
+_LT_DECL([], [shlibpath_overrides_runpath], [0],
+    [Is shlibpath searched before the hard-coded library search path?])
+_LT_DECL([], [libname_spec], [1], [Format of library name prefix])
+_LT_DECL([], [library_names_spec], [1],
+    [[List of archive names.  First name is the real one, the rest are links.
+    The last name is the one that the linker finds with -lNAME]])
+_LT_DECL([], [soname_spec], [1],
+    [[The coded name of the library, if different from the real name]])
+_LT_DECL([], [postinstall_cmds], [2],
+    [Command to use after installation of a shared archive])
+_LT_DECL([], [postuninstall_cmds], [2],
+    [Command to use after uninstallation of a shared archive])
+_LT_DECL([], [finish_cmds], [2],
+    [Commands used to finish a libtool library installation in a directory])
+_LT_DECL([], [finish_eval], [1],
+    [[As "finish_cmds", except a single script fragment to be evaled but
+    not shown]])
+_LT_DECL([], [hardcode_into_libs], [0],
+    [Whether we should hardcode library paths into libraries])
+_LT_DECL([], [sys_lib_search_path_spec], [2],
+    [Compile-time system search path for libraries])
+_LT_DECL([], [sys_lib_dlsearch_path_spec], [2],
+    [Run-time system search path for libraries])
+])# _LT_SYS_DYNAMIC_LINKER
+
+
+# _LT_PATH_TOOL_PREFIX(TOOL)
+# --------------------------
+# find a file program which can recognize shared library
+AC_DEFUN([_LT_PATH_TOOL_PREFIX],
+[m4_require([_LT_DECL_EGREP])dnl
+AC_MSG_CHECKING([for $1])
+AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
+[case $MAGIC_CMD in
+[[\\/*] |  ?:[\\/]*])
+  lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
+  ;;
+*)
+  lt_save_MAGIC_CMD="$MAGIC_CMD"
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+dnl $ac_dummy forces splitting on constant user-supplied paths.
+dnl POSIX.2 word splitting is done only on the output of word expansions,
+dnl not every word.  This closes a longstanding sh security hole.
+  ac_dummy="m4_if([$2], , $PATH, [$2])"
+  for ac_dir in $ac_dummy; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$1; then
+      lt_cv_path_MAGIC_CMD="$ac_dir/$1"
+      if test -n "$file_magic_test_file"; then
+       case $deplibs_check_method in
+       "file_magic "*)
+         file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"`
+         MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+         if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
+           $EGREP "$file_magic_regex" > /dev/null; then
+           :
+         else
+           cat <<_LT_EOF 1>&2
+
+*** Warning: the command libtool uses to detect shared libraries,
+*** $file_magic_cmd, produces output that libtool cannot recognize.
+*** The result is that libtool may fail to recognize shared libraries
+*** as such.  This will affect the creation of libtool libraries that
+*** depend on shared libraries, but programs linked with such libtool
+*** libraries will work regardless of this problem.  Nevertheless, you
+*** may want to report the problem to your system manager and/or to
+*** bug-libtool@gnu.org
+
+_LT_EOF
+         fi ;;
+       esac
+      fi
+      break
+    fi
+  done
+  IFS="$lt_save_ifs"
+  MAGIC_CMD="$lt_save_MAGIC_CMD"
+  ;;
+esac])
+MAGIC_CMD="$lt_cv_path_MAGIC_CMD"
+if test -n "$MAGIC_CMD"; then
+  AC_MSG_RESULT($MAGIC_CMD)
+else
+  AC_MSG_RESULT(no)
+fi
+_LT_DECL([], [MAGIC_CMD], [0],
+        [Used to examine libraries when file_magic_cmd begins with "file"])dnl
+])# _LT_PATH_TOOL_PREFIX
+
+# Old name:
+AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], [])
+
+
+# _LT_PATH_MAGIC
+# --------------
+# find a file program which can recognize a shared library
+m4_defun([_LT_PATH_MAGIC],
+[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
+if test -z "$lt_cv_path_MAGIC_CMD"; then
+  if test -n "$ac_tool_prefix"; then
+    _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
+  else
+    MAGIC_CMD=:
+  fi
+fi
+])# _LT_PATH_MAGIC
+
+
+# LT_PATH_LD
+# ----------
+# find the pathname to the GNU or non-GNU linker
+AC_DEFUN([LT_PATH_LD],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_CANONICAL_BUILD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+
+AC_ARG_WITH([gnu-ld],
+    [AS_HELP_STRING([--with-gnu-ld],
+       [assume the C compiler uses GNU ld @<:@default=no@:>@])],
+    [test "$withval" = no || with_gnu_ld=yes],
+    [with_gnu_ld=no])dnl
+
+ac_prog=ld
+if test "$GCC" = yes; then
+  # Check if gcc -print-prog-name=ld gives a path.
+  AC_MSG_CHECKING([for ld used by $CC])
+  case $host in
+  *-*-mingw*)
+    # gcc leaves a trailing carriage return which upsets mingw
+    ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+  *)
+    ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+  esac
+  case $ac_prog in
+    # Accept absolute paths.
+    [[\\/]]* | ?:[[\\/]]*)
+      re_direlt='/[[^/]][[^/]]*/\.\./'
+      # Canonicalize the pathname of ld
+      ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+       ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
+      done
+      test -z "$LD" && LD="$ac_prog"
+      ;;
+  "")
+    # If it fails, then pretend we aren't using GCC.
+    ac_prog=ld
+    ;;
+  *)
+    # If it is relative, then search for the first ld in PATH.
+    with_gnu_ld=unknown
+    ;;
+  esac
+elif test "$with_gnu_ld" = yes; then
+  AC_MSG_CHECKING([for GNU ld])
+else
+  AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(lt_cv_path_LD,
+[if test -z "$LD"; then
+  lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+  for ac_dir in $PATH; do
+    IFS="$lt_save_ifs"
+    test -z "$ac_dir" && ac_dir=.
+    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+      lt_cv_path_LD="$ac_dir/$ac_prog"
+      # Check to see if the program is GNU ld.  I'd rather use --version,
+      # but apparently some variants of GNU ld only accept -v.
+      # Break only if it was the GNU/non-GNU ld that we prefer.
+      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
+      *GNU* | *'with BFD'*)
+       test "$with_gnu_ld" != no && break
+       ;;
+      *)
+       test "$with_gnu_ld" != yes && break
+       ;;
+      esac
+    fi
+  done
+  IFS="$lt_save_ifs"
+else
+  lt_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$lt_cv_path_LD"
+if test -n "$LD"; then
+  AC_MSG_RESULT($LD)
+else
+  AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+_LT_PATH_LD_GNU
+AC_SUBST([LD])
+
+_LT_TAGDECL([], [LD], [1], [The linker used to build libraries])
+])# LT_PATH_LD
+
+# Old names:
+AU_ALIAS([AM_PROG_LD], [LT_PATH_LD])
+AU_ALIAS([AC_PROG_LD], [LT_PATH_LD])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_LD], [])
+dnl AC_DEFUN([AC_PROG_LD], [])
+
+
+# _LT_PATH_LD_GNU
+#- --------------
+m4_defun([_LT_PATH_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU lds only accept -v.
+case `$LD -v 2>&1 </dev/null` in
+*GNU* | *'with BFD'*)
+  lt_cv_prog_gnu_ld=yes
+  ;;
+*)
+  lt_cv_prog_gnu_ld=no
+  ;;
+esac])
+with_gnu_ld=$lt_cv_prog_gnu_ld
+])# _LT_PATH_LD_GNU
+
+
+# _LT_CMD_RELOAD
+# --------------
+# find reload flag for linker
+#   -- PORTME Some linkers may need a different reload flag.
+m4_defun([_LT_CMD_RELOAD],
+[AC_CACHE_CHECK([for $LD option to reload object files],
+  lt_cv_ld_reload_flag,
+  [lt_cv_ld_reload_flag='-r'])
+reload_flag=$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=" $reload_flag" ;;
+esac
+reload_cmds='$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  darwin*)
+    if test "$GCC" = yes; then
+      reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs'
+    else
+      reload_cmds='$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
+_LT_DECL([], [reload_flag], [1], [How to create reloadable object files])dnl
+_LT_DECL([], [reload_cmds], [2])dnl
+])# _LT_CMD_RELOAD
+
+
+# _LT_CHECK_MAGIC_METHOD
+# ----------------------
+# how to check for library dependencies
+#  -- PORTME fill in with the dynamic library characteristics
+m4_defun([_LT_CHECK_MAGIC_METHOD],
+[m4_require([_LT_DECL_EGREP])
+m4_require([_LT_DECL_OBJDUMP])
+AC_CACHE_CHECK([how to recognize dependent libraries],
+lt_cv_deplibs_check_method,
+[lt_cv_file_magic_cmd='$MAGIC_CMD'
+lt_cv_file_magic_test_file=
+lt_cv_deplibs_check_method='unknown'
+# Need to set the preceding variable on all platforms that support
+# interlibrary dependencies.
+# 'none' -- dependencies not supported.
+# `unknown' -- same as none, but documents that we really don't know.
+# 'pass_all' -- all dependencies passed with no checks.
+# 'test_compile' -- check by making test program.
+# 'file_magic [[regex]]' -- check by looking for files in library path
+# which responds to the $file_magic_cmd with a given extended regex.
+# If you have `file' or equivalent on your system and you're not sure
+# whether `pass_all' will *always* work, you probably want this one.
+
+case $host_os in
+aix[[4-9]]*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+beos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+bsdi[[45]]*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib)'
+  lt_cv_file_magic_cmd='/usr/bin/file -L'
+  lt_cv_file_magic_test_file=/shlib/libc.so
+  ;;
+
+cygwin*)
+  # func_win32_libid is a shell function defined in ltmain.sh
+  lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+  lt_cv_file_magic_cmd='func_win32_libid'
+  ;;
+
+mingw* | pw32*)
+  # Base MSYS/MinGW do not provide the 'file' command needed by
+  # func_win32_libid shell function, so use a weaker test based on 'objdump',
+  # unless we find 'file', for example because we are cross-compiling.
+  if ( file / ) >/dev/null 2>&1; then
+    lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd='func_win32_libid'
+  else
+    lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?'
+    lt_cv_file_magic_cmd='$OBJDUMP -f'
+  fi
+  ;;
+
+cegcc)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?'
+  lt_cv_file_magic_cmd='$OBJDUMP -f'
+  ;;
+
+darwin* | rhapsody*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    case $host_cpu in
+    i*86 )
+      # Not sure whether the presence of OpenBSD here was a mistake.
+      # Let's accept both of them until this is cleared up.
+      lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library'
+      lt_cv_file_magic_cmd=/usr/bin/file
+      lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*`
+      ;;
+    esac
+  else
+    lt_cv_deplibs_check_method=pass_all
+  fi
+  ;;
+
+gnu*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+hpux10.20* | hpux11*)
+  lt_cv_file_magic_cmd=/usr/bin/file
+  case $host_cpu in
+  ia64*)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64'
+    lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so
+    ;;
+  hppa*64*)
+    [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]']
+    lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl
+    ;;
+  *)
+    lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library'
+    lt_cv_file_magic_test_file=/usr/lib/libc.sl
+    ;;
+  esac
+  ;;
+
+interix[[3-9]]*)
+  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
+  lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$'
+  ;;
+
+irix5* | irix6* | nonstopux*)
+  case $LD in
+  *-32|*"-32 ") libmagic=32-bit;;
+  *-n32|*"-n32 ") libmagic=N32;;
+  *-64|*"-64 ") libmagic=64-bit;;
+  *) libmagic=never-match;;
+  esac
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+# This must be Linux ELF.
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+netbsd* | netbsdelf*-gnu)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
+  fi
+  ;;
+
+newos6*)
+  lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)'
+  lt_cv_file_magic_cmd=/usr/bin/file
+  lt_cv_file_magic_test_file=/usr/lib/libnls.so
+  ;;
+
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+openbsd*)
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$'
+  else
+    lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$'
+  fi
+  ;;
+
+osf3* | osf4* | osf5*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+rdos*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+solaris*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+
+sysv4 | sysv4.3*)
+  case $host_vendor in
+  motorola)
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
+    lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*`
+    ;;
+  ncr)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  sequent)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )'
+    ;;
+  sni)
+    lt_cv_file_magic_cmd='/bin/file'
+    lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib"
+    lt_cv_file_magic_test_file=/lib/libc.so
+    ;;
+  siemens)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  pc)
+    lt_cv_deplibs_check_method=pass_all
+    ;;
+  esac
+  ;;
+
+tpf*)
+  lt_cv_deplibs_check_method=pass_all
+  ;;
+esac
+])
+file_magic_cmd=$lt_cv_file_magic_cmd
+deplibs_check_method=$lt_cv_deplibs_check_method
+test -z "$deplibs_check_method" && deplibs_check_method=unknown
+
+_LT_DECL([], [deplibs_check_method], [1],
+    [Method to check whether dependent libraries are shared objects])
+_LT_DECL([], [file_magic_cmd], [1],
+    [Command to use when deplibs_check_method == "file_magic"])
+])# _LT_CHECK_MAGIC_METHOD
+
+
+# LT_PATH_NM
+# ----------
+# find the pathname to a BSD- or MS-compatible name lister
+AC_DEFUN([LT_PATH_NM],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM,
+[if test -n "$NM"; then
+  # Let the user override the test.
+  lt_cv_path_NM="$NM"
+else
+  lt_nm_to_check="${ac_tool_prefix}nm"
+  if test -n "$ac_tool_prefix" && test "$build" = "$host"; then
+    lt_nm_to_check="$lt_nm_to_check nm"
+  fi
+  for lt_tmp_nm in $lt_nm_to_check; do
+    lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
+    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
+      IFS="$lt_save_ifs"
+      test -z "$ac_dir" && ac_dir=.
+      tmp_nm="$ac_dir/$lt_tmp_nm"
+      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
+       # Check to see if the nm accepts a BSD-compat flag.
+       # Adding the `sed 1q' prevents false positives on HP-UX, which says:
+       #   nm: unknown option "B" ignored
+       # Tru64's nm complains that /dev/null is an invalid object file
+       case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
+       */dev/null* | *'Invalid file or object type'*)
+         lt_cv_path_NM="$tmp_nm -B"
+         break
+         ;;
+       *)
+         case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
+         */dev/null*)
+           lt_cv_path_NM="$tmp_nm -p"
+           break
+           ;;
+         *)
+           lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but
+           continue # so that we can try to find one that supports BSD flags
+           ;;
+         esac
+         ;;
+       esac
+      fi
+    done
+    IFS="$lt_save_ifs"
+  done
+  : ${lt_cv_path_NM=no}
+fi])
+if test "$lt_cv_path_NM" != "no"; then
+  NM="$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :)
+  AC_SUBST([DUMPBIN])
+  if test "$DUMPBIN" != ":"; then
+    NM="$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=nm
+AC_SUBST([NM])
+_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl
+
+AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface],
+  [lt_cv_nm_interface="BSD nm"
+  echo "int some_variable = 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:__oline__: $ac_compile\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:__oline__: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&AS_MESSAGE_LOG_FD
+  (eval echo "\"\$as_me:__oline__: output\"" >&AS_MESSAGE_LOG_FD)
+  cat conftest.out >&AS_MESSAGE_LOG_FD
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface="MS dumpbin"
+  fi
+  rm -f conftest*])
+])# LT_PATH_NM
+
+# Old names:
+AU_ALIAS([AM_PROG_NM], [LT_PATH_NM])
+AU_ALIAS([AC_PROG_NM], [LT_PATH_NM])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AM_PROG_NM], [])
+dnl AC_DEFUN([AC_PROG_NM], [])
+
+
+# LT_LIB_M
+# --------
+# check for math library
+AC_DEFUN([LT_LIB_M],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+LIBM=
+case $host in
+*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
+  # These system don't have libm, or don't need it
+  ;;
+*-ncr-sysv4.3*)
+  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw")
+  AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm")
+  ;;
+*)
+  AC_CHECK_LIB(m, cos, LIBM="-lm")
+  ;;
+esac
+AC_SUBST([LIBM])
+])# LT_LIB_M
+
+# Old name:
+AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([AC_CHECK_LIBM], [])
+
+
+# _LT_COMPILER_NO_RTTI([TAGNAME])
+# -------------------------------
+m4_defun([_LT_COMPILER_NO_RTTI],
+[m4_require([_LT_TAG_COMPILER])dnl
+
+_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+
+if test "$GCC" = yes; then
+  _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+
+  _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions],
+    lt_cv_prog_compiler_rtti_exceptions,
+    [-fno-rtti -fno-exceptions], [],
+    [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
+fi
+_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1],
+       [Compiler flag to turn off builtin functions])
+])# _LT_COMPILER_NO_RTTI
+
+
+# _LT_CMD_GLOBAL_SYMBOLS
+# ----------------------
+m4_defun([_LT_CMD_GLOBAL_SYMBOLS],
+[AC_REQUIRE([AC_CANONICAL_HOST])dnl
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+AC_REQUIRE([LT_PATH_LD])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+
+# Check for command to grab the raw symbol name followed by C symbol from nm.
+AC_MSG_CHECKING([command to parse $NM output from $compiler object])
+AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
+[
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode='[[BCDEGRST]]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode='[[BCDT]]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode='[[ABCDGISTW]]'
+  ;;
+hpux*)
+  if test "$host_cpu" = ia64; then
+    symcode='[[ABCDEGRST]]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode='[[BCDEGRST]]'
+  ;;
+osf*)
+  symcode='[[BCDEGQRST]]'
+  ;;
+solaris*)
+  symcode='[[BDRT]]'
+  ;;
+sco3.2v5*)
+  symcode='[[DT]]'
+  ;;
+sysv4.2uw2*)
+  symcode='[[DT]]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode='[[ABDT]]'
+  ;;
+sysv4)
+  symcode='[[DFNSTU]]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode='[[ABCDGIRSTW]]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\) $/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=
+case $build_os in
+mingw*)
+  opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
+
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol.
+  symxfrm="\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" = "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe="$AWK ['"\
+"     {last_section=section; section=\$ 3};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\
+"     ' prfx=^$ac_symprfx]"
+  else
+    lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[    ]]\($symcode$symcode*\)[[       ]][[    ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+
+  # Check to see that the pipe works correctly.
+  pipe_works=no
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var='a';nm_test_func();return(0);}
+_LT_EOF
+
+  if AC_TRY_EVAL(ac_compile); then
+    # Now try to grab the symbols.
+    nlist=conftest.nm
+    if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+       mv -f "$nlist"T "$nlist"
+      else
+       rm -f "$nlist"T
+      fi
+
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+       if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+         cat <<_LT_EOF > conftest.$ac_ext
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+_LT_EOF
+         # Now generate the symbol file.
+         eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext'
+
+         cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+const struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[[]] =
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+         $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext
+         cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+_LT_EOF
+         # Now try linking the two files.
+         mv conftest.$ac_objext conftstm.$ac_objext
+         lt_save_LIBS="$LIBS"
+         lt_save_CFLAGS="$CFLAGS"
+         LIBS="conftstm.$ac_objext"
+         CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
+         if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
+           pipe_works=yes
+         fi
+         LIBS="$lt_save_LIBS"
+         CFLAGS="$lt_save_CFLAGS"
+       else
+         echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
+       fi
+      else
+       echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
+    fi
+  else
+    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" = yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=
+  fi
+done
+])
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then
+  AC_MSG_RESULT(failed)
+else
+  AC_MSG_RESULT(ok)
+fi
+
+_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1],
+    [Take the output of nm and produce a listing of raw symbols and C names])
+_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1],
+    [Transform the output of nm in a proper C declaration])
+_LT_DECL([global_symbol_to_c_name_address],
+    [lt_cv_sys_global_symbol_to_c_name_address], [1],
+    [Transform the output of nm in a C name address pair])
+_LT_DECL([global_symbol_to_c_name_address_lib_prefix],
+    [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1],
+    [Transform the output of nm in a C name address pair when lib prefix is needed])
+]) # _LT_CMD_GLOBAL_SYMBOLS
+
+
+# _LT_COMPILER_PIC([TAGNAME])
+# ---------------------------
+m4_defun([_LT_COMPILER_PIC],
+[m4_require([_LT_TAG_COMPILER])dnl
+_LT_TAGVAR(lt_prog_compiler_wl, $1)=
+_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+_LT_TAGVAR(lt_prog_compiler_static, $1)=
+
+AC_MSG_CHECKING([for $compiler option to produce PIC])
+m4_if([$1], [CXX], [
+  # C++ specific cases for pic, static, wl, etc.
+  if test "$GXX" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+    aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+       # AIX 5 now supports IA64 processor
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+    mingw* | cygwin* | os2* | pw32* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+       [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+    *djgpp*)
+      # DJGPP does not support shared libraries at all
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+      ;;
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+    sysv4*MP*)
+      if test -d /usr/nec; then
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+       ;;
+      *)
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+       ;;
+      esac
+      ;;
+    *qnx* | *nto*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    case $host_os in
+      aix[[4-9]]*)
+       # All AIX code is PIC.
+       if test "$host_cpu" = ia64; then
+         # AIX 5 now supports IA64 processor
+         _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+       else
+         _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+       fi
+       ;;
+      chorus*)
+       case $cc_basename in
+       cxch68*)
+         # Green Hills C++ Compiler
+         # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
+         ;;
+       esac
+       ;;
+      dgux*)
+       case $cc_basename in
+         ec++*)
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+           ;;
+         ghcx*)
+           # Green Hills C++ Compiler
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      freebsd* | dragonfly*)
+       # FreeBSD uses GNU C++
+       ;;
+      hpux9* | hpux10* | hpux11*)
+       case $cc_basename in
+         CC*)
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+           if test "$host_cpu" != ia64; then
+             _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+           fi
+           ;;
+         aCC*)
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+           case $host_cpu in
+           hppa*64*|ia64*)
+             # +Z the default
+             ;;
+           *)
+             _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+             ;;
+           esac
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      interix*)
+       # This is c89, which is MS Visual C++ (no shared libs)
+       # Anyone wants to do a port?
+       ;;
+      irix5* | irix6* | nonstopux*)
+       case $cc_basename in
+         CC*)
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+           # CC pic flag -KPIC is the default.
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+       case $cc_basename in
+         KCC*)
+           # KAI C++ Compiler
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+           ;;
+         ecpc* )
+           # old Intel C++ for x86_64 which still supported -KPIC.
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+           ;;
+         icpc* )
+           # Intel C++, used to be incompatible with GCC.
+           # ICC 10 doesn't accept -KPIC any more.
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+           ;;
+         pgCC* | pgcpp*)
+           # Portland Group C++ compiler
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+           ;;
+         cxx*)
+           # Compaq C++
+           # Make sure the PIC flag is empty.  It appears that all Alpha
+           # Linux and Compaq Tru64 Unix objects are PIC.
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+           ;;
+         xlc* | xlC*)
+           # IBM XL 8.0 on PPC
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+           ;;
+         *)
+           case `$CC -V 2>&1 | sed 5q` in
+           *Sun\ C*)
+             # Sun C++ 5.9
+             _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+             _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+             _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+             ;;
+           esac
+           ;;
+       esac
+       ;;
+      lynxos*)
+       ;;
+      m88k*)
+       ;;
+      mvs*)
+       case $cc_basename in
+         cxx*)
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall'
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      netbsd* | netbsdelf*-gnu)
+       ;;
+      *qnx* | *nto*)
+        # QNX uses GNU C++, but need to define -shared option too, otherwise
+        # it will coredump.
+        _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+        ;;
+      osf3* | osf4* | osf5*)
+       case $cc_basename in
+         KCC*)
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,'
+           ;;
+         RCC*)
+           # Rational C++ 2.4.1
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+           ;;
+         cxx*)
+           # Digital/Compaq C++
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           # Make sure the PIC flag is empty.  It appears that all Alpha
+           # Linux and Compaq Tru64 Unix objects are PIC.
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      psos*)
+       ;;
+      solaris*)
+       case $cc_basename in
+         CC*)
+           # Sun C++ 4.2, 5.x and Centerline C++
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+           ;;
+         gcx*)
+           # Green Hills C++ Compiler
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      sunos4*)
+       case $cc_basename in
+         CC*)
+           # Sun C++ 4.x
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+           ;;
+         lcc*)
+           # Lucid
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+       case $cc_basename in
+         CC*)
+           _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+           _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+           ;;
+       esac
+       ;;
+      tandem*)
+       case $cc_basename in
+         NCC*)
+           # NonStop-UX NCC 3.20
+           _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+           ;;
+         *)
+           ;;
+       esac
+       ;;
+      vxworks*)
+       ;;
+      *)
+       _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+       ;;
+    esac
+  fi
+],
+[
+  if test "$GCC" = yes; then
+    _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+    _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+
+    case $host_os in
+      aix*)
+      # All AIX code is PIC.
+      if test "$host_cpu" = ia64; then
+       # AIX 5 now supports IA64 processor
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries, but
+            # adding the `-m68020' flag to GCC prevents building anything better,
+            # like `-m68040'.
+            _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      # PIC is the default for these OSes.
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-style
+      # (--disable-auto-import) libraries
+      m4_if([$1], [GCJ], [],
+       [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    darwin* | rhapsody*)
+      # PIC is the default on this platform
+      # Common symbols not allowed in MH_DYLIB files
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common'
+      ;;
+
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+       # +Z the default
+       ;;
+      *)
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+       ;;
+      esac
+      ;;
+
+    interix[[3-9]]*)
+      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
+      # Instead, we relocate shared libraries at runtime.
+      ;;
+
+    msdosdjgpp*)
+      # Just because we use GCC doesn't mean we suddenly get shared libraries
+      # on systems that don't support them.
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      enable_shared=no
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic
+      fi
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+      ;;
+    esac
+  else
+    # PORTME Check for flag to pass linker flags through the system compiler.
+    case $host_os in
+    aix*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      if test "$host_cpu" = ia64; then
+       # AIX 5 now supports IA64 processor
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      else
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp'
+      fi
+      ;;
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
+      # This hack is so that the source file can tell whether it is being
+      # built for inclusion in a dll (and should export symbols for example).
+      m4_if([$1], [GCJ], [],
+       [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT'])
+      ;;
+
+    hpux9* | hpux10* | hpux11*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
+      # not for PA HP-UX.
+      case $host_cpu in
+      hppa*64*|ia64*)
+       # +Z the default
+       ;;
+      *)
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z'
+       ;;
+      esac
+      # Is there a better lt_prog_compiler_static that works with the bundled CC?
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive'
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # PIC (with -KPIC) is the default.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
+      case $cc_basename in
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC'
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared'
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='--static'
+       ;;
+      pgcc* | pgf77* | pgf90* | pgf95*)
+        # Portland Group compilers (*not* the Pentium gcc compiler,
+       # which looks to be a dead project)
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic'
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+        ;;
+      ccc*)
+        _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+        # All Alpha code is PIC.
+        _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+        ;;
+      xl*)
+       # IBM XL C 8.0/Fortran 10.1 on PPC
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic'
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink'
+       ;;
+      *)
+       case `$CC -V 2>&1 | sed 5q` in
+       *Sun\ C*)
+         # Sun C 5.9
+         _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+         _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+         _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+         ;;
+       *Sun\ F*)
+         # Sun Fortran 8.3 passes all unrecognized flags to the linker
+         _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+         _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+         _LT_TAGVAR(lt_prog_compiler_wl, $1)=''
+         ;;
+       esac
+       ;;
+      esac
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared'
+      ;;
+
+    osf3* | osf4* | osf5*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      # All OSF/1 code is PIC.
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    rdos*)
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared'
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      case $cc_basename in
+      f77* | f90* | f95*)
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';;
+      *)
+       _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld '
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4 | sysv4.2uw2* | sysv4.3*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec ;then
+       _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic'
+       _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      fi
+      ;;
+
+    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    unicos*)
+      _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,'
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic'
+      _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic'
+      ;;
+
+    *)
+      _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no
+      ;;
+    esac
+  fi
+])
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)=
+    ;;
+  *)
+    _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])"
+    ;;
+esac
+AC_MSG_RESULT([$_LT_TAGVAR(lt_prog_compiler_pic, $1)])
+_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1],
+       [How to pass a linker flag through the compiler])
+
+#
+# Check to make sure the PIC flag actually works.
+#
+if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then
+  _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works],
+    [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)],
+    [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [],
+    [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in
+     "" | " "*) ;;
+     *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;;
+     esac],
+    [_LT_TAGVAR(lt_prog_compiler_pic, $1)=
+     _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no])
+fi
+_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1],
+       [Additional compiler flags for building library objects])
+
+#
+# Check to make sure the static flag actually works.
+#
+wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\"
+_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works],
+  _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1),
+  $lt_tmp_static_flag,
+  [],
+  [_LT_TAGVAR(lt_prog_compiler_static, $1)=])
+_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1],
+       [Compiler flag to prevent dynamic linking])
+])# _LT_COMPILER_PIC
+
+
+# _LT_LINKER_SHLIBS([TAGNAME])
+# ----------------------------
+# See if the linker supports building shared libraries.
+m4_defun([_LT_LINKER_SHLIBS],
+[AC_REQUIRE([LT_PATH_LD])dnl
+AC_REQUIRE([LT_PATH_NM])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+m4_require([_LT_DECL_SED])dnl
+m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl
+m4_require([_LT_TAG_COMPILER])dnl
+AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+m4_if([$1], [CXX], [
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  case $host_os in
+  aix[[4-9]]*)
+    # If we're using GNU nm, then we don't want the "-C" option.
+    # -C means demangle to AIX nm, but means don't demangle with GNU nm
+    if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    else
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+    fi
+    ;;
+  pw32*)
+    _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds"
+  ;;
+  cygwin* | mingw* | cegcc*)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols'
+  ;;
+  linux* | k*bsd*-gnu)
+    _LT_TAGVAR(link_all_deplibs, $1)=no
+  ;;
+  *)
+    _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  ;;
+  esac
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+], [
+  runpath_var=
+  _LT_TAGVAR(allow_undefined_flag, $1)=
+  _LT_TAGVAR(always_export_symbols, $1)=no
+  _LT_TAGVAR(archive_cmds, $1)=
+  _LT_TAGVAR(archive_expsym_cmds, $1)=
+  _LT_TAGVAR(compiler_needs_object, $1)=no
+  _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+  _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+  _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  _LT_TAGVAR(hardcode_automatic, $1)=no
+  _LT_TAGVAR(hardcode_direct, $1)=no
+  _LT_TAGVAR(hardcode_direct_absolute, $1)=no
+  _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+  _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+  _LT_TAGVAR(hardcode_libdir_separator, $1)=
+  _LT_TAGVAR(hardcode_minus_L, $1)=no
+  _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+  _LT_TAGVAR(inherit_rpath, $1)=no
+  _LT_TAGVAR(link_all_deplibs, $1)=unknown
+  _LT_TAGVAR(module_cmds, $1)=
+  _LT_TAGVAR(module_expsym_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_new_cmds, $1)=
+  _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)=
+  _LT_TAGVAR(thread_safe_flag_spec, $1)=
+  _LT_TAGVAR(whole_archive_flag_spec, $1)=
+  # include_expsyms should be a list of space-separated symbols to be *always*
+  # included in the symbol list
+  _LT_TAGVAR(include_expsyms, $1)=
+  # exclude_expsyms can be an extended regexp of symbols to exclude
+  # it will be wrapped by ` (' and `)$', so one must not match beginning or
+  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc',
+  # as well as any symbol that contains `d'.
+  _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*']
+  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
+  # platforms (ab)use it in PIC code, but their linkers get confused if
+  # the symbol is explicitly referenced.  Since portable code cannot
+  # rely on this symbol name, it's probably fine to never include it in
+  # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
+dnl Note also adjust exclude_expsyms for C++ above.
+  extract_expsyms_cmds=
+
+  case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    # FIXME: the MSVC++ port hasn't been tested in a loooong time
+    # When not using gcc, we currently assume that we are using
+    # Microsoft Visual C++.
+    if test "$GCC" != yes; then
+      with_gnu_ld=no
+    fi
+    ;;
+  interix*)
+    # we just hope/assume this is gcc and not c89 (= MSVC++)
+    with_gnu_ld=yes
+    ;;
+  openbsd*)
+    with_gnu_ld=no
+    ;;
+  linux* | k*bsd*-gnu)
+    _LT_TAGVAR(link_all_deplibs, $1)=no
+    ;;
+  esac
+
+  _LT_TAGVAR(ld_shlibs, $1)=yes
+  if test "$with_gnu_ld" = yes; then
+    # If archive_cmds runs LD, not CC, wlarc should be empty
+    wlarc='${wl}'
+
+    # Set some defaults for GNU ld with shared library support. These
+    # are reset later if shared libraries are not supported. Putting them
+    # here allows them to be overridden if necessary.
+    runpath_var=LD_RUN_PATH
+    _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+    _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+    # ancient GNU ld didn't support --whole-archive et. al.
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+    else
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+    supports_anon_versioning=no
+    case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=yes ;;
+      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
+      *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ...
+      *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ...
+      *\ 2.11.*) ;; # other 2.11 versions
+      *) supports_anon_versioning=yes ;;
+    esac
+
+    # See if GNU ld supports shared libraries.
+    case $host_os in
+    aix[[3-9]]*)
+      # On AIX/PPC, the GNU linker is very broken
+      if test "$host_cpu" != ia64; then
+       _LT_TAGVAR(ld_shlibs, $1)=no
+       cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+*** to be unable to reliably create shared libraries on AIX.
+*** Therefore, libtool is disabling shared libraries support.  If you
+*** really care for shared libraries, you may want to modify your PATH
+*** so that a non-GNU linker is found, and then restart.
+
+_LT_EOF
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    beos*)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+       _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+       # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
+       # support --undefined.  This deserves some investigation.  FIXME
+       _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+      else
+       _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+      # as there is no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=no
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols'
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+       # If the export-symbols file already is a .def file (1st line
+       # is EXPORTS), use it as is; otherwise, prepend...
+       _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+         cp $export_symbols $output_objdir/$soname.def;
+       else
+         echo EXPORTS > $output_objdir/$soname.def;
+         cat $export_symbols >> $output_objdir/$soname.def;
+       fi~
+       $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+      else
+       _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    interix[[3-9]]*)
+      _LT_TAGVAR(hardcode_direct, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+      # Instead, shared libraries are loaded at an image base (0x10000000 by
+      # default) and relocated if they conflict, which is a slow very memory
+      # consuming and fragmenting process.  To avoid this, we pick a random,
+      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+      ;;
+
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      tmp_diet=no
+      if test "$host_os" = linux-dietlibc; then
+       case $cc_basename in
+         diet\ *) tmp_diet=yes;;       # linux-dietlibc with static linking (!diet-dyn)
+       esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \
+        && test "$tmp_diet" = no
+      then
+       tmp_addflag=
+       tmp_sharedflag='-shared'
+       case $cc_basename,$host_cpu in
+        pgcc*)                         # Portland Group C compiler
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+         tmp_addflag=' $pic_flag'
+         ;;
+       pgf77* | pgf90* | pgf95*)       # Portland Group f77 and f90 compilers
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+         tmp_addflag=' $pic_flag -Mnomain' ;;
+       ecc*,ia64* | icc*,ia64*)        # Intel C compiler on ia64
+         tmp_addflag=' -i_dynamic' ;;
+       efc*,ia64* | ifort*,ia64*)      # Intel Fortran compiler on ia64
+         tmp_addflag=' -i_dynamic -nofor_main' ;;
+       ifc* | ifort*)                  # Intel Fortran compiler
+         tmp_addflag=' -nofor_main' ;;
+       lf95*)                          # Lahey Fortran 8.1
+         _LT_TAGVAR(whole_archive_flag_spec, $1)=
+         tmp_sharedflag='--shared' ;;
+       xl[[cC]]*)                      # IBM XL C 8.0 on PPC (deal with xlf below)
+         tmp_sharedflag='-qmkshrobj'
+         tmp_addflag= ;;
+       esac
+       case `$CC -V 2>&1 | sed 5q` in
+       *Sun\ C*)                       # Sun C 5.9
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+         _LT_TAGVAR(compiler_needs_object, $1)=yes
+         tmp_sharedflag='-G' ;;
+       *Sun\ F*)                       # Sun Fortran 8.3
+         tmp_sharedflag='-G' ;;
+       esac
+       _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+        if test "x$supports_anon_versioning" = xyes; then
+          _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+           cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+           echo "local: *; };" >> $output_objdir/$libname.ver~
+           $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+        fi
+
+       case $cc_basename in
+       xlf*)
+         # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive'
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+         _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir'
+         _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib'
+         if test "x$supports_anon_versioning" = xyes; then
+           _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+             cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+             echo "local: *; };" >> $output_objdir/$libname.ver~
+             $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib'
+         fi
+         ;;
+       esac
+      else
+        _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    netbsd* | netbsdelf*-gnu)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+       _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
+       wlarc=
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      fi
+      ;;
+
+    solaris*)
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
+       _LT_TAGVAR(ld_shlibs, $1)=no
+       cat <<_LT_EOF 1>&2
+
+*** Warning: The releases 2.8.* of the GNU linker cannot reliably
+*** create shared libraries on Solaris systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.9.1 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+       _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
+      case `$LD -v 2>&1` in
+        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)
+       _LT_TAGVAR(ld_shlibs, $1)=no
+       cat <<_LT_EOF 1>&2
+
+*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
+*** reliably create shared libraries on SCO systems.  Therefore, libtool
+*** is disabling shared libraries support.  We urge you to upgrade GNU
+*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
+*** your PATH or compiler configuration so that the native linker is
+*** used, and then restart.
+
+_LT_EOF
+       ;;
+       *)
+         # For security reasons, it is highly recommended that you always
+         # use absolute paths for naming shared libraries, and exclude the
+         # DT_RUNPATH tag from executables and libraries.  But doing so
+         # requires that you compile everything twice, which is a pain.
+         if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+           _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+           _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+         else
+           _LT_TAGVAR(ld_shlibs, $1)=no
+         fi
+       ;;
+      esac
+      ;;
+
+    sunos4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      wlarc=
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      else
+       _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+    esac
+
+    if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then
+      runpath_var=
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=
+      _LT_TAGVAR(whole_archive_flag_spec, $1)=
+    fi
+  else
+    # PORTME fill in a description of your system's linker (not GNU ld)
+    case $host_os in
+    aix3*)
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname'
+      # Note: this linker hardcodes the directories in LIBPATH if there
+      # are no directories specified by -L.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then
+       # Neither direct hardcoding nor static linking is supported with a
+       # broken collect2.
+       _LT_TAGVAR(hardcode_direct, $1)=unsupported
+      fi
+      ;;
+
+    aix[[4-9]]*)
+      if test "$host_cpu" = ia64; then
+       # On IA64, the linker does run time linking by default, so we don't
+       # have to do anything special.
+       aix_use_runtimelinking=no
+       exp_sym_flag='-Bexport'
+       no_entry_flag=""
+      else
+       # If we're using GNU nm, then we don't want the "-C" option.
+       # -C means demangle to AIX nm, but means don't demangle with GNU nm
+       if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+         _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+       else
+         _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
+       fi
+       aix_use_runtimelinking=no
+
+       # Test if we are trying to use run time linking or normal
+       # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+       # need to do runtime linking.
+       case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+         for ld_flag in $LDFLAGS; do
+         if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then
+           aix_use_runtimelinking=yes
+           break
+         fi
+         done
+         ;;
+       esac
+
+       exp_sym_flag='-bexport'
+       no_entry_flag='-bnoentry'
+      fi
+
+      # When large executables or shared objects are built, AIX ld can
+      # have problems creating the table of contents.  If linking a library
+      # or program results in "error TOC overflow" add -mminimal-toc to
+      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+      _LT_TAGVAR(archive_cmds, $1)=''
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+      if test "$GCC" = yes; then
+       case $host_os in aix4.[[012]]|aix4.[[012]].*)
+       # We only want to do this on AIX 4.2 and lower, the check
+       # below for broken collect2 doesn't work under 4.3+
+         collect2name=`${CC} -print-prog-name=collect2`
+         if test -f "$collect2name" &&
+          strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+         then
+         # We have reworked collect2
+         :
+         else
+         # We have old collect2
+         _LT_TAGVAR(hardcode_direct, $1)=unsupported
+         # It fails to find uninstalled libraries when the uninstalled
+         # path is not listed in the libpath.  Setting hardcode_minus_L
+         # to unsupported forces relinking
+         _LT_TAGVAR(hardcode_minus_L, $1)=yes
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+         _LT_TAGVAR(hardcode_libdir_separator, $1)=
+         fi
+         ;;
+       esac
+       shared_flag='-shared'
+       if test "$aix_use_runtimelinking" = yes; then
+         shared_flag="$shared_flag "'${wl}-G'
+       fi
+       _LT_TAGVAR(link_all_deplibs, $1)=no
+      else
+       # not using gcc
+       if test "$host_cpu" = ia64; then
+       # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+       # chokes on -Wl,-G. The following line is correct:
+         shared_flag='-G'
+       else
+         if test "$aix_use_runtimelinking" = yes; then
+           shared_flag='${wl}-G'
+         else
+           shared_flag='${wl}-bM:SRE'
+         fi
+       fi
+      fi
+
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+      # It seems that -bexpall does not export symbols beginning with
+      # underscore (_), so it is better to generate a list of symbols to export.
+      _LT_TAGVAR(always_export_symbols, $1)=yes
+      if test "$aix_use_runtimelinking" = yes; then
+       # Warning - without using the other runtime loading flags (-brtl),
+       # -berok will link without error, but may produce a broken library.
+       _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        _LT_SYS_MODULE_PATH_AIX
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
+       if test "$host_cpu" = ia64; then
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+         _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+         _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+       else
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        _LT_SYS_MODULE_PATH_AIX
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+         # Warning - without using the other run time loading flags,
+         # -berok will link without error, but may produce a broken library.
+         _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+         _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+         # Exported symbols can be pulled into shared objects from archives
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+         _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+         # This is similar to how AIX traditionally builds its shared libraries.
+         _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+       fi
+      fi
+      ;;
+
+    amigaos*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+            _LT_TAGVAR(archive_expsym_cmds, $1)=''
+        ;;
+      m68k)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes
+        ;;
+      esac
+      ;;
+
+    bsdi[[45]]*)
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic
+      ;;
+
+    cygwin* | mingw* | pw32* | cegcc*)
+      # When not using gcc, we currently assume that we are using
+      # Microsoft Visual C++.
+      # hardcode_libdir_flag_spec is actually meaningless, as there is
+      # no search path for DLLs.
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' '
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      # Tell ltmain to make .lib files, not .a files.
+      libext=lib
+      # Tell ltmain to make .dll files, not .so files.
+      shrext_cmds=".dll"
+      # FIXME: Setting linknames here is a bad hack.
+      _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames='
+      # The linker will automatically build a .lib file if we build a DLL.
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='true'
+      # FIXME: Should let the user specify the lib program.
+      _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs'
+      _LT_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`'
+      _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+      ;;
+
+    darwin* | rhapsody*)
+      _LT_DARWIN_LINKER_FEATURES($1)
+      ;;
+
+    dgux*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    freebsd1*)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+
+    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor
+    # support.  Future versions do this automatically, but an explicit c++rt0.o
+    # does not break anything, and helps significantly (at the cost of a little
+    # extra space).
+    freebsd2.2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
+    freebsd2*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
+    freebsd* | dragonfly*)
+      _LT_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    hpux9*)
+      if test "$GCC" = yes; then
+       _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+
+      # hardcode_minus_L: Not really in the search PATH,
+      # but as the default location of the library.
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+      ;;
+
+    hpux10*)
+      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      if test "$with_gnu_ld" = no; then
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+       _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir'
+       _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+       _LT_TAGVAR(hardcode_direct, $1)=yes
+       _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+       _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+       # hardcode_minus_L: Not really in the search PATH,
+       # but as the default location of the library.
+       _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      fi
+      ;;
+
+    hpux11*)
+      if test "$GCC" = yes -a "$with_gnu_ld" = no; then
+       case $host_cpu in
+       hppa*64*)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       ia64*)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       *)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       esac
+      else
+       case $host_cpu in
+       hppa*64*)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       ia64*)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       *)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       esac
+      fi
+      if test "$with_gnu_ld" = no; then
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+       _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+       case $host_cpu in
+       hppa*64*|ia64*)
+         _LT_TAGVAR(hardcode_direct, $1)=no
+         _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+         ;;
+       *)
+         _LT_TAGVAR(hardcode_direct, $1)=yes
+         _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+         _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+
+         # hardcode_minus_L: Not really in the search PATH,
+         # but as the default location of the library.
+         _LT_TAGVAR(hardcode_minus_L, $1)=yes
+         ;;
+       esac
+      fi
+      ;;
+
+    irix5* | irix6* | nonstopux*)
+      if test "$GCC" = yes; then
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+       # Try to use the -exported_symbol ld option, if it does not
+       # work, assume that -exports_file does not work either and
+       # implicitly export all symbols.
+        save_LDFLAGS="$LDFLAGS"
+        LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null"
+        AC_LINK_IFELSE(int foo(void) {},
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+        )
+        LDFLAGS="$save_LDFLAGS"
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(inherit_rpath, $1)=yes
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    netbsd* | netbsdelf*-gnu)
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+       _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'  # a.out
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags'      # ELF
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    newsos6)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *nto* | *qnx*)
+      ;;
+
+    openbsd*)
+      if test -f /usr/libexec/ld.so; then
+       _LT_TAGVAR(hardcode_direct, $1)=yes
+       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+       _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+       if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+         _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+         _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+       else
+         case $host_os in
+          openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
+            _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+            ;;
+          *)
+            _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags'
+            _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+            ;;
+         esac
+       fi
+      else
+       _LT_TAGVAR(ld_shlibs, $1)=no
+      fi
+      ;;
+
+    os2*)
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+      _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def'
+      ;;
+
+    osf3*)
+      if test "$GCC" = yes; then
+       _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+      else
+       _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    osf4* | osf5*)     # as osf3* with the addition of -msym flag
+      if test "$GCC" = yes; then
+       _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+      else
+       _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~
+       $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp'
+
+       # Both c and cxx compiler support -rpath directly
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+      fi
+      _LT_TAGVAR(archive_cmds_need_lc, $1)='no'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+      ;;
+
+    solaris*)
+      _LT_TAGVAR(no_undefined_flag, $1)=' -z defs'
+      if test "$GCC" = yes; then
+       wlarc='${wl}'
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+         $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+       case `$CC -V 2>&1` in
+       *"Compilers 5.0"*)
+         wlarc=''
+         _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags'
+         _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+         $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp'
+         ;;
+       *)
+         wlarc='${wl}'
+         _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags'
+         _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+         $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+         ;;
+       esac
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      case $host_os in
+      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+      *)
+       # The compiler driver will combine and reorder linker options,
+       # but understands `-z linker_flag'.  GCC discards it without `$wl',
+       # but is careful enough not to reorder.
+       # Supported since Solaris 2.6 (maybe 2.5.1?)
+       if test "$GCC" = yes; then
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+       else
+         _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+       fi
+       ;;
+      esac
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      ;;
+
+    sunos4*)
+      if test "x$host_vendor" = xsequent; then
+       # Use $CC to link under sequent, because it throws in some extra .o
+       # files that make .init and .fini sections work.
+       _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags'
+      fi
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_direct, $1)=yes
+      _LT_TAGVAR(hardcode_minus_L, $1)=yes
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4)
+      case $host_vendor in
+       sni)
+         _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+         _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true???
+       ;;
+       siemens)
+         ## LD is ld it makes a PLAMLIB
+         ## CC just makes a GrossModule.
+         _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags'
+         _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs'
+         _LT_TAGVAR(hardcode_direct, $1)=no
+        ;;
+       motorola)
+         _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+         _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie
+       ;;
+      esac
+      runpath_var='LD_RUN_PATH'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    sysv4.3*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport'
+      ;;
+
+    sysv4*MP*)
+      if test -d /usr/nec; then
+       _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+       runpath_var=LD_RUN_PATH
+       hardcode_runpath_var=yes
+       _LT_TAGVAR(ld_shlibs, $1)=yes
+      fi
+      ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    sysv5* | sco3.2v5* | sco5v6*)
+      # Note: We can NOT use -z defs as we might desire, because we do not
+      # link with -lc, and that would cause any symbols used from libc to
+      # always be unresolved, which means just about no library would
+      # ever link correctly.  If we're not using GNU ld we use -z text
+      # though, which does catch some bad symbols but isn't as heavy-handed
+      # as -z defs.
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+      _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+      _LT_TAGVAR(link_all_deplibs, $1)=yes
+      _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+      runpath_var='LD_RUN_PATH'
+
+      if test "$GCC" = yes; then
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+       _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+      fi
+      ;;
+
+    uts4*)
+      _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags'
+      _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      ;;
+
+    *)
+      _LT_TAGVAR(ld_shlibs, $1)=no
+      ;;
+    esac
+
+    if test x$host_vendor = xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+       _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym'
+       ;;
+      esac
+    fi
+  fi
+])
+AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld
+
+_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl
+_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl
+_LT_DECL([], [extract_expsyms_cmds], [2],
+    [The commands to extract the exported symbol list from a shared archive])
+
+#
+# Do we need to explicitly link libc?
+#
+case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in
+x|xyes)
+  # Assume -lc should be added
+  _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+
+  if test "$enable_shared" = yes && test "$GCC" = yes; then
+    case $_LT_TAGVAR(archive_cmds, $1) in
+    *'~'*)
+      # FIXME: we may have to deal with multi-command sequences.
+      ;;
+    '$CC '*)
+      # Test whether the compiler implicitly links with -lc since on some
+      # systems, -lgcc has to come before -lc. If gcc already passes -lc
+      # to ld, don't add -lc before -lgcc.
+      AC_MSG_CHECKING([whether -lc should be explicitly linked in])
+      $RM conftest*
+      echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+      if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
+        soname=conftest
+        lib=conftest
+        libobjs=conftest.$ac_objext
+        deplibs=
+        wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1)
+       pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1)
+        compiler_flags=-v
+        linker_flags=-v
+        verstring=
+        output_objdir=.
+        libname=conftest
+        lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1)
+        _LT_TAGVAR(allow_undefined_flag, $1)=
+        if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1)
+        then
+         _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        else
+         _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+        fi
+        _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag
+      else
+        cat conftest.err 1>&5
+      fi
+      $RM conftest*
+      AC_MSG_RESULT([$_LT_TAGVAR(archive_cmds_need_lc, $1)])
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0],
+    [Whether or not to add -lc for building shared libraries])
+_LT_TAGDECL([allow_libtool_libs_with_static_runtimes],
+    [enable_shared_with_static_runtimes], [0],
+    [Whether or not to disallow shared libs when runtime libs are static])
+_LT_TAGDECL([], [export_dynamic_flag_spec], [1],
+    [Compiler flag to allow reflexive dlopens])
+_LT_TAGDECL([], [whole_archive_flag_spec], [1],
+    [Compiler flag to generate shared objects directly from archives])
+_LT_TAGDECL([], [compiler_needs_object], [1],
+    [Whether the compiler copes with passing no objects directly])
+_LT_TAGDECL([], [old_archive_from_new_cmds], [2],
+    [Create an old-style archive from a shared archive])
+_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2],
+    [Create a temporary old-style archive to link instead of a shared archive])
+_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive])
+_LT_TAGDECL([], [archive_expsym_cmds], [2])
+_LT_TAGDECL([], [module_cmds], [2],
+    [Commands used to build a loadable module if different from building
+    a shared archive.])
+_LT_TAGDECL([], [module_expsym_cmds], [2])
+_LT_TAGDECL([], [with_gnu_ld], [1],
+    [Whether we are building with GNU ld or not])
+_LT_TAGDECL([], [allow_undefined_flag], [1],
+    [Flag that allows shared libraries with undefined symbols to be built])
+_LT_TAGDECL([], [no_undefined_flag], [1],
+    [Flag that enforces no undefined symbols])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1],
+    [Flag to hardcode $libdir into a binary during linking.
+    This must work even if $libdir does not exist])
+_LT_TAGDECL([], [hardcode_libdir_flag_spec_ld], [1],
+    [[If ld is used when linking, flag to hardcode $libdir into a binary
+    during linking.  This must work even if $libdir does not exist]])
+_LT_TAGDECL([], [hardcode_libdir_separator], [1],
+    [Whether we need a single "-rpath" flag with a separated argument])
+_LT_TAGDECL([], [hardcode_direct], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary])
+_LT_TAGDECL([], [hardcode_direct_absolute], [0],
+    [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes
+    DIR into the resulting binary and the resulting library dependency is
+    "absolute", i.e impossible to change by setting ${shlibpath_var} if the
+    library is relocated])
+_LT_TAGDECL([], [hardcode_minus_L], [0],
+    [Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_shlibpath_var], [0],
+    [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR
+    into the resulting binary])
+_LT_TAGDECL([], [hardcode_automatic], [0],
+    [Set to "yes" if building a shared library automatically hardcodes DIR
+    into the library and all subsequent libraries and executables linked
+    against it])
+_LT_TAGDECL([], [inherit_rpath], [0],
+    [Set to yes if linker adds runtime paths of dependent libraries
+    to runtime path list])
+_LT_TAGDECL([], [link_all_deplibs], [0],
+    [Whether libtool must link a program against all its dependency libraries])
+_LT_TAGDECL([], [fix_srcfile_path], [1],
+    [Fix the shell variable $srcfile for the compiler])
+_LT_TAGDECL([], [always_export_symbols], [0],
+    [Set to "yes" if exported symbols are required])
+_LT_TAGDECL([], [export_symbols_cmds], [2],
+    [The commands to list exported symbols])
+_LT_TAGDECL([], [exclude_expsyms], [1],
+    [Symbols that should not be listed in the preloaded symbols])
+_LT_TAGDECL([], [include_expsyms], [1],
+    [Symbols that must always be exported])
+_LT_TAGDECL([], [prelink_cmds], [2],
+    [Commands necessary for linking programs (against libraries) with templates])
+_LT_TAGDECL([], [file_list_spec], [1],
+    [Specify filename containing input files])
+dnl FIXME: Not yet implemented
+dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1],
+dnl    [Compiler flag to generate thread safe objects])
+])# _LT_LINKER_SHLIBS
+
+
+# _LT_LANG_C_CONFIG([TAG])
+# ------------------------
+# Ensure that the configuration variables for a C compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_C_CONFIG],
+[m4_require([_LT_DECL_EGREP])dnl
+lt_save_CC="$CC"
+AC_LANG_PUSH(C)
+
+# Source file extension for C test sources.
+ac_ext=c
+
+# Object file extension for compiled C test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="int some_variable = 0;"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='int main(){return(0);}'
+
+_LT_TAG_COMPILER
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=$CC
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_SYS_DYNAMIC_LINKER($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+  LT_SYS_DLOPEN_SELF
+  _LT_CMD_STRIPLIB
+
+  # Report which library types will actually be built
+  AC_MSG_CHECKING([if libtool supports shared libraries])
+  AC_MSG_RESULT([$can_build_shared])
+
+  AC_MSG_CHECKING([whether to build shared libraries])
+  test "$can_build_shared" = "no" && enable_shared=no
+
+  # On AIX, shared libraries and static libraries use the same namespace, and
+  # are all built from PIC.
+  case $host_os in
+  aix3*)
+    test "$enable_shared" = yes && enable_static=no
+    if test -n "$RANLIB"; then
+      archive_cmds="$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds='$RANLIB $lib'
+    fi
+    ;;
+
+  aix[[4-9]]*)
+    if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+      test "$enable_shared" = yes && enable_static=no
+    fi
+    ;;
+  esac
+  AC_MSG_RESULT([$enable_shared])
+
+  AC_MSG_CHECKING([whether to build static libraries])
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" = yes || enable_static=yes
+  AC_MSG_RESULT([$enable_static])
+
+  _LT_CONFIG($1)
+fi
+AC_LANG_POP
+CC="$lt_save_CC"
+])# _LT_LANG_C_CONFIG
+
+
+# _LT_PROG_CXX
+# ------------
+# Since AC_PROG_CXX is broken, in that it returns g++ if there is no c++
+# compiler, we have our own version here.
+m4_defun([_LT_PROG_CXX],
+[
+pushdef([AC_MSG_ERROR], [_lt_caught_CXX_error=yes])
+AC_PROG_CXX
+if test -n "$CXX" && ( test "X$CXX" != "Xno" &&
+    ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
+    (test "X$CXX" != "Xg++"))) ; then
+  AC_PROG_CXXCPP
+else
+  _lt_caught_CXX_error=yes
+fi
+popdef([AC_MSG_ERROR])
+])# _LT_PROG_CXX
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([_LT_PROG_CXX], [])
+
+
+# _LT_LANG_CXX_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a C++ compiler are suitably
+# defined.  These variables are subsequently used by _LT_CONFIG to write
+# the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_CXX_CONFIG],
+[AC_REQUIRE([_LT_PROG_CXX])dnl
+m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+m4_require([_LT_DECL_EGREP])dnl
+
+AC_LANG_PUSH(C++)
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(compiler_needs_object, $1)=no
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for C++ test sources.
+ac_ext=cpp
+
+# Object file extension for compiled C++ test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the CXX compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_caught_CXX_error" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="int some_variable = 0;"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }'
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC=$CC
+  lt_save_LD=$LD
+  lt_save_GCC=$GCC
+  GCC=$GXX
+  lt_save_with_gnu_ld=$with_gnu_ld
+  lt_save_path_LD=$lt_cv_path_LD
+  if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
+    lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx
+  else
+    $as_unset lt_cv_prog_gnu_ld
+  fi
+  if test -n "${lt_cv_path_LDCXX+set}"; then
+    lt_cv_path_LD=$lt_cv_path_LDCXX
+  else
+    $as_unset lt_cv_path_LD
+  fi
+  test -z "${LDCXX+set}" || LD=$LDCXX
+  CC=${CXX-"c++"}
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    # We don't want -fno-exception when compiling C++ code, so set the
+    # no_builtin_flag separately
+    if test "$GXX" = yes; then
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin'
+    else
+      _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=
+    fi
+
+    if test "$GXX" = yes; then
+      # Set up default GNU C++ configuration
+
+      LT_PATH_LD
+
+      # Check if GNU C++ uses GNU ld as the underlying linker, since the
+      # archiving commands below assume that GNU ld is being used.
+      if test "$with_gnu_ld" = yes; then
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+        _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+        # If archive_cmds runs LD, not CC, wlarc should be empty
+        # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
+        #     investigate it a little bit more. (MM)
+        wlarc='${wl}'
+
+        # ancient GNU ld didn't support --whole-archive et. al.
+        if eval "`$CC -print-prog-name=ld` --help 2>&1" |
+         $GREP 'no-whole-archive' > /dev/null; then
+          _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+        else
+          _LT_TAGVAR(whole_archive_flag_spec, $1)=
+        fi
+      else
+        with_gnu_ld=no
+        wlarc=
+
+        # A generic and very simple default shared library creation
+        # command for GNU C++ for the case where it uses the native
+        # linker, instead of GNU ld.  If possible, this setting should
+        # overridden to take advantage of the native linker features on
+        # the platform it is being used on.
+        _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+      fi
+
+      # Commands to make compiler produce verbose output that lists
+      # what "hidden" libraries, object files and flags are used when
+      # linking a shared library.
+      output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+
+    else
+      GXX=no
+      with_gnu_ld=no
+      wlarc=
+    fi
+
+    # PORTME: fill in a description of your system's C++ link characteristics
+    AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries])
+    _LT_TAGVAR(ld_shlibs, $1)=yes
+    case $host_os in
+      aix3*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+      aix[[4-9]]*)
+        if test "$host_cpu" = ia64; then
+          # On IA64, the linker does run time linking by default, so we don't
+          # have to do anything special.
+          aix_use_runtimelinking=no
+          exp_sym_flag='-Bexport'
+          no_entry_flag=""
+        else
+          aix_use_runtimelinking=no
+
+          # Test if we are trying to use run time linking or normal
+          # AIX style linking. If -brtl is somewhere in LDFLAGS, we
+          # need to do runtime linking.
+          case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*)
+           for ld_flag in $LDFLAGS; do
+             case $ld_flag in
+             *-brtl*)
+               aix_use_runtimelinking=yes
+               break
+               ;;
+             esac
+           done
+           ;;
+          esac
+
+          exp_sym_flag='-bexport'
+          no_entry_flag='-bnoentry'
+        fi
+
+        # When large executables or shared objects are built, AIX ld can
+        # have problems creating the table of contents.  If linking a library
+        # or program results in "error TOC overflow" add -mminimal-toc to
+        # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
+        # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
+
+        _LT_TAGVAR(archive_cmds, $1)=''
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+        _LT_TAGVAR(link_all_deplibs, $1)=yes
+        _LT_TAGVAR(file_list_spec, $1)='${wl}-f,'
+
+        if test "$GXX" = yes; then
+          case $host_os in aix4.[[012]]|aix4.[[012]].*)
+          # We only want to do this on AIX 4.2 and lower, the check
+          # below for broken collect2 doesn't work under 4.3+
+         collect2name=`${CC} -print-prog-name=collect2`
+         if test -f "$collect2name" &&
+            strings "$collect2name" | $GREP resolve_lib_name >/dev/null
+         then
+           # We have reworked collect2
+           :
+         else
+           # We have old collect2
+           _LT_TAGVAR(hardcode_direct, $1)=unsupported
+           # It fails to find uninstalled libraries when the uninstalled
+           # path is not listed in the libpath.  Setting hardcode_minus_L
+           # to unsupported forces relinking
+           _LT_TAGVAR(hardcode_minus_L, $1)=yes
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+           _LT_TAGVAR(hardcode_libdir_separator, $1)=
+         fi
+          esac
+          shared_flag='-shared'
+         if test "$aix_use_runtimelinking" = yes; then
+           shared_flag="$shared_flag "'${wl}-G'
+         fi
+        else
+          # not using gcc
+          if test "$host_cpu" = ia64; then
+         # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+         # chokes on -Wl,-G. The following line is correct:
+         shared_flag='-G'
+          else
+           if test "$aix_use_runtimelinking" = yes; then
+             shared_flag='${wl}-G'
+           else
+             shared_flag='${wl}-bM:SRE'
+           fi
+          fi
+        fi
+
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall'
+        # It seems that -bexpall does not export symbols beginning with
+        # underscore (_), so it is better to generate a list of symbols to
+       # export.
+        _LT_TAGVAR(always_export_symbols, $1)=yes
+        if test "$aix_use_runtimelinking" = yes; then
+          # Warning - without using the other runtime loading flags (-brtl),
+          # -berok will link without error, but may produce a broken library.
+          _LT_TAGVAR(allow_undefined_flag, $1)='-berok'
+          # Determine the default libpath from the value encoded in an empty
+          # executable.
+          _LT_SYS_MODULE_PATH_AIX
+          _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+
+          _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+        else
+          if test "$host_cpu" = ia64; then
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib'
+           _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs"
+           _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
+          else
+           # Determine the default libpath from the value encoded in an
+           # empty executable.
+           _LT_SYS_MODULE_PATH_AIX
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath"
+           # Warning - without using the other run time loading flags,
+           # -berok will link without error, but may produce a broken library.
+           _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok'
+           _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok'
+           # Exported symbols can be pulled into shared objects from archives
+           _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience'
+           _LT_TAGVAR(archive_cmds_need_lc, $1)=yes
+           # This is similar to how AIX traditionally builds its shared
+           # libraries.
+           _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname'
+          fi
+        fi
+        ;;
+
+      beos*)
+       if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then
+         _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+         # Joseph Beckenbach <jrb3@best.com> says some releases of gcc
+         # support --undefined.  This deserves some investigation.  FIXME
+         _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+       else
+         _LT_TAGVAR(ld_shlibs, $1)=no
+       fi
+       ;;
+
+      chorus*)
+        case $cc_basename in
+          *)
+         # FIXME: insert proper C++ library support
+         _LT_TAGVAR(ld_shlibs, $1)=no
+         ;;
+        esac
+        ;;
+
+      cygwin* | mingw* | pw32* | cegcc*)
+        # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
+        # as there is no search path for DLLs.
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir'
+        _LT_TAGVAR(allow_undefined_flag, $1)=unsupported
+        _LT_TAGVAR(always_export_symbols, $1)=no
+        _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes
+
+        if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
+          _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+          # If the export-symbols file already is a .def file (1st line
+          # is EXPORTS), use it as is; otherwise, prepend...
+          _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then
+           cp $export_symbols $output_objdir/$soname.def;
+          else
+           echo EXPORTS > $output_objdir/$soname.def;
+           cat $export_symbols >> $output_objdir/$soname.def;
+          fi~
+          $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
+        else
+          _LT_TAGVAR(ld_shlibs, $1)=no
+        fi
+        ;;
+      darwin* | rhapsody*)
+        _LT_DARWIN_LINKER_FEATURES($1)
+       ;;
+
+      dgux*)
+        case $cc_basename in
+          ec++*)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          ghcx*)
+           # Green Hills C++ Compiler
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          *)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+        esac
+        ;;
+
+      freebsd[[12]]*)
+        # C++ shared libraries reported to be fairly broken before
+       # switch to ELF
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      freebsd-elf*)
+        _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+        ;;
+
+      freebsd* | dragonfly*)
+        # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
+        # conventions
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+        ;;
+
+      gnu*)
+        ;;
+
+      hpux9*)
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+        _LT_TAGVAR(hardcode_direct, $1)=yes
+        _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+                                            # but as the default
+                                            # location of the library.
+
+        case $cc_basename in
+          CC*)
+            # FIXME: insert proper C++ library support
+            _LT_TAGVAR(ld_shlibs, $1)=no
+            ;;
+          aCC*)
+            _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            # Commands to make compiler produce verbose output that lists
+            # what "hidden" libraries, object files and flags are used when
+            # linking a shared library.
+            #
+            # There doesn't appear to be a way to prevent this compiler from
+            # explicitly linking system object files so we need to strip them
+            # from the output so that they don't get included in the library
+            # dependencies.
+            output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+            ;;
+          *)
+            if test "$GXX" = yes; then
+              _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib'
+            else
+              # FIXME: insert proper C++ library support
+              _LT_TAGVAR(ld_shlibs, $1)=no
+            fi
+            ;;
+        esac
+        ;;
+
+      hpux10*|hpux11*)
+        if test $with_gnu_ld = no; then
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir'
+         _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+          case $host_cpu in
+            hppa*64*|ia64*)
+              ;;
+            *)
+             _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+              ;;
+          esac
+        fi
+        case $host_cpu in
+          hppa*64*|ia64*)
+            _LT_TAGVAR(hardcode_direct, $1)=no
+            _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+            ;;
+          *)
+            _LT_TAGVAR(hardcode_direct, $1)=yes
+            _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+            _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH,
+                                                # but as the default
+                                                # location of the library.
+            ;;
+        esac
+
+        case $cc_basename in
+          CC*)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          aCC*)
+           case $host_cpu in
+             hppa*64*)
+               _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+               ;;
+             ia64*)
+               _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+               ;;
+             *)
+               _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+               ;;
+           esac
+           # Commands to make compiler produce verbose output that lists
+           # what "hidden" libraries, object files and flags are used when
+           # linking a shared library.
+           #
+           # There doesn't appear to be a way to prevent this compiler from
+           # explicitly linking system object files so we need to strip them
+           # from the output so that they don't get included in the library
+           # dependencies.
+           output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+           ;;
+          *)
+           if test "$GXX" = yes; then
+             if test $with_gnu_ld = no; then
+               case $host_cpu in
+                 hppa*64*)
+                   _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+                   ;;
+                 ia64*)
+                   _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+                   ;;
+                 *)
+                   _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+                   ;;
+               esac
+             fi
+           else
+             # FIXME: insert proper C++ library support
+             _LT_TAGVAR(ld_shlibs, $1)=no
+           fi
+           ;;
+        esac
+        ;;
+
+      interix[[3-9]]*)
+       _LT_TAGVAR(hardcode_direct, $1)=no
+       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+       _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+       # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
+       # Instead, shared libraries are loaded at an image base (0x10000000 by
+       # default) and relocated if they conflict, which is a slow very memory
+       # consuming and fragmenting process.  To avoid this, we pick a random,
+       # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
+       # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
+       _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+       _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
+       ;;
+      irix5* | irix6*)
+        case $cc_basename in
+          CC*)
+           # SGI C++
+           _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+
+           # Archives containing C++ object files must be created using
+           # "CC -ar", where "CC" is the IRIX C++ compiler.  This is
+           # necessary to make sure instantiated templates are included
+           # in the archive.
+           _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs'
+           ;;
+          *)
+           if test "$GXX" = yes; then
+             if test "$with_gnu_ld" = no; then
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+             else
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` -o $lib'
+             fi
+           fi
+           _LT_TAGVAR(link_all_deplibs, $1)=yes
+           ;;
+        esac
+        _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+        _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+        _LT_TAGVAR(inherit_rpath, $1)=yes
+        ;;
+
+      linux* | k*bsd*-gnu | kopensolaris*-gnu)
+        case $cc_basename in
+          KCC*)
+           # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+           # KCC will only create a shared library if the output file
+           # ends with ".so" (or ".sl" for HP-UX), so rename the library
+           # to its proper name (with version) after linking.
+           _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+           _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib'
+           # Commands to make compiler produce verbose output that lists
+           # what "hidden" libraries, object files and flags are used when
+           # linking a shared library.
+           #
+           # There doesn't appear to be a way to prevent this compiler from
+           # explicitly linking system object files so we need to strip them
+           # from the output so that they don't get included in the library
+           # dependencies.
+           output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+           _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+
+           # Archives containing C++ object files must be created using
+           # "CC -Bstatic", where "CC" is the KAI C++ compiler.
+           _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs'
+           ;;
+         icpc* | ecpc* )
+           # Intel C++
+           with_gnu_ld=yes
+           # version 8.0 and above of icpc choke on multiply defined symbols
+           # if we add $predep_objects and $postdep_objects, however 7.1 and
+           # earlier do not add the objects themselves.
+           case `$CC -V 2>&1` in
+             *"Version 7."*)
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+               _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+               ;;
+             *)  # Version 8.0 or newer
+               tmp_idyn=
+               case $host_cpu in
+                 ia64*) tmp_idyn=' -i_dynamic';;
+               esac
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+               _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+               ;;
+           esac
+           _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+           _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+           _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive'
+           ;;
+          pgCC* | pgcpp*)
+            # Portland Group C++ compiler
+           case `$CC -V` in
+           *pgCC\ [[1-5]]* | *pgcpp\ [[1-5]]*)
+             _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~
+               rm -rf $tpldir~
+               $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~
+               compile_command="$compile_command `find $tpldir -name \*.o | $NL2SP`"'
+             _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~
+               rm -rf $tpldir~
+               $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~
+               $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | $NL2SP`~
+               $RANLIB $oldlib'
+             _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~
+               rm -rf $tpldir~
+               $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+               $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+             _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~
+               rm -rf $tpldir~
+               $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~
+               $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+             ;;
+           *) # Version 6 will use weak symbols
+             _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
+             _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
+             ;;
+           esac
+
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir'
+           _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+           _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+            ;;
+         cxx*)
+           # Compaq C++
+           _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
+           _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-retain-symbols-file $wl$export_symbols'
+
+           runpath_var=LD_RUN_PATH
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+           _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+           # Commands to make compiler produce verbose output that lists
+           # what "hidden" libraries, object files and flags are used when
+           # linking a shared library.
+           #
+           # There doesn't appear to be a way to prevent this compiler from
+           # explicitly linking system object files so we need to strip them
+           # from the output so that they don't get included in the library
+           # dependencies.
+           output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+           ;;
+         xl*)
+           # IBM XL 8.0 on PPC, with GNU ld
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+           _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic'
+           _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
+           if test "x$supports_anon_versioning" = xyes; then
+             _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~
+               cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~
+               echo "local: *; };" >> $output_objdir/$libname.ver~
+               $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib'
+           fi
+           ;;
+         *)
+           case `$CC -V 2>&1 | sed 5q` in
+           *Sun\ C*)
+             # Sun C++ 5.9
+             _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+             _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+             _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols'
+             _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+             _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive'
+             _LT_TAGVAR(compiler_needs_object, $1)=yes
+
+             # Not sure whether something based on
+             # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1
+             # would be better.
+             output_verbose_link_cmd='echo'
+
+             # Archives containing C++ object files must be created using
+             # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+             # necessary to make sure instantiated templates are included
+             # in the archive.
+             _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+             ;;
+           esac
+           ;;
+       esac
+       ;;
+
+      lynxos*)
+        # FIXME: insert proper C++ library support
+       _LT_TAGVAR(ld_shlibs, $1)=no
+       ;;
+
+      m88k*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+       ;;
+
+      mvs*)
+        case $cc_basename in
+          cxx*)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+         *)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+       esac
+       ;;
+
+      netbsd*)
+        if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
+         _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable  -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags'
+         wlarc=
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+         _LT_TAGVAR(hardcode_direct, $1)=yes
+         _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+       fi
+       # Workaround some broken pre-1.5 toolchains
+       output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
+       ;;
+
+      *nto* | *qnx*)
+        _LT_TAGVAR(ld_shlibs, $1)=yes
+       ;;
+
+      openbsd2*)
+        # C++ shared libraries are fairly broken
+       _LT_TAGVAR(ld_shlibs, $1)=no
+       ;;
+
+      openbsd*)
+       if test -f /usr/libexec/ld.so; then
+         _LT_TAGVAR(hardcode_direct, $1)=yes
+         _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+         _LT_TAGVAR(hardcode_direct_absolute, $1)=yes
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
+         _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+         if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then
+           _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib'
+           _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E'
+           _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive'
+         fi
+         output_verbose_link_cmd=echo
+       else
+         _LT_TAGVAR(ld_shlibs, $1)=no
+       fi
+       ;;
+
+      osf3* | osf4* | osf5*)
+        case $cc_basename in
+          KCC*)
+           # Kuck and Associates, Inc. (KAI) C++ Compiler
+
+           # KCC will only create a shared library if the output file
+           # ends with ".so" (or ".sl" for HP-UX), so rename the library
+           # to its proper name (with version) after linking.
+           _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
+
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir'
+           _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+           # Archives containing C++ object files must be created using
+           # the KAI C++ compiler.
+           case $host in
+             osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;;
+             *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;;
+           esac
+           ;;
+          RCC*)
+           # Rational C++ 2.4.1
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          cxx*)
+           case $host in
+             osf3*)
+               _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && $ECHO "X${wl}-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+               _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+               ;;
+             *)
+               _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*'
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib'
+               _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
+                 echo "-hidden">> $lib.exp~
+                 $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp  `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~
+                 $RM $lib.exp'
+               _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir'
+               ;;
+           esac
+
+           _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+           # Commands to make compiler produce verbose output that lists
+           # what "hidden" libraries, object files and flags are used when
+           # linking a shared library.
+           #
+           # There doesn't appear to be a way to prevent this compiler from
+           # explicitly linking system object files so we need to strip them
+           # from the output so that they don't get included in the library
+           # dependencies.
+           output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed'
+           ;;
+         *)
+           if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+             _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*'
+             case $host in
+               osf3*)
+                 _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+                 ;;
+               *)
+                 _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
+                 ;;
+             esac
+
+             _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir'
+             _LT_TAGVAR(hardcode_libdir_separator, $1)=:
+
+             # Commands to make compiler produce verbose output that lists
+             # what "hidden" libraries, object files and flags are used when
+             # linking a shared library.
+             output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+
+           else
+             # FIXME: insert proper C++ library support
+             _LT_TAGVAR(ld_shlibs, $1)=no
+           fi
+           ;;
+        esac
+        ;;
+
+      psos*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      sunos4*)
+        case $cc_basename in
+          CC*)
+           # Sun C++ 4.x
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          lcc*)
+           # Lucid
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          *)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+        esac
+        ;;
+
+      solaris*)
+        case $cc_basename in
+          CC*)
+           # Sun C++ 4.2, 5.x and Centerline C++
+            _LT_TAGVAR(archive_cmds_need_lc,$1)=yes
+           _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs'
+           _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag}  -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
+           _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+             $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+           _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir'
+           _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+           case $host_os in
+             solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+             *)
+               # The compiler driver will combine and reorder linker options,
+               # but understands `-z linker_flag'.
+               # Supported since Solaris 2.6 (maybe 2.5.1?)
+               _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract'
+               ;;
+           esac
+           _LT_TAGVAR(link_all_deplibs, $1)=yes
+
+           output_verbose_link_cmd='echo'
+
+           # Archives containing C++ object files must be created using
+           # "CC -xar", where "CC" is the Sun C++ compiler.  This is
+           # necessary to make sure instantiated templates are included
+           # in the archive.
+           _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs'
+           ;;
+          gcx*)
+           # Green Hills C++ Compiler
+           _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+
+           # The C++ compiler must be used to create the archive.
+           _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs'
+           ;;
+          *)
+           # GNU C++ compiler with Solaris linker
+           if test "$GXX" = yes && test "$with_gnu_ld" = no; then
+             _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs'
+             if $CC --version | $GREP -v '^2\.7' > /dev/null; then
+               _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+               _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+                 $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+               # Commands to make compiler produce verbose output that lists
+               # what "hidden" libraries, object files and flags are used when
+               # linking a shared library.
+               output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+             else
+               # g++ 2.7 appears to require `-G' NOT `-shared' on this
+               # platform.
+               _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
+               _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+                 $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp'
+
+               # Commands to make compiler produce verbose output that lists
+               # what "hidden" libraries, object files and flags are used when
+               # linking a shared library.
+               output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"'
+             fi
+
+             _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir'
+             case $host_os in
+               solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
+               *)
+                 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract'
+                 ;;
+             esac
+           fi
+           ;;
+        esac
+        ;;
+
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*)
+      _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+      _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+      _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+      runpath_var='LD_RUN_PATH'
+
+      case $cc_basename in
+        CC*)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+         _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+       *)
+         _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+         _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+         ;;
+      esac
+      ;;
+
+      sysv5* | sco3.2v5* | sco5v6*)
+       # Note: We can NOT use -z defs as we might desire, because we do not
+       # link with -lc, and that would cause any symbols used from libc to
+       # always be unresolved, which means just about no library would
+       # ever link correctly.  If we're not using GNU ld we use -z text
+       # though, which does catch some bad symbols but isn't as heavy-handed
+       # as -z defs.
+       _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text'
+       _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs'
+       _LT_TAGVAR(archive_cmds_need_lc, $1)=no
+       _LT_TAGVAR(hardcode_shlibpath_var, $1)=no
+       _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir'
+       _LT_TAGVAR(hardcode_libdir_separator, $1)=':'
+       _LT_TAGVAR(link_all_deplibs, $1)=yes
+       _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport'
+       runpath_var='LD_RUN_PATH'
+
+       case $cc_basename in
+          CC*)
+           _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+           _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+           ;;
+         *)
+           _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+           _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
+           ;;
+       esac
+      ;;
+
+      tandem*)
+        case $cc_basename in
+          NCC*)
+           # NonStop-UX NCC 3.20
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+          *)
+           # FIXME: insert proper C++ library support
+           _LT_TAGVAR(ld_shlibs, $1)=no
+           ;;
+        esac
+        ;;
+
+      vxworks*)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+
+      *)
+        # FIXME: insert proper C++ library support
+        _LT_TAGVAR(ld_shlibs, $1)=no
+        ;;
+    esac
+
+    AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)])
+    test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no
+
+    _LT_TAGVAR(GCC, $1)="$GXX"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  CC=$lt_save_CC
+  LDCXX=$LD
+  LD=$lt_save_LD
+  GCC=$lt_save_GCC
+  with_gnu_ld=$lt_save_with_gnu_ld
+  lt_cv_path_LDCXX=$lt_cv_path_LD
+  lt_cv_path_LD=$lt_save_path_LD
+  lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld
+  lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld
+fi # test "$_lt_caught_CXX_error" != yes
+
+AC_LANG_POP
+])# _LT_LANG_CXX_CONFIG
+
+
+# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME])
+# ---------------------------------
+# Figure out "hidden" library dependencies from verbose
+# compiler output when linking a shared library.
+# Parse the compiler output and extract the necessary
+# objects, libraries and library flags.
+m4_defun([_LT_SYS_HIDDEN_LIBDEPS],
+[m4_require([_LT_FILEUTILS_DEFAULTS])dnl
+# Dependencies to place before and after the object being linked:
+_LT_TAGVAR(predep_objects, $1)=
+_LT_TAGVAR(postdep_objects, $1)=
+_LT_TAGVAR(predeps, $1)=
+_LT_TAGVAR(postdeps, $1)=
+_LT_TAGVAR(compiler_lib_search_path, $1)=
+
+dnl we can't use the lt_simple_compile_test_code here,
+dnl because it contains code intended for an executable,
+dnl not a library.  It's possible we should let each
+dnl tag define a new lt_????_link_test_code variable,
+dnl but it's only used here...
+m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF
+int a;
+void foo (void) { a = 0; }
+_LT_EOF
+], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF
+class Foo
+{
+public:
+  Foo (void) { a = 0; }
+private:
+  int a;
+};
+_LT_EOF
+], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer*4 a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF
+      subroutine foo
+      implicit none
+      integer a
+      a=0
+      return
+      end
+_LT_EOF
+], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF
+public class foo {
+  private int a;
+  public void bar (void) {
+    a = 0;
+  }
+};
+_LT_EOF
+])
+dnl Parse the compiler output and extract the necessary
+dnl objects, libraries and library flags.
+if AC_TRY_EVAL(ac_compile); then
+  # Parse the compiler output and extract the necessary
+  # objects, libraries and library flags.
+
+  # Sentinel used to keep track of whether or not we are before
+  # the conftest object file.
+  pre_test_object_deps_done=no
+
+  for p in `eval "$output_verbose_link_cmd"`; do
+    case $p in
+
+    -L* | -R* | -l*)
+       # Some compilers place space between "-{L,R}" and the path.
+       # Remove the space.
+       if test $p = "-L" ||
+          test $p = "-R"; then
+        prev=$p
+        continue
+       else
+        prev=
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+        case $p in
+        -L* | -R*)
+          # Internal compiler library paths should come after those
+          # provided the user.  The postdeps already come after the
+          # user supplied libs so there is no need to process them.
+          if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then
+            _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}"
+          else
+            _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}"
+          fi
+          ;;
+        # The "-l" case would never come before the object being
+        # linked, so don't bother handling this case.
+        esac
+       else
+        if test -z "$_LT_TAGVAR(postdeps, $1)"; then
+          _LT_TAGVAR(postdeps, $1)="${prev}${p}"
+        else
+          _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}"
+        fi
+       fi
+       ;;
+
+    *.$objext)
+       # This assumes that the test object file only shows up
+       # once in the compiler output.
+       if test "$p" = "conftest.$objext"; then
+        pre_test_object_deps_done=yes
+        continue
+       fi
+
+       if test "$pre_test_object_deps_done" = no; then
+        if test -z "$_LT_TAGVAR(predep_objects, $1)"; then
+          _LT_TAGVAR(predep_objects, $1)="$p"
+        else
+          _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p"
+        fi
+       else
+        if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then
+          _LT_TAGVAR(postdep_objects, $1)="$p"
+        else
+          _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p"
+        fi
+       fi
+       ;;
+
+    *) ;; # Ignore the rest.
+
+    esac
+  done
+
+  # Clean up.
+  rm -f a.out a.exe
+else
+  echo "libtool.m4: error: problem compiling $1 test program"
+fi
+
+$RM -f confest.$objext
+
+# PORTME: override above test on systems where it is broken
+m4_if([$1], [CXX],
+[case $host_os in
+interix[[3-9]]*)
+  # Interix 3.5 installs completely hosed .la files for C++, so rather than
+  # hack all around it, let's just trust "g++" to DTRT.
+  _LT_TAGVAR(predep_objects,$1)=
+  _LT_TAGVAR(postdep_objects,$1)=
+  _LT_TAGVAR(postdeps,$1)=
+  ;;
+
+linux*)
+  case `$CC -V 2>&1 | sed 5q` in
+  *Sun\ C*)
+    # Sun C++ 5.9
+
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+
+solaris*)
+  case $cc_basename in
+  CC*)
+    # The more standards-conforming stlport4 library is
+    # incompatible with the Cstd library. Avoid specifying
+    # it if it's in CXXFLAGS. Ignore libCrun as
+    # -library=stlport4 depends on it.
+    case " $CXX $CXXFLAGS " in
+    *" -library=stlport4 "*)
+      solaris_use_stlport4=yes
+      ;;
+    esac
+
+    # Adding this requires a known-good setup of shared libraries for
+    # Sun compiler versions before 5.6, else PIC objects from an old
+    # archive will be linked into the output, leading to subtle bugs.
+    if test "$solaris_use_stlport4" != yes; then
+      _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun'
+    fi
+    ;;
+  esac
+  ;;
+esac
+])
+
+case " $_LT_TAGVAR(postdeps, $1) " in
+*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;;
+esac
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=
+if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then
+ _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'`
+fi
+_LT_TAGDECL([], [compiler_lib_search_dirs], [1],
+    [The directories searched by this compiler when creating a shared library])
+_LT_TAGDECL([], [predep_objects], [1],
+    [Dependencies to place before and after the objects being linked to
+    create a shared library])
+_LT_TAGDECL([], [postdep_objects], [1])
+_LT_TAGDECL([], [predeps], [1])
+_LT_TAGDECL([], [postdeps], [1])
+_LT_TAGDECL([], [compiler_lib_search_path], [1],
+    [The library search path used internally by the compiler when linking
+    a shared library])
+])# _LT_SYS_HIDDEN_LIBDEPS
+
+
+# _LT_PROG_F77
+# ------------
+# Since AC_PROG_F77 is broken, in that it returns the empty string
+# if there is no fortran compiler, we have our own version here.
+m4_defun([_LT_PROG_F77],
+[
+pushdef([AC_MSG_ERROR], [_lt_disable_F77=yes])
+AC_PROG_F77
+if test -z "$F77" || test "X$F77" = "Xno"; then
+  _lt_disable_F77=yes
+fi
+popdef([AC_MSG_ERROR])
+])# _LT_PROG_F77
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([_LT_PROG_F77], [])
+
+
+# _LT_LANG_F77_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for a Fortran 77 compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_F77_CONFIG],
+[AC_REQUIRE([_LT_PROG_F77])dnl
+AC_LANG_PUSH(Fortran 77)
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for f77 test sources.
+ac_ext=f
+
+# Object file extension for compiled f77 test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the F77 compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_F77" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  CC=${F77-"f77"}
+  compiler=$CC
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+  GCC=$G77
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+       if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+         test "$enable_shared" = yes && enable_static=no
+       fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$G77"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+fi # test "$_lt_disable_F77" != yes
+
+AC_LANG_POP
+])# _LT_LANG_F77_CONFIG
+
+
+# _LT_PROG_FC
+# -----------
+# Since AC_PROG_FC is broken, in that it returns the empty string
+# if there is no fortran compiler, we have our own version here.
+m4_defun([_LT_PROG_FC],
+[
+pushdef([AC_MSG_ERROR], [_lt_disable_FC=yes])
+AC_PROG_FC
+if test -z "$FC" || test "X$FC" = "Xno"; then
+  _lt_disable_FC=yes
+fi
+popdef([AC_MSG_ERROR])
+])# _LT_PROG_FC
+
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([_LT_PROG_FC], [])
+
+
+# _LT_LANG_FC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for a Fortran compiler are
+# suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_FC_CONFIG],
+[AC_REQUIRE([_LT_PROG_FC])dnl
+AC_LANG_PUSH(Fortran)
+
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+_LT_TAGVAR(allow_undefined_flag, $1)=
+_LT_TAGVAR(always_export_symbols, $1)=no
+_LT_TAGVAR(archive_expsym_cmds, $1)=
+_LT_TAGVAR(export_dynamic_flag_spec, $1)=
+_LT_TAGVAR(hardcode_direct, $1)=no
+_LT_TAGVAR(hardcode_direct_absolute, $1)=no
+_LT_TAGVAR(hardcode_libdir_flag_spec, $1)=
+_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=
+_LT_TAGVAR(hardcode_libdir_separator, $1)=
+_LT_TAGVAR(hardcode_minus_L, $1)=no
+_LT_TAGVAR(hardcode_automatic, $1)=no
+_LT_TAGVAR(inherit_rpath, $1)=no
+_LT_TAGVAR(module_cmds, $1)=
+_LT_TAGVAR(module_expsym_cmds, $1)=
+_LT_TAGVAR(link_all_deplibs, $1)=unknown
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+_LT_TAGVAR(no_undefined_flag, $1)=
+_LT_TAGVAR(whole_archive_flag_spec, $1)=
+_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no
+
+# Source file extension for fc test sources.
+ac_ext=${ac_fc_srcext-f}
+
+# Object file extension for compiled fc test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# No sense in running all these tests if we already determined that
+# the FC compiler isn't working.  Some variables (like enable_shared)
+# are currently assumed to apply to all compilers on this platform,
+# and will be corrupted by setting them based on a non-working compiler.
+if test "$_lt_disable_FC" != yes; then
+  # Code to be used in simple compile tests
+  lt_simple_compile_test_code="\
+      subroutine t
+      return
+      end
+"
+
+  # Code to be used in simple link tests
+  lt_simple_link_test_code="\
+      program t
+      end
+"
+
+  # ltmain only uses $CC for tagged configurations so make sure $CC is set.
+  _LT_TAG_COMPILER
+
+  # save warnings/boilerplate of simple test code
+  _LT_COMPILER_BOILERPLATE
+  _LT_LINKER_BOILERPLATE
+
+  # Allow CC to be a program name with arguments.
+  lt_save_CC="$CC"
+  lt_save_GCC=$GCC
+  CC=${FC-"f95"}
+  compiler=$CC
+  GCC=$ac_cv_fc_compiler_gnu
+
+  _LT_TAGVAR(compiler, $1)=$CC
+  _LT_CC_BASENAME([$compiler])
+
+  if test -n "$compiler"; then
+    AC_MSG_CHECKING([if libtool supports shared libraries])
+    AC_MSG_RESULT([$can_build_shared])
+
+    AC_MSG_CHECKING([whether to build shared libraries])
+    test "$can_build_shared" = "no" && enable_shared=no
+
+    # On AIX, shared libraries and static libraries use the same namespace, and
+    # are all built from PIC.
+    case $host_os in
+      aix3*)
+        test "$enable_shared" = yes && enable_static=no
+        if test -n "$RANLIB"; then
+          archive_cmds="$archive_cmds~\$RANLIB \$lib"
+          postinstall_cmds='$RANLIB $lib'
+        fi
+        ;;
+      aix[[4-9]]*)
+       if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then
+         test "$enable_shared" = yes && enable_static=no
+       fi
+        ;;
+    esac
+    AC_MSG_RESULT([$enable_shared])
+
+    AC_MSG_CHECKING([whether to build static libraries])
+    # Make sure either enable_shared or enable_static is yes.
+    test "$enable_shared" = yes || enable_static=yes
+    AC_MSG_RESULT([$enable_static])
+
+    _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu"
+    _LT_TAGVAR(LD, $1)="$LD"
+
+    ## CAVEAT EMPTOR:
+    ## There is no encapsulation within the following macros, do not change
+    ## the running order or otherwise move them around unless you know exactly
+    ## what you are doing...
+    _LT_SYS_HIDDEN_LIBDEPS($1)
+    _LT_COMPILER_PIC($1)
+    _LT_COMPILER_C_O($1)
+    _LT_COMPILER_FILE_LOCKS($1)
+    _LT_LINKER_SHLIBS($1)
+    _LT_SYS_DYNAMIC_LINKER($1)
+    _LT_LINKER_HARDCODE_LIBPATH($1)
+
+    _LT_CONFIG($1)
+  fi # test -n "$compiler"
+
+  GCC=$lt_save_GCC
+  CC="$lt_save_CC"
+fi # test "$_lt_disable_FC" != yes
+
+AC_LANG_POP
+])# _LT_LANG_FC_CONFIG
+
+
+# _LT_LANG_GCJ_CONFIG([TAG])
+# --------------------------
+# Ensure that the configuration variables for the GNU Java Compiler compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_GCJ_CONFIG],
+[AC_REQUIRE([LT_PROG_GCJ])dnl
+AC_LANG_SAVE
+
+# Source file extension for Java test sources.
+ac_ext=java
+
+# Object file extension for compiled Java test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code="class foo {}"
+
+# Code to be used in simple link tests
+lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }'
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_GCC=$GCC
+GCC=yes
+CC=${GCJ-"gcj"}
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_TAGVAR(LD, $1)="$LD"
+_LT_CC_BASENAME([$compiler])
+
+# GCJ did not exist at the time GCC didn't implicitly link libc in.
+_LT_TAGVAR(archive_cmds_need_lc, $1)=no
+
+_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
+  _LT_COMPILER_NO_RTTI($1)
+  _LT_COMPILER_PIC($1)
+  _LT_COMPILER_C_O($1)
+  _LT_COMPILER_FILE_LOCKS($1)
+  _LT_LINKER_SHLIBS($1)
+  _LT_LINKER_HARDCODE_LIBPATH($1)
+
+  _LT_CONFIG($1)
+fi
+
+AC_LANG_RESTORE
+
+GCC=$lt_save_GCC
+CC="$lt_save_CC"
+])# _LT_LANG_GCJ_CONFIG
+
+
+# _LT_LANG_RC_CONFIG([TAG])
+# -------------------------
+# Ensure that the configuration variables for the Windows resource compiler
+# are suitably defined.  These variables are subsequently used by _LT_CONFIG
+# to write the compiler configuration to `libtool'.
+m4_defun([_LT_LANG_RC_CONFIG],
+[AC_REQUIRE([LT_PROG_RC])dnl
+AC_LANG_SAVE
+
+# Source file extension for RC test sources.
+ac_ext=rc
+
+# Object file extension for compiled RC test sources.
+objext=o
+_LT_TAGVAR(objext, $1)=$objext
+
+# Code to be used in simple compile tests
+lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }'
+
+# Code to be used in simple link tests
+lt_simple_link_test_code="$lt_simple_compile_test_code"
+
+# ltmain only uses $CC for tagged configurations so make sure $CC is set.
+_LT_TAG_COMPILER
+
+# save warnings/boilerplate of simple test code
+_LT_COMPILER_BOILERPLATE
+_LT_LINKER_BOILERPLATE
+
+# Allow CC to be a program name with arguments.
+lt_save_CC="$CC"
+lt_save_GCC=$GCC
+GCC=
+CC=${RC-"windres"}
+compiler=$CC
+_LT_TAGVAR(compiler, $1)=$CC
+_LT_CC_BASENAME([$compiler])
+_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes
+
+if test -n "$compiler"; then
+  :
+  _LT_CONFIG($1)
+fi
+
+GCC=$lt_save_GCC
+AC_LANG_RESTORE
+CC="$lt_save_CC"
+])# _LT_LANG_RC_CONFIG
+
+
+# LT_PROG_GCJ
+# -----------
+AC_DEFUN([LT_PROG_GCJ],
+[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ],
+  [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ],
+    [AC_CHECK_TOOL(GCJ, gcj,)
+      test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2"
+      AC_SUBST(GCJFLAGS)])])[]dnl
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_GCJ], [])
+
+
+# LT_PROG_RC
+# ----------
+AC_DEFUN([LT_PROG_RC],
+[AC_CHECK_TOOL(RC, windres,)
+])
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_RC], [])
+
+
+# _LT_DECL_EGREP
+# --------------
+# If we don't have a new enough Autoconf to choose the best grep
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_EGREP],
+[AC_REQUIRE([AC_PROG_EGREP])dnl
+AC_REQUIRE([AC_PROG_FGREP])dnl
+test -z "$GREP" && GREP=grep
+_LT_DECL([], [GREP], [1], [A grep program that handles long lines])
+_LT_DECL([], [EGREP], [1], [An ERE matcher])
+_LT_DECL([], [FGREP], [1], [A literal string matcher])
+dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too
+AC_SUBST([GREP])
+])
+
+
+# _LT_DECL_OBJDUMP
+# --------------
+# If we don't have a new enough Autoconf to choose the best objdump
+# available, choose the one first in the user's PATH.
+m4_defun([_LT_DECL_OBJDUMP],
+[AC_CHECK_TOOL(OBJDUMP, objdump, false)
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [1], [An object symbol dumper])
+AC_SUBST([OBJDUMP])
+])
+
+
+# _LT_DECL_SED
+# ------------
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible.  Prefer GNU sed if found.
+m4_defun([_LT_DECL_SED],
+[AC_PROG_SED
+test -z "$SED" && SED=sed
+Xsed="$SED -e 1s/^X//"
+_LT_DECL([], [SED], [1], [A sed program that does not truncate output])
+_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"],
+    [Sed that helps us avoid accidentally triggering echo(1) options like -n])
+])# _LT_DECL_SED
+
+m4_ifndef([AC_PROG_SED], [
+############################################################
+# NOTE: This macro has been submitted for inclusion into   #
+#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
+#  a released version of Autoconf we should remove this    #
+#  macro and use it instead.                               #
+############################################################
+
+m4_defun([AC_PROG_SED],
+[AC_MSG_CHECKING([for a sed that does not truncate output])
+AC_CACHE_VAL(lt_cv_path_SED,
+[# Loop through the user's path and test for sed and gsed.
+# Then use that list of sed's as ones to test for truncation.
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for lt_ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
+        lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
+      fi
+    done
+  done
+done
+IFS=$as_save_IFS
+lt_ac_max=0
+lt_ac_count=0
+# Add /usr/xpg4/bin/sed as it is typically found on Solaris
+# along with /bin/sed that truncates output.
+for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
+  test ! -f $lt_ac_sed && continue
+  cat /dev/null > conftest.in
+  lt_ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
+  # Check for GNU sed and select it if it is found.
+  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
+    lt_cv_path_SED=$lt_ac_sed
+    break
+  fi
+  while true; do
+    cat conftest.in conftest.in >conftest.tmp
+    mv conftest.tmp conftest.in
+    cp conftest.in conftest.nl
+    echo >>conftest.nl
+    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
+    cmp -s conftest.out conftest.nl || break
+    # 10000 chars as input seems more than enough
+    test $lt_ac_count -gt 10 && break
+    lt_ac_count=`expr $lt_ac_count + 1`
+    if test $lt_ac_count -gt $lt_ac_max; then
+      lt_ac_max=$lt_ac_count
+      lt_cv_path_SED=$lt_ac_sed
+    fi
+  done
+done
+])
+SED=$lt_cv_path_SED
+AC_SUBST([SED])
+AC_MSG_RESULT([$SED])
+])#AC_PROG_SED
+])#m4_ifndef
+
+# Old name:
+AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED])
+dnl aclocal-1.4 backwards compatibility:
+dnl AC_DEFUN([LT_AC_PROG_SED], [])
+
+
+# _LT_CHECK_SHELL_FEATURES
+# ------------------------
+# Find out whether the shell is Bourne or XSI compatible,
+# or has some other useful features.
+m4_defun([_LT_CHECK_SHELL_FEATURES],
+[AC_MSG_CHECKING([whether the shell understands some XSI constructs])
+# Try some XSI features
+xsi_shell=no
+( _lt_dummy="a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \
+      = c,a/b,, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=yes
+AC_MSG_RESULT([$xsi_shell])
+_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell'])
+
+AC_MSG_CHECKING([whether the shell understands "+="])
+lt_shell_append=no
+( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=yes
+AC_MSG_RESULT([$lt_shell_append])
+_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append'])
+
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=unset
+else
+  lt_unset=false
+fi
+_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL='tr \040 \012'
+  lt_NL2SP='tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL='tr \100 \n'
+  lt_NL2SP='tr \r\n \100\100'
+  ;;
+esac
+_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl
+_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl
+])# _LT_CHECK_SHELL_FEATURES
+
+
+# _LT_PROG_XSI_SHELLFNS
+# ---------------------
+# Bourne and XSI compatible variants of some useful shell functions.
+m4_defun([_LT_PROG_XSI_SHELLFNS],
+[case $xsi_shell in
+  yes)
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+  case ${1} in
+    */*) func_dirname_result="${1%/*}${2}" ;;
+    *  ) func_dirname_result="${3}" ;;
+  esac
+}
+
+# func_basename file
+func_basename ()
+{
+  func_basename_result="${1##*/}"
+}
+
+# func_dirname_and_basename file append nondir_replacement
+# perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# Implementation must be kept synchronized with func_dirname
+# and func_basename. For efficiency, we do not delegate to
+# those functions but instead duplicate the functionality here.
+func_dirname_and_basename ()
+{
+  case ${1} in
+    */*) func_dirname_result="${1%/*}${2}" ;;
+    *  ) func_dirname_result="${3}" ;;
+  esac
+  func_basename_result="${1##*/}"
+}
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+func_stripname ()
+{
+  # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are
+  # positional parameters, so assign one to ordinary parameter first.
+  func_stripname_result=${3}
+  func_stripname_result=${func_stripname_result#"${1}"}
+  func_stripname_result=${func_stripname_result%"${2}"}
+}
+
+# func_opt_split
+func_opt_split ()
+{
+  func_opt_split_opt=${1%%=*}
+  func_opt_split_arg=${1#*=}
+}
+
+# func_lo2o object
+func_lo2o ()
+{
+  case ${1} in
+    *.lo) func_lo2o_result=${1%.lo}.${objext} ;;
+    *)    func_lo2o_result=${1} ;;
+  esac
+}
+
+# func_xform libobj-or-source
+func_xform ()
+{
+  func_xform_result=${1%.*}.lo
+}
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+  func_arith_result=$(( $[*] ))
+}
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+  func_len_result=${#1}
+}
+
+_LT_EOF
+    ;;
+  *) # Bourne compatible functions.
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+  # Extract subdirectory from the argument.
+  func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"`
+  if test "X$func_dirname_result" = "X${1}"; then
+    func_dirname_result="${3}"
+  else
+    func_dirname_result="$func_dirname_result${2}"
+  fi
+}
+
+# func_basename file
+func_basename ()
+{
+  func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"`
+}
+
+dnl func_dirname_and_basename
+dnl A portable version of this function is already defined in general.m4sh
+dnl so there is no need for it here.
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+  case ${2} in
+    .*) func_stripname_result=`$ECHO "X${3}" \
+           | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;;
+    *)  func_stripname_result=`$ECHO "X${3}" \
+           | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;;
+  esac
+}
+
+# sed scripts:
+my_sed_long_opt='1s/^\(-[[^=]]*\)=.*/\1/;q'
+my_sed_long_arg='1s/^-[[^=]]*=//'
+
+# func_opt_split
+func_opt_split ()
+{
+  func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"`
+  func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"`
+}
+
+# func_lo2o object
+func_lo2o ()
+{
+  func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"`
+}
+
+# func_xform libobj-or-source
+func_xform ()
+{
+  func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[[^.]]*$/.lo/'`
+}
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+  func_arith_result=`expr "$[@]"`
+}
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+  func_len_result=`expr "$[1]" : ".*" 2>/dev/null || echo $max_cmd_len`
+}
+
+_LT_EOF
+esac
+
+case $lt_shell_append in
+  yes)
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+  eval "$[1]+=\$[2]"
+}
+_LT_EOF
+    ;;
+  *)
+    cat << \_LT_EOF >> "$cfgfile"
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+  eval "$[1]=\$$[1]\$[2]"
+}
+
+_LT_EOF
+    ;;
+  esac
+])
diff --git a/common/m4/ltoptions.m4 b/common/m4/ltoptions.m4
new file mode 100644 (file)
index 0000000..34151a3
--- /dev/null
@@ -0,0 +1,368 @@
+# Helper functions for option handling.                    -*- Autoconf -*-
+#
+#   Copyright (C) 2004, 2005, 2007, 2008 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 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_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],      [0], [Assembler program])dnl
+
+test -z "$DLLTOOL" && DLLTOOL=dlltool
+_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl
+
+test -z "$OBJDUMP" && OBJDUMP=objdump
+_LT_DECL([], [OBJDUMP], [0], [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_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],
+       [try to use only PIC/non-PIC objects @<:@default=use both@:>@])],
+    [pic_mode="$withval"],
+    [pic_mode=default])
+
+test -z "$pic_mode" && 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])])
diff --git a/common/m4/ltsugar.m4 b/common/m4/ltsugar.m4
new file mode 100644 (file)
index 0000000..9000a05
--- /dev/null
@@ -0,0 +1,123 @@
+# ltsugar.m4 -- libtool m4 base layer.                         -*-Autoconf-*-
+#
+# Copyright (C) 2004, 2005, 2007, 2008 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
+])
diff --git a/common/m4/ltversion.m4 b/common/m4/ltversion.m4
new file mode 100644 (file)
index 0000000..f3c5309
--- /dev/null
@@ -0,0 +1,23 @@
+# ltversion.m4 -- version numbers                      -*- Autoconf -*-
+#
+#   Copyright (C) 2004 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.
+
+# Generated from ltversion.in.
+
+# serial 3017 ltversion.m4
+# This file is part of GNU Libtool
+
+m4_define([LT_PACKAGE_VERSION], [2.2.6b])
+m4_define([LT_PACKAGE_REVISION], [1.3017])
+
+AC_DEFUN([LTVERSION_VERSION],
+[macro_version='2.2.6b'
+macro_revision='1.3017'
+_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?])
+_LT_DECL(, macro_revision, 0)
+])
diff --git a/common/m4/lt~obsolete.m4 b/common/m4/lt~obsolete.m4
new file mode 100644 (file)
index 0000000..637bb20
--- /dev/null
@@ -0,0 +1,92 @@
+# lt~obsolete.m4 -- aclocal satisfying obsolete definitions.    -*-Autoconf-*-
+#
+#   Copyright (C) 2004, 2005, 2007 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 4 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_RC],             [AC_DEFUN([AC_LIBTOOL_RC])])
+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])])
diff --git a/common/m4/pkg.m4 b/common/m4/pkg.m4
new file mode 100755 (executable)
index 0000000..3c20213
--- /dev/null
@@ -0,0 +1,135 @@
+# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
+# 
+# Copyright Â© 2004 Scott James Remnant <scott@netsplit.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 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# 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.
+
+# PKG_PROG_PKG_CONFIG([MIN-VERSION])
+# ----------------------------------
+AC_DEFUN([PKG_PROG_PKG_CONFIG],
+[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
+m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
+AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl
+if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
+       AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
+fi
+if test -n "$PKG_CONFIG"; then
+       _pkg_min_version=m4_ifval([$1], [$1], [0.9.0])
+       AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
+       if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
+               AC_MSG_RESULT([yes])
+       else
+               AC_MSG_RESULT([no])
+               PKG_CONFIG=""
+       fi
+               
+fi[]dnl
+])# PKG_PROG_PKG_CONFIG
+
+# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+#
+# Check to see whether a particular set of modules exists.  Similar
+# to PKG_CHECK_MODULES(), but does not set variables or print errors.
+#
+#
+# Similar to PKG_CHECK_MODULES, make sure that the first instance of
+# this or PKG_CHECK_MODULES is called, or make sure to call
+# PKG_CHECK_EXISTS manually
+# --------------------------------------------------------------
+AC_DEFUN([PKG_CHECK_EXISTS],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+if test -n "$PKG_CONFIG" && \
+    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
+  m4_ifval([$2], [$2], [:])
+m4_ifvaln([$3], [else
+  $3])dnl
+fi])
+
+
+# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
+# ---------------------------------------------
+m4_define([_PKG_CONFIG],
+[if test -n "$PKG_CONFIG"; then
+    if test -n "$$1"; then
+        pkg_cv_[]$1="$$1"
+    else
+        PKG_CHECK_EXISTS([$3],
+                         [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
+                        [pkg_failed=yes])
+    fi
+else
+       pkg_failed=untried
+fi[]dnl
+])# _PKG_CONFIG
+
+# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+# [ACTION-IF-NOT-FOUND])
+#
+#
+# Note that if there is a possibility the first call to
+# PKG_CHECK_MODULES might not happen, you should be sure to include an
+# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
+#
+#
+# --------------------------------------------------------------
+AC_DEFUN([PKG_CHECK_MODULES],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
+AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
+
+pkg_failed=no
+AC_MSG_CHECKING([for $1])
+
+_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
+_PKG_CONFIG([$1][_LIBS], [libs], [$2])
+
+if test $pkg_failed = yes; then
+       $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
+       # Put the nasty error message in config.log where it belongs
+       echo "$$1[]_PKG_ERRORS" 1>&AS_MESSAGE_LOG_FD
+
+       ifelse([$4], , [AC_MSG_ERROR(dnl
+[Package requirements ($2) were not met.
+Consider adjusting the PKG_CONFIG_PATH environment variable if you
+installed software in a non-standard prefix.
+
+Alternatively you may set the $1_CFLAGS and $1_LIBS environment variables
+to avoid the need to call pkg-config.  See the pkg-config man page for
+more details.])],
+               [$4])
+elif test $pkg_failed = untried; then
+       ifelse([$4], , [AC_MSG_FAILURE(dnl
+[The pkg-config script could not be found or is too old.  Make sure it
+is in your PATH or set the PKG_CONFIG environment variable to the full
+path to pkg-config.
+
+Alternatively you may set the $1_CFLAGS and $1_LIBS environment variables
+to avoid the need to call pkg-config.  See the pkg-config man page for
+more details.
+
+To get pkg-config, see <http://www.freedesktop.org/software/pkgconfig>.])],
+               [$4])
+else
+       $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
+       $1[]_LIBS=$pkg_cv_[]$1[]_LIBS
+        AC_MSG_RESULT([yes])
+       ifelse([$3], , :, [$3])
+fi[]dnl
+])# PKG_CHECK_MODULES
diff --git a/common/m4/progtest.m4 b/common/m4/progtest.m4
new file mode 100755 (executable)
index 0000000..443c8e3
--- /dev/null
@@ -0,0 +1,59 @@
+# progtest.m4 serial 2 (gettext-0.10.40)
+dnl Copyright (C) 1996-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License.  As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+dnl
+dnl This file can can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Library General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Library General Public License, and the rest of the GNU
+dnl gettext package package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl   Ulrich Drepper <drepper@cygnus.com>, 1996.
+
+# Search path for a program which passes the given test.
+
+dnl AM_PATH_PROG_WITH_TEST(VARIABLE, PROG-TO-CHECK-FOR,
+dnl   TEST-PERFORMED-ON-FOUND_PROGRAM [, VALUE-IF-NOT-FOUND [, PATH]])
+AC_DEFUN([AM_PATH_PROG_WITH_TEST],
+[# Extract the first word of "$2", so it can be a program name with args.
+set dummy $2; ac_word=[$]2
+AC_MSG_CHECKING([for $ac_word])
+AC_CACHE_VAL(ac_cv_path_$1,
+[case "[$]$1" in
+  /*)
+  ac_cv_path_$1="[$]$1" # Let the user override the test with a path.
+  ;;
+  *)
+  IFS="${IFS=  }"; ac_save_ifs="$IFS"; IFS="${IFS}:"
+  for ac_dir in ifelse([$5], , $PATH, [$5]); do
+    test -z "$ac_dir" && ac_dir=.
+    if test -f $ac_dir/$ac_word; then
+      if [$3]; then
+       ac_cv_path_$1="$ac_dir/$ac_word"
+       break
+      fi
+    fi
+  done
+  IFS="$ac_save_ifs"
+dnl If no 4th arg is given, leave the cache variable unset,
+dnl so AC_PATH_PROGS will keep looking.
+ifelse([$4], , , [  test -z "[$]ac_cv_path_$1" && ac_cv_path_$1="$4"
+])dnl
+  ;;
+esac])dnl
+$1="$ac_cv_path_$1"
+if test ifelse([$4], , [-n "[$]$1"], ["[$]$1" != "$4"]); then
+  AC_MSG_RESULT([$]$1)
+else
+  AC_MSG_RESULT(no)
+fi
+AC_SUBST($1)dnl
+])
diff --git a/common/mangle-tmpl.py b/common/mangle-tmpl.py
new file mode 100755 (executable)
index 0000000..d319040
--- /dev/null
@@ -0,0 +1,155 @@
+# -*- Mode: Python -*-
+# vi:si:et:sw=4:sts=4:ts=4
+
+"""
+use the output from gst-xmlinspect.py to mangle tmpl/*.sgml and
+insert/overwrite Short Description and Long Description
+"""
+
+# FIXME: right now it uses pygst and scans on its own;
+# we really should use inspect/*.xml instead since the result of
+# gst-xmlinspect.py is commited by the docs maintainer, who can be
+# expected to have pygst, but this step should be done for every docs build,
+# so no pygst allowed
+
+# read in inspect/*.xml
+# for every tmpl/element-(name).xml: mangle with details from element
+
+import glob
+import re
+import sys
+import os
+
+class Tmpl:
+    def __init__(self, filename):
+        self.filename = filename
+        self._sectionids = []
+        self._sections = {}
+
+    def read(self):
+        """
+        Read and parse the sections from the given file.
+        """
+        lines = open(self.filename).readlines()
+        matcher = re.compile("<!-- ##### SECTION (\S+) ##### -->\n")
+        id = None
+
+        for line in lines:
+            match = matcher.search(line)
+            if match:
+                id = match.expand("\\1")
+                self._sectionids.append(id)
+                self._sections[id] = []
+            else:
+                if not id:
+                    sys.stderr.write(
+                        "WARNING: line before a SECTION header: %s" % line)
+                else:
+                    self._sections[id].append(line)
+
+    def get_section(self, id):
+        """
+        Get the content from the given section.
+        """
+        return self._sections[id]
+
+    def set_section(self, id, content):
+        """
+        Replace the given section id with the given content.
+        """
+        self._sections[id] = content
+
+    def output(self):
+        """
+        Return the output of the current template in the tmpl/*.sgml format.
+        """
+        lines = []
+        for id in self._sectionids:
+            lines.append("<!-- ##### SECTION %s ##### -->\n" % id)
+            for line in self._sections[id]:
+                lines.append(line)
+
+        return "".join(lines)
+
+    def write(self, backup=False):
+        """
+        Write out the template file again, backing up the previous one.
+        """
+        if backup:
+            target = self.filename + ".mangle.bak"
+            os.rename(self.filename, target)
+
+        handle = open(self.filename, "w")
+        handle.write(self.output())
+        handle.close()
+
+from xml.dom.ext.reader import Sax2
+from xml.dom.NodeFilter import NodeFilter
+
+def get_elements(file):
+    elements = {}
+    handle = open(file)
+    reader = Sax2.Reader()
+    doc = reader.fromStream(handle)
+    handle.close()
+
+    walker = doc.createTreeWalker(doc.documentElement,
+        NodeFilter.SHOW_ELEMENT, None, 0)
+    while walker.currentNode and walker.currentNode.tagName != 'elements':
+        walker.nextNode()
+        
+    # we're at elements now
+    el = walker.firstChild()
+    while walker.currentNode:
+        element = walker.firstChild()
+        # loop over children of <element>
+        name = None
+        description = None
+        while walker.currentNode:
+            if walker.currentNode.tagName == 'name':
+                name = walker.currentNode.firstChild.data.encode('UTF-8')
+            if walker.currentNode.tagName == 'description':
+                description = walker.currentNode.firstChild.data.encode('UTF-8')
+            if not walker.nextSibling(): break
+        # back up to <element>
+        walker.parentNode()
+        elements[name] = {'description': description}
+
+        if not walker.nextSibling(): break
+
+    return elements
+
+        
+def main():
+    if not len(sys.argv) == 3:
+        sys.stderr.write('Please specify the inspect/ dir and the tmpl/ dir')
+        sys.exit(1)
+
+    inspectdir = sys.argv[1]
+    tmpldir = sys.argv[2]
+
+    # parse all .xml files; build map of element name -> short desc
+    #for file in glob.glob("inspect/plugin-*.xml"):
+    elements = {}
+    for file in glob.glob("%s/plugin-*.xml" % inspectdir):
+        elements.update(get_elements(file))
+
+    for file in glob.glob("%s/element-*.sgml" % tmpldir):
+        base = os.path.basename(file)
+        element = base[len("element-"):-len(".sgml")]
+        tmpl = Tmpl(file)
+        tmpl.read()
+        if element in elements.keys():
+            description = elements[element]['description']
+            tmpl.set_section("Short_Description", "%s\n\n" % description)
+
+        # put in an include if not yet there
+        line = '<include xmlns="http://www.w3.org/2003/XInclude" href="' + \
+            'element-' + element + '-details.xml" />\n'
+        section = tmpl.get_section("Long_Description")
+        if not section[0]  == line:
+            section.insert(0, line)
+        tmpl.set_section("Long_Description", section)
+        tmpl.write()
+
+main()
diff --git a/common/plugins.xsl b/common/plugins.xsl
new file mode 100755 (executable)
index 0000000..150087f
--- /dev/null
@@ -0,0 +1,200 @@
+<?xml version='1.0'?> <!--*- mode: xml -*-->
+
+<xsl:stylesheet
+  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+  xmlns:exsl="http://exslt.org/common"
+  extension-element-prefixes="exsl"
+  version="1.0">
+<xsl:output method="xml" indent="yes"
+            doctype-public ="-//OASIS//DTD DocBook XML V4.1.2//EN"
+            doctype-system = "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"/> 
+
+<xsl:param name="module" />
+
+  <xsl:template match="element">
+    <xsl:element name="varlistentry">
+      <xsl:element name="term">
+        <xsl:element name="link">
+          <xsl:attribute name="linkend"><xsl:value-of select="$module" />-plugins-<xsl:value-of select="name"/></xsl:attribute>
+          <xsl:value-of select="name" />
+        </xsl:element>
+      </xsl:element>
+      <xsl:element name="listitem">
+        <xsl:element name="simpara"><xsl:value-of select="description" /></xsl:element>
+      </xsl:element>
+    </xsl:element>
+    <xsl:variable name="name"><xsl:copy-of select="name"/></xsl:variable>
+    <!-- here we write an element-(name)-details.xml file for the element -->
+    <exsl:document href="{concat ('xml/element-', $name, '-details.xml')}" method="xml" indent="yes">
+
+      <xsl:element name="refsect2">
+        <xsl:element name="title">Element Information</xsl:element>
+        <xsl:element name="variablelist">
+        
+          <!-- plugin name and link -->
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">plugin</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara">
+                <xsl:element name="link">
+                  <xsl:attribute name="linkend">plugin-<xsl:value-of select="../../name"/></xsl:attribute>
+                  <xsl:value-of select="../../name" />
+                </xsl:element>
+              </xsl:element>
+            </xsl:element>
+          </xsl:element>
+        
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">author</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara"><xsl:value-of select="author" /></xsl:element>
+            </xsl:element>
+          </xsl:element>
+        
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">class</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara"><xsl:value-of select="class" /></xsl:element>
+            </xsl:element>
+          </xsl:element>
+                      
+        </xsl:element> <!-- variablelist -->
+
+        <xsl:element name="title">Element Pads</xsl:element>
+        <!-- process all caps -->
+        <xsl:for-each select="pads/caps">
+          <xsl:element name="variablelist">
+            <xsl:element name="varlistentry">
+              <xsl:element name="term">name</xsl:element>
+              <xsl:element name="listitem">
+                <xsl:element name="simpara"><xsl:value-of select="name" /></xsl:element>
+              </xsl:element>
+            </xsl:element>
+            
+            <xsl:element name="varlistentry">
+              <xsl:element name="term">direction</xsl:element>
+              <xsl:element name="listitem">
+                <xsl:element name="simpara"><xsl:value-of select="direction" /></xsl:element>
+              </xsl:element>
+            </xsl:element>
+            
+            <xsl:element name="varlistentry">
+              <xsl:element name="term">presence</xsl:element>
+              <xsl:element name="listitem">
+                <xsl:element name="simpara"><xsl:value-of select="presence" /></xsl:element>
+              </xsl:element>
+            </xsl:element>
+            
+            <xsl:element name="varlistentry">
+              <xsl:element name="term">details</xsl:element>
+              <xsl:element name="listitem">
+                <xsl:element name="simpara"><xsl:value-of select="details" /></xsl:element>
+              </xsl:element>
+            </xsl:element>
+
+          </xsl:element> <!-- variablelist -->
+
+          <!--xsl:element name="programlisting"><xsl:value-of select="details" /></xsl:element-->
+
+        </xsl:for-each>
+      </xsl:element>
+
+    </exsl:document>
+  </xsl:template>
+
+  <xsl:template match="plugin">
+    <xsl:element name="refentry">
+      <xsl:attribute name="id"><xsl:value-of select="$module" />-plugins-plugin-<xsl:value-of select="name"/></xsl:attribute>
+
+      <xsl:element name="refmeta">
+        <xsl:element name="refentrytitle">
+          <xsl:value-of select="name"/>
+        </xsl:element>
+        <xsl:element name="manvolnum">3</xsl:element>
+        <xsl:element name="refmiscinfo">FIXME Library</xsl:element>
+      </xsl:element> <!-- refmeta -->
+
+      <xsl:element name="refnamediv">
+        <xsl:element name="refname">
+          <xsl:element name="anchor">
+            <xsl:attribute name="id">plugin-<xsl:value-of select="name"/></xsl:attribute>
+            <xsl:value-of select="name"/>
+          </xsl:element>
+        </xsl:element>
+  
+        <xsl:element name="refpurpose">
+          <xsl:value-of select="description"/>
+        </xsl:element>
+      </xsl:element>
+
+      <xsl:element name="refsect1">
+        <xsl:element name="title">Plugin Information</xsl:element>
+        <xsl:element name="variablelist">
+
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">filename</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara"><xsl:value-of select="basename" /></xsl:element>
+            </xsl:element>
+          </xsl:element>
+
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">version</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara"><xsl:value-of select="version" /></xsl:element>
+            </xsl:element>
+          </xsl:element>
+
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">run-time license</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara"><xsl:value-of select="license" /></xsl:element>
+            </xsl:element>
+          </xsl:element>
+
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">package</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara"><xsl:value-of select="package" /></xsl:element>
+            </xsl:element>
+          </xsl:element>
+
+          <xsl:element name="varlistentry">
+            <xsl:element name="term">origin</xsl:element>
+            <xsl:element name="listitem">
+              <xsl:element name="simpara">
+                <!-- only show origin as link if it starts with http -->
+                <xsl:choose>
+                  <xsl:when test="substring(@href, 1, 4) = 'http'">
+                    <xsl:element name="ulink">
+                      <xsl:attribute name="url"><xsl:value-of select="origin" /></xsl:attribute>
+                      <xsl:value-of select="origin" />
+                    </xsl:element>
+                  </xsl:when>
+                  <xsl:otherwise>
+                    <xsl:value-of select="origin" />
+                  </xsl:otherwise>
+                </xsl:choose>
+              </xsl:element>
+            </xsl:element>
+          </xsl:element>
+
+        </xsl:element>
+      </xsl:element>
+
+      <xsl:element name="refsect1">
+        <xsl:element name="title">Elements</xsl:element>
+        <!-- process all elements -->
+        <xsl:element name="variablelist">
+          <xsl:apply-templates select="elements"/>
+        </xsl:element>
+      </xsl:element>
+
+    </xsl:element>
+
+  </xsl:template>
+
+  <!-- ignore -->
+  <xsl:template match="gst-plugin-paths" />
+
+</xsl:stylesheet>
diff --git a/common/po.mak b/common/po.mak
new file mode 100755 (executable)
index 0000000..e019fac
--- /dev/null
@@ -0,0 +1,4 @@
+# rule to download the latest .po files
+download-po: $(top_srcdir)/common/download-translations
+       $(top_srcdir)/common/download-translations $(PACKAGE)
+
diff --git a/common/release.mak b/common/release.mak
new file mode 100755 (executable)
index 0000000..afb0c8c
--- /dev/null
@@ -0,0 +1,25 @@
+# include this snippet to add a common release: target by using
+# include $(top_srcdir)/common/release.mak
+
+# make bz2 as well
+AUTOMAKE_OPTIONS = dist-bzip2
+
+release: dist
+       $(MAKE) $(PACKAGE)-$(VERSION).tar.gz.md5
+       $(MAKE) $(PACKAGE)-$(VERSION).tar.bz2.md5
+
+# generate md5 sum files
+%.md5: %
+       md5sum $< > $@
+
+# check that no marshal or enumtypes files are included
+# this in turn ensures that distcheck fails for missing .list files which is currently
+# shadowed when the corresponding .c and .h files are included.
+distcheck-hook:
+       @test "x" = "x`find $(distdir) -name \*-enumtypes.[ch] | grep -v win32`" && \
+       test "x" = "x`find $(distdir) -name \*-marshal.[ch]`" || \
+       ( $(ECHO) "*** Leftover enumtypes or marshal files in the tarball." && \
+          $(ECHO) "*** Make sure the following files are not disted:" && \
+          find $(distdir) -name \*-enumtypes.[ch] | grep -v win32 && \
+          find $(distdir) -name \*-marshal.[ch] && \
+          false )
diff --git a/common/scangobj-merge.py b/common/scangobj-merge.py
new file mode 100755 (executable)
index 0000000..4917255
--- /dev/null
@@ -0,0 +1,226 @@
+#!/usr/bin/python
+# -*- Mode: Python -*-
+# vi:si:et:sw=4:sts=4:ts=4
+
+"""
+parse, update and write .signals and .args files
+"""
+
+from twisted.python import util
+
+import sys
+import os
+
+def debug(*args):
+    pass
+
+class Object:
+    def __init__(self, name):
+        self._signals = util.OrderedDict()
+        self._args = util.OrderedDict()
+        self.name = name
+
+    def __repr__(self):
+        return "<Object %s>" % self.name
+
+    def add_signal(self, signal, overwrite=True):
+        if not overwrite and self._signals.has_key(signal.name):
+            raise IndexError, "signal %s already in %r" % (signal.name, self)
+        self._signals[signal.name] = signal
+
+    def add_arg(self, arg, overwrite=True):
+        if not overwrite and self._args.has_key(arg.name):
+            raise IndexError, "arg %s already in %r" % (arg.name, self)
+        self._args[arg.name] = arg
+        
+class Docable:
+    def __init__(self, **kwargs):
+        for key in self.attrs:
+            setattr(self, key, kwargs[key])
+        self.dict = kwargs
+
+    def __repr__(self):
+        return "<%r %s>" % (str(self.__class__), self.name)
+
+class Signal(Docable):
+    attrs = ['name', 'returns', 'args']
+
+class Arg(Docable):
+    attrs = ['name', 'type', 'range', 'flags', 'nick', 'blurb', 'default']
+
+class GDoc:
+    def load_file(self, filename):
+        try:
+            lines = open(filename).readlines()
+            self.load_data("".join(lines))
+        except IOError:
+            print "WARNING - could not read from %s" % filename
+
+    def save_file(self, filename, backup=False):
+        """
+        Save the signals information to the given .signals file if the
+        file content changed.
+        """
+        olddata = None
+        try:
+            lines = open(filename).readlines()
+            olddata = "".join(lines)
+        except IOError:
+            print "WARNING - could not read from %s" % filename
+        newdata = self.get_data()
+        if olddata and olddata == newdata:
+            return
+
+        if olddata:
+            if backup:
+                os.rename(filename, filename + '.bak')
+
+        handle = open(filename, "w")
+        handle.write(newdata)
+        handle.close()
+
+class Signals(GDoc):
+    def __init__(self):
+        self._objects = util.OrderedDict()
+
+    def load_data(self, data):
+        """
+        Load the .signals lines, creating our list of objects and signals.
+        """
+        import re
+        smatcher = re.compile(
+            '(?s)'                                      # make . match \n
+            '<SIGNAL>\n(.*?)</SIGNAL>\n'
+            )
+        nmatcher = re.compile(
+            '<NAME>'
+            '(?P<object>\S*)'                           # store object
+            '::'
+            '(?P<signal>\S*)'                           # store signal
+            '</NAME>'
+        )
+        rmatcher = re.compile(
+            '(?s)'                                      # make . match \n
+            '<RETURNS>(?P<returns>\S*)</RETURNS>\n'     # store returns
+            '(?P<args>.*)'                              # store args
+        )
+        for block in smatcher.findall(data):
+            nmatch = nmatcher.search(block)
+            if nmatch:
+                o = nmatch.group('object')
+                debug("Found object", o)
+                debug("Found signal", nmatch.group('signal'))
+                if not self._objects.has_key(o):
+                    object = Object(o)
+                    self._objects[o] = object
+
+                rmatch = rmatcher.search(block)
+                if rmatch:
+                    dict = rmatch.groupdict().copy()
+                    dict['name'] = nmatch.group('signal')
+                    signal = Signal(**dict)
+                    self._objects[o].add_signal(signal)
+
+    def get_data(self):
+        lines = []
+        for o in self._objects.values():
+            for s in o._signals.values():
+                block = """<SIGNAL>
+<NAME>%(object)s::%(name)s</NAME>
+<RETURNS>%(returns)s</RETURNS>
+%(args)s</SIGNAL>
+"""
+                d = s.dict.copy()
+                d['object'] = o.name
+                lines.append(block % d)
+
+        return "\n".join(lines) + '\n'
+
+class Args(GDoc):
+    def __init__(self):
+        self._objects = util.OrderedDict()
+
+    def load_data(self, data):
+        """
+        Load the .args lines, creating our list of objects and args.
+        """
+        import re
+        amatcher = re.compile(
+            '(?s)'                                      # make . match \n
+            '<ARG>\n(.*?)</ARG>\n'
+            )
+        nmatcher = re.compile(
+            '<NAME>'
+            '(?P<object>\S*)'                           # store object
+            '::'
+            '(?P<arg>\S*)'                              # store arg
+            '</NAME>'
+        )
+        rmatcher = re.compile(
+            '(?s)'                                      # make . match \n
+            '<TYPE>(?P<type>\S*)</TYPE>\n'              # store type
+            '<RANGE>(?P<range>.*?)</RANGE>\n'           # store range
+            '<FLAGS>(?P<flags>\S*)</FLAGS>\n'           # store flags
+            '<NICK>(?P<nick>.*?)</NICK>\n'              # store nick
+            '<BLURB>(?P<blurb>.*?)</BLURB>\n'           # store blurb
+            '<DEFAULT>(?P<default>.*?)</DEFAULT>\n'     # store default
+        )
+        for block in amatcher.findall(data):
+            nmatch = nmatcher.search(block)
+            if nmatch:
+                o = nmatch.group('object')
+                debug("Found object", o)
+                debug("Found arg", nmatch.group('arg'))
+                if not self._objects.has_key(o):
+                    object = Object(o)
+                    self._objects[o] = object
+
+                rmatch = rmatcher.search(block)
+                if rmatch:
+                    dict = rmatch.groupdict().copy()
+                    dict['name'] = nmatch.group('arg')
+                    arg = Arg(**dict)
+                    self._objects[o].add_arg(arg)
+                else:
+                    print "ERROR: could not match arg from block %s" % block
+
+    def get_data(self):
+        lines = []
+        for o in self._objects.values():
+            for a in o._args.values():
+                block = """<ARG>
+<NAME>%(object)s::%(name)s</NAME>
+<TYPE>%(type)s</TYPE>
+<RANGE>%(range)s</RANGE>
+<FLAGS>%(flags)s</FLAGS>
+<NICK>%(nick)s</NICK>
+<BLURB>%(blurb)s</BLURB>
+<DEFAULT>%(default)s</DEFAULT>
+</ARG>
+"""
+                d = a.dict.copy()
+                d['object'] = o.name
+                lines.append(block % d)
+
+        return "\n".join(lines) + '\n'
+
+def main(argv):
+    modulename = None
+    try:
+        modulename = argv[1]
+    except IndexError:
+        sys.stderr.write('Pleae provide a documentation module name\n')
+        sys.exit(1)
+
+    print "Merging scangobj output for %s" % modulename
+    signals = Signals()
+    signals.load_file(modulename + '.signals')
+    signals.load_file(modulename + '.signals.new')
+    signals.save_file(modulename + '.signals', backup=True)
+
+    args = Args()
+    args.load_file(modulename + '.args')
+    args.load_file(modulename + '.args.new')
+    args.save_file(modulename + '.args', backup=True)
+
+main(sys.argv)
diff --git a/common/upload.mak b/common/upload.mak
new file mode 100755 (executable)
index 0000000..60731e5
--- /dev/null
@@ -0,0 +1,33 @@
+# this snippet is to be included by both our docbook manuals
+# and gtk-doc API references
+
+# it adds an upload target to each of these dir's Makefiles
+
+# each Makefile.am should define the following variables:
+# - DOC: the base name of the documentation
+#        (faq, manual, pwg, gstreamer, gstreamer-libs)
+# - FORMATS: the formats in which DOC is output
+#            (html ps pdf)
+
+# if you want to use it, make sure your $HOME/.ssh/config file contains the
+# correct User entry for the Host entry for the DOC_SERVER
+
+# these variables define the location of the online docs
+DOC_SERVER = gstreamer.freedesktop.org
+DOC_BASE = /srv/gstreamer.freedesktop.org/www/data/doc
+DOC_URL = $(DOC_SERVER):$(DOC_BASE)
+
+upload: $(FORMATS)
+       @if test "x$(PACKAGE_VERSION_NANO)" = x0; then \
+            export DOCVERSION=$(VERSION); \
+        else export DOCVERSION=head; \
+        fi; \
+        export DIR=$(DOC_BASE)/gstreamer/$$DOCVERSION/$(DOC); \
+       ssh $(DOC_SERVER) mkdir -p $$DIR; \
+       if echo $(FORMATS) | grep html > /dev/null; then export SRC="$$SRC html"; fi; \
+       if echo $(FORMATS) | grep ps > /dev/null; then export SRC="$$SRC $(DOC).ps"; fi; \
+       if echo $(FORMATS) | grep pdf > /dev/null; then export SRC="$$SRC $(DOC).pdf"; fi; \
+       echo Uploading $$SRC to $(DOC_SERVER):$$DIR; \
+       rsync -rv -e ssh --delete $$SRC $(DOC_SERVER):$$DIR; \
+       ssh $(DOC_SERVER) chmod -R g+w $$DIR; \
+       echo Done
diff --git a/common/win32.mak b/common/win32.mak
new file mode 100755 (executable)
index 0000000..63b1310
--- /dev/null
@@ -0,0 +1,54 @@
+# various tests to make sure we dist the win32 stuff (for MSVC builds) right
+
+# the MANIFEST contains all win32 related files that should be disted
+win32 = $(shell cat $(top_srcdir)/win32/MANIFEST)
+
+# wildcard is apparently not portable to other makes, hence the use of find
+# these are library .def files with the symbols to export
+win32defs = $(shell find $(top_srcdir)/win32/common -name '*.def')
+
+# wildcard is apparently not portable to other makes, hence the use of find
+# these are files that need to be disted with CRLF line endings:
+win32crlf = $(shell find $(top_srcdir)/win32 -name '*.dsw' -o -name '*.dsp')
+
+win32-debug:
+       @echo; \
+       echo win32     = $(win32); \
+       echo; \
+       echo win32defs = $(win32defs); \
+       echo; \
+       echo win32crlf = $(win32crlf); \
+       echo
+
+win32-check-crlf:
+       @echo Checking win32 files for CR LF line endings ...; \
+       fail=0 ; \
+       for each in $(win32crlf) ; do \
+         if ! (file $$each | grep CRLF >/dev/null) ; then \
+           echo $$each must be fixed to have CRLF line endings ; \
+           fail=1; \
+         fi ; \
+       done ; \
+       exit $$fail
+
+# make sure all symbols we export on linux are defined in the win32 .def too
+# (don't care about other unixes for now, it's enough if it works on one of
+# the linux build bots; we assume .so )
+check-exports:
+       fail=0 ; \
+       for l in $(win32defs); do \
+         libbase=`basename "$$l" ".def"`; \
+         libso=`find "$(top_builddir)" -name "$$libbase-@GST_MAJORMINOR@.so"`; \
+         libdef="$(top_srcdir)/win32/common/$$libbase.def"; \
+         if test "x$$libso" != "x"; then \
+           echo Checking symbols in $$libso; \
+           if ! ($(top_srcdir)/common/check-exports $$libdef $$libso) ; then \
+             fail=1; \
+           fi; \
+         fi; \
+       done
+
+
+dist-hook: check-exports win32-check-crlf
+
+
diff --git a/configure.ac b/configure.ac
new file mode 100755 (executable)
index 0000000..221721b
--- /dev/null
@@ -0,0 +1,464 @@
+
+AC_INIT([Gstreamer Tizen Plug-ins],[1.2.2],[gst-plugins-tizen])
+dnl versions of gstreamer and plugins-base
+GST_MAJORMINOR=1.0
+GST_REQUIRED=1.2.0
+GSTPB_REQUIRED=1.2.0
+EFL_REQUIRED=1.0.0
+
+dnl fill in your package name and version here
+dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
+dnl and 2... for a prerelease
+
+dnl when going to/from release please set the nano correctly !
+dnl releases only do Wall, cvs and prerelease does Werror too
+AS_VERSION(gst-plugin, GST_PLUGIN_VERSION, 0, 10, 0, 1,
+    GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
+
+dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
+AM_MAINTAINER_MODE
+
+#AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
+AM_INIT_AUTOMAKE
+
+#AC_CONFIG_MACRO_DIR([m4])
+
+dnl make aclocal work in maintainer mode
+dnl AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
+
+dnl Add parameters for aclocal
+AC_SUBST(ACLOCAL_AMFLAGS, "-I m4 -I common/m4")
+
+AM_CONFIG_HEADER(config.h)
+
+dnl check for tools
+AC_PROG_CC
+AC_PROG_CXX
+AC_PROG_LIBTOOL
+
+dnl decide on error flags
+AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
+                                                                                
+if test "x$GST_WALL" = "xyes"; then
+   GST_ERROR="$GST_ERROR -Wall"
+                                                                                
+#   if test "x$GST_PLUGIN_CVS" = "xyes"; then
+#     AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
+#   fi
+fi
+
+
+dnl our libraries and install dirs use GST_API_VERSION in the filename
+dnl to allow side-by-side installation of different API versions
+GST_API_VERSION=1.0
+AC_SUBST(GST_API_VERSION)
+AC_DEFINE_UNQUOTED(GST_API_VERSION, "$GST_API_VERSION",
+  [GStreamer API Version])
+
+dnl Check for pkgconfig first
+AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
+
+dnl Give error and exit if we don't have pkgconfig
+if test "x$HAVE_PKGCONFIG" = "xno"; then
+  AC_MSG_ERROR(you need to have pkgconfig installed !)
+fi
+
+dnl Now we're ready to ask for gstreamer libs and cflags
+dnl And we can also ask for the right version of gstreamer
+AM_CONDITIONAL([IS_VODA_SDK], [test "x$DISTRO" = "xvodafone-sdk"])
+AM_CONDITIONAL([ISPROTECTOR_VODA_SDK], [test "x$DISTRO" = "xvodafone-sdk" && test "x$MACHINE" = "xprotector"])
+AM_CONDITIONAL([ISVOLANS_VODA_SDK], [test "x$DISTRO" = "xvodafone-sdk" && test "x$MACHINE" = "xvolans"])
+AM_CONDITIONAL([ISPROTECTOR_TARGET], [test "x$ARCH" = "xarm" && test "x$MACHINE" = "xprotector"])
+AM_CONDITIONAL([ISVOLANS_TARGET], [test "x$ARCH" = "xarm" && test "x$MACHINE" = "xvolans"])
+
+PKG_CHECK_MODULES(GST, \
+  gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
+  HAVE_GST=yes,HAVE_GST=no)
+
+dnl Give error and exit if we don't have gstreamer
+if test "x$HAVE_GST" = "xno"; then
+  AC_MSG_ERROR(you need gstreamer development packages installed !)
+fi
+
+dnl append GST_ERROR cflags to GST_CFLAGS
+GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
+
+dnl make GST_CFLAGS and GST_LIBS available
+PKG_CHECK_MODULES(GST, gstreamer-1.0 >= 1.2.0)
+AC_SUBST(GST_CFLAGS)
+AC_SUBST(GST_LIBS)
+
+dnl make GST_MAJORMINOR available in Makefile.am
+AC_SUBST(GST_MAJORMINOR)
+
+dnl If we need them, we can also use the base class libraries
+PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
+                  HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
+
+dnl Give a warning if we don't have gstreamer libs
+dnl you can turn this into an error if you need them
+if test "x$HAVE_GST_BASE" = "xno"; then
+  AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
+fi
+
+dnl make _CFLAGS and _LIBS available
+AC_SUBST(GST_BASE_CFLAGS)
+AC_SUBST(GST_BASE_LIBS)
+
+dnl If we need them, we can also use the gstreamer-plugins-base libraries
+PKG_CHECK_MODULES(GSTPB_BASE,
+                  gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
+                  HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
+
+dnl Give a warning if we don't have gstreamer libs
+dnl you can turn this into an error if you need them
+if test "x$HAVE_GSTPB_BASE" = "xno"; then
+  AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
+fi
+
+dnl make _CFLAGS and _LIBS available
+AC_SUBST(GSTPB_BASE_CFLAGS)
+AC_SUBST(GSTPB_BASE_LIBS)
+
+dnl If we need them, we can also use the gstreamer-controller libraries
+PKG_CHECK_MODULES(GSTCTRL,
+                  gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
+                  HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
+
+dnl Give a warning if we don't have gstreamer-controller
+dnl you can turn this into an error if you need them
+if test "x$HAVE_GSTCTRL" = "xno"; then
+  AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
+fi
+
+dnl make _CFLAGS and _LIBS available
+AC_SUBST(GSTCTRL_CFLAGS)
+AC_SUBST(GSTCTRL_LIBS)
+
+dnl set the plugindir where plugins should be installed
+if test "x${prefix}" = "x$HOME"; then
+  plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
+else
+  plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
+fi
+AC_SUBST(plugindir)
+
+dnl set proper LDFLAGS for plugins
+#GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
+GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\|FIR_\|arkamys_malloc\|arkamys_free\).*'
+#GST_PLUGIN_LDFLAGS='-module -avoid-version'
+AC_SUBST(GST_PLUGIN_LDFLAGS)
+
+
+PKG_CHECK_MODULES(GST_AUDIO, gstreamer-audio-$GST_MAJORMINOR >= $GST_REQUIRED )
+
+
+dnl make _CFLAGS and _LIBS available
+AC_SUBST(GST_AUDIO_CFLAGS)
+AC_SUBST(GST_AUDIO_LIBS)
+
+PKG_CHECK_MODULES(GST_VIDEO, gstreamer-video-$GST_MAJORMINOR >= $GST_REQUIRED)
+
+dnl make _CFLAGS and _LIBS available
+AC_SUBST(GST_VIDEO_CFLAGS)
+AC_SUBST(GST_VIDEO_LIBS)
+
+dnl xvimagesrc _CFLAGS and _LIB available
+
+PKG_CHECK_MODULES(DRI2, libdri2)
+AC_SUBST(DRI2_CFLAGS)
+AC_SUBST(DRI2_LIBS)
+
+PKG_CHECK_MODULES(X11, x11)
+AC_SUBST(X11_CFLAGS)
+AC_SUBST(X11_LIBS)
+
+PKG_CHECK_MODULES(XEXT, xext)
+AC_SUBST(XEXT_CFLAGS)
+AC_SUBST(XEXT_LIBS)
+
+PKG_CHECK_MODULES(XV, xv)
+AC_SUBST(XV_CFLAGS)
+AC_SUBST(XV_LIBS)
+
+PKG_CHECK_MODULES(XDAMAGE, xdamage)
+AC_SUBST(XDAMAGE_CFLAGS)
+AC_SUBST(XDAMAGE_LIBS)
+
+PKG_CHECK_MODULES(DRM, libdrm)
+AC_SUBST(DRM_CFLAGS)
+AC_SUBST(DRM_LIBS)
+
+PKG_CHECK_MODULES(DRM, libdrm-devel)
+AC_SUBST(DRM_DEVEL_CFLAGS)
+AC_SUBST(DRM_DEVEL_LIBS)
+
+PKG_CHECK_MODULES(TBM, libtbm)
+AC_SUBST(TBM_CFLAGS)
+AC_SUBST(TBM_LIBS)
+
+PKG_CHECK_MODULES(MMCOMMON,mm-common)
+AC_SUBST(MMCOMMON_CFLAGS)
+
+dnl required package for evaspixmapsink
+PKG_CHECK_MODULES(EFL, [
+  evas >= $EFL_REQUIRED
+  ecore >= $EFL_REQUIRED
+  ecore-x >= $EFL_REQUIRED
+], [
+  AC_SUBST(EFL_CFLAGS)
+  AC_SUBST(EFL_LIBS)
+], [
+  AC_MSG_ERROR([
+      You need to install or upgrade the EFL development
+      packages on your system. On debian-based systems these are
+      libevas-dev and libecore-dev.
+      The minimum version required is $EFL_REQUIRED.
+  ])
+])
+
+dnl *** belows are related to evaspixmapsink plug-ins ***
+AG_GST_ARG_WITH_PACKAGE_NAME
+AG_GST_ARG_WITH_PACKAGE_ORIGIN
+
+dnl set license and copyright notice
+GST_LICENSE="LGPL"
+AC_DEFINE_UNQUOTED(GST_LICENSE, "$GST_LICENSE", [GStreamer license])
+AC_SUBST(GST_LICENSE)
+
+echo
+AC_MSG_NOTICE([Checking libraries for evaspixmapsink plugin])
+echo
+dnl *** X11 ***
+translit(dnm, m, l) AM_CONDITIONAL(USE_X, true)
+AG_GST_CHECK_FEATURE(X, [X libraries and plugins],
+                  [evaspixmapsink], [
+  AC_PATH_XTRA
+  ac_cflags_save="$CFLAGS"
+  ac_cppflags_save="$CPPFLAGS"
+  CFLAGS="$CFLAGS $X_CFLAGS"
+  CPPFLAGS="$CPPFLAGS $X_CFLAGS"
+
+  dnl now try to find the HEADER
+  AC_CHECK_HEADER(X11/Xlib.h, HAVE_X="yes", HAVE_X="no")
+
+  if test "x$HAVE_X" = "xno"
+  then
+    AC_MSG_NOTICE([cannot find X11 development files])
+  else
+    dnl this is much more than we want
+    X_LIBS="$X_LIBS $X_PRE_LIBS $X_EXTRA_LIBS"
+    dnl AC_PATH_XTRA only defines the path needed to find the X libs,
+    dnl it does not add the libs; therefore we add them here
+    X_LIBS="$X_LIBS -lX11"
+    AC_SUBST(X_CFLAGS)
+    AC_SUBST(X_LIBS)
+  fi
+  AC_SUBST(HAVE_X)
+  CFLAGS="$ac_cflags_save"
+  CPPFLAGS="$ac_cppflags_save"
+])
+
+dnl Check for Xv extension
+translit(dnm, m, l) AM_CONDITIONAL(USE_XVIDEO, true)
+AG_GST_CHECK_FEATURE(XVIDEO, [X11 XVideo extensions],
+                  [evaspixmapsink], [
+AG_GST_CHECK_XV
+])
+
+dnl check for X Shm
+translit(dnm, m, l) AM_CONDITIONAL(USE_XSHM, true)
+AG_GST_CHECK_FEATURE(XSHM, [X Shared Memory extension], , [
+  if test x$HAVE_X = xyes; then
+    AC_CHECK_LIB(Xext, XShmAttach,
+                HAVE_XSHM="yes", HAVE_XSHM="no",
+                $X_LIBS)
+    if test "x$HAVE_XSHM" = "xyes"; then
+      XSHM_LIBS="-lXext"
+    else
+      dnl On AIX, it is in XextSam instead, but we still need -lXext
+      AC_CHECK_LIB(XextSam, XShmAttach,
+                  HAVE_XSHM="yes", HAVE_XSHM="no",
+                  $X_LIBS)
+      if test "x$HAVE_XSHM" = "xyes"; then
+       XSHM_LIBS="-lXext -lXextSam"
+      fi
+    fi
+  fi
+], , [
+  AC_SUBST(HAVE_XSHM)
+  AC_SUBST(XSHM_LIBS)
+])
+
+dnl PKG_CHECK_MODULES(UDEVMGR, unified-dev-mgr)
+dnl AC_SUBST(UDEVMGR_CFLAGS)
+dnl AC_SUBST(UDEVMGR_LIBS)
+
+dnl use ext-encodebin --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-encodebin, AC_HELP_STRING([--enable-ext-encodebin], [using encodebin]),
+  [
+    case "${enableval}" in
+      yes) USE_GST_TIZEN_ENCODEBIN=yes ;;
+      no)  USE_GST_TIZEN_ENCODEBIN=no ;;
+      *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-encodebin) ;;
+    esac
+  ],
+  [USE_GST_TIZEN_ENCODEBIN=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_ENCODEBIN, test "x$USE_GST_TIZEN_ENCODEBIN" = "xyes")
+
+dnl use evaspixmapsink ---------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-evaspixmapsink, AC_HELP_STRING([--enable-ext-evaspixmapsink], [using evaspixmapsink]),
+  [
+    case "${enableval}" in
+      yes) USE_GST_TIZEN_EVASPIXMAPSINK=yes ;;
+      no)  USE_GST_TIZEN_EVASPIXMAPSINK=no ;;
+      *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-evaspixmapsink) ;;
+    esac
+  ],
+  [USE_GST_TIZEN_EVASPIXMAPSINK=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_EVASPIXMAPSINK, test "x$USE_GST_TIZEN_EVASPIXMAPSINK" = "xyes")
+
+dnl use ext-xvimagesrc--------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-xvimagesrc, AC_HELP_STRING([--enable-ext-xvimagesrc], [using xvimagesrc]),
+  [
+    case "${enableval}" in
+      yes) USE_GST_TIZEN_XVIMAGESRC=yes ;;
+      no)  USE_GST_TIZEN_XVIMAGESRC=no ;;
+      *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-xvimagesrc) ;;
+    esac
+  ],
+  [USE_GST_TIZEN_XVIMAGESRC=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_XVIMAGESRC, test "x$USE_GST_TIZEN_XVIMAGESRC" = "xyes")
+
+dnl use ext-drmsrc --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-drmsrc, AC_HELP_STRING([--enable-ext-drmsrc], [using drmsrc]),
+  [
+    case "${enableval}" in
+      yes) USE_GST_TIZEN_DRMSRC=yes ;;
+      no)  USE_GST_TIZEN_DRMSRC=no ;;
+      *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-drmsrc) ;;
+    esac
+  ],
+  [USE_GST_TIZEN_DRMSRC=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_DRMSRC, test "x$USE_GST_TIZEN_DRMSRC" = "xyes")
+dnl use ext-toggle --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-toggle, AC_HELP_STRING([--enable-ext-toggle], [using toggle]),
+  [
+    case "${enableval}" in
+      yes) USE_GST_TIZEN_TOGGLE=yes ;;
+      no)  USE_GST_TIZEN_TOGGLE=no ;;
+      *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-toggle) ;;
+    esac
+  ],
+  [USE_GST_TIZEN_TOGGLE=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_TOGGLE, test "x$USE_GST_TIZEN_TOGGLE" = "xyes")
+
+dnl for i386 --------------------------------------------------------------------------
+AC_ARG_ENABLE(i386, AC_HELP_STRING([--enable-i386], [i386 build]),
+       [
+        case "${enableval}" in
+         yes) IS_I386=yes ;;
+         no)  IS_I386=no ;;
+         *)   AC_MSG_ERROR(bad value ${enableval} for --enable-i386) ;;
+        esac
+       ],
+       [IS_I386=no])
+AM_CONDITIONAL([IS_I386], [test "x$IS_I386" = "xyes"])
+
+dnl use ext-pdpushsrc --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-pdpushsrc, AC_HELP_STRING([--enable-ext-pdpushsrc], [using pdpushsrc]),
+[
+ case "${enableval}" in
+        yes) USE_GST_TIZEN_PD_PUSHSRC=yes ;;
+        no)  USE_GST_TIZEN_PD_PUSHSRC=no ;;
+        *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-pdpushsrc) ;;
+ esac
+ ],
+ [USE_GST_TIZEN_PD_PUSHSRC=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_PD_PUSHSRC, test "x$USE_GST_TIZEN_PD_PUSHSRC" = "xyes")
+dnl use ext-audiotp --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-audiotp, AC_HELP_STRING([--enable-ext-audiotp], [using audiotp]),
+[
+ case "${enableval}" in
+        yes) USE_GST_TIZEN_AUDIOTP=yes ;;
+        no)  USE_GST_TIZEN_AUDIOTP=no ;;
+        *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-audiotp) ;;
+ esac
+ ],
+ [USE_GST_TIZEN_AUDIOTP=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_AUDIOTP, test "x$USE_GST_TIZEN_AUDIOTP" = "xyes")
+
+dnl use ext-audioeq --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-audioeq, AC_HELP_STRING([--enable-ext-audioeq], [using audioeq]),
+[
+ case "${enableval}" in
+         yes) USE_GST_TIZEN_AUDIOEQ=yes ;;
+         no)  USE_GST_TIZEN_AUDIOEQ=no ;;
+         *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-audioeq) ;;
+ esac
+ ],
+ [USE_GST_TIZEN_AUDIOEQ=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_AUDIOEQ, test "x$USE_GST_TIZEN_AUDIOEQ" = "xyes")
+
+dnl use ext-fimcconvert ----------------------------------------------------------------------
+AC_ARG_ENABLE(ext-fimcconvert, AC_HELP_STRING([--enable-ext-fimcconvert], [using fimcconvert]),
+[
+ case "${enableval}" in
+         yes) USE_GST_TIZEN_FIMCCONVERT=yes ;;
+         no)  USE_GST_TIZEN_FIMCCONVERT=no ;;
+         *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-fimcconvert) ;;
+ esac
+ ],
+ [USE_GST_TIZEN_FIMCCONVERT=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_FIMCCONVERT, test "x$USE_GST_TIZEN_FIMCCONVERT" = "xyes")
+
+dnl use ext-wfdmanager --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-wfdmanager, AC_HELP_STRING([--enable-ext-wfdmanager], [using wfdmanager]),
+[
+ case "${enableval}" in
+  yes) USE_GST_TIZEN_WFDMANAGER=yes ;;
+  no)  USE_GST_TIZEN_WFDMANAGER=no ;;
+  *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-wfdmanager) ;;
+ esac
+ ],
+ [USE_GST_TIZEN_WFDMANAGER=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_WFDMANAGER, test "x$USE_GST_TIZEN_WFDMANAGER" = "xyes")
+
+dnl use ext-wfdtsdemux --------------------------------------------------------------------------
+AC_ARG_ENABLE(ext-wfdtsdemux, AC_HELP_STRING([--enable-ext-wfdtsdemux], [using wfdtsdemux]),
+[
+ case "${enableval}" in
+  yes) USE_GST_TIZEN_WFDTSDEMUX=yes ;;
+  no)  USE_GST_TIZEN_WFDTSDEMUX=no ;;
+  *)   AC_MSG_ERROR(bad value ${enableval} for --enable-ext-wfdtsdemux) ;;
+ esac
+ ],
+ [USE_GST_TIZEN_WFDTSDEMUX=yes])
+AM_CONDITIONAL(USE_GST_TIZEN_WFDTSDEMUX, test "x$USE_GST_TIZEN_WFDTSDEMUX" = "xyes")
+
+AC_OUTPUT(
+Makefile
+common/Makefile
+common/m4/Makefile
+pdpushsrc/Makefile
+pdpushsrc/src/Makefile
+encodebin/Makefile
+encodebin/src/Makefile
+evaspixmapsink/Makefile
+xvimagesrc/Makefile
+xvimagesrc/src/Makefile
+toggle/Makefile
+toggle/src/Makefile
+drmsrc/Makefile
+drmsrc/src/Makefile
+audiotp/Makefile
+audiotp/src/Makefile
+audioeq/Makefile
+audioeq/src/Makefile
+fimcconvert/Makefile
+fimcconvert/src/Makefile
+wfdmanager/Makefile
+wfdmanager/wfdbase/Makefile
+wfdtsdemux/Makefile
+)
diff --git a/drmsrc/Makefile.am b/drmsrc/Makefile.am
new file mode 100755 (executable)
index 0000000..308a09c
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src\r
diff --git a/drmsrc/src/Makefile.am b/drmsrc/src/Makefile.am
new file mode 100755 (executable)
index 0000000..842ed43
--- /dev/null
@@ -0,0 +1,27 @@
+# plugindir is set in configure
+
+##############################################################################
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #
+##############################################################################
+plugin_LTLIBRARIES = libgstdrmsrc.la
+
+##############################################################################
+# for the next set of variables, rename the prefix if you renamed the .la,   #
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #
+##############################################################################
+
+# sources used to compile this plug-in
+libgstdrmsrc_la_SOURCES = gstdrmsrc.c
+
+# flags used to compile this plugin
+# add other _CFLAGS and _LIBS as needed
+libgstdrmsrc_la_CFLAGS = $(GST_CFLAGS) -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64
+libgstdrmsrc_la_LIBADD = $(GST_LIBS) $(GST_BASE_LIBS) 
+libgstdrmsrc_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gstdrmsrc.h
+
diff --git a/drmsrc/src/gstdrmsrc.c b/drmsrc/src/gstdrmsrc.c
new file mode 100755 (executable)
index 0000000..4ab025b
--- /dev/null
@@ -0,0 +1,606 @@
+/*
+ * drmsrc
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+#include "gstdrmsrc.h"
+
+#define LOG_TRACE(message)  //g_print("DRM_SRC: %s: %d: %s - %s \n", __FILE__, __LINE__, __FUNCTION__, message);
+
+#define GST_TAG_PLAYREADY "playready_file_path"
+
+static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS,GST_STATIC_CAPS_ANY);
+
+
+GST_DEBUG_CATEGORY_STATIC (gst_drm_src_debug);
+#define GST_CAT_DEFAULT gst_drm_src_debug
+
+enum
+{
+       ARG_0,
+       ARG_LOCATION,
+       ARG_FD
+};
+static void gst_drm_src_finalize (GObject * object);
+static void gst_drm_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);
+static void gst_drm_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
+static gboolean gst_drm_src_start (GstBaseSrc * basesrc);
+static gboolean gst_drm_src_stop (GstBaseSrc * basesrc);
+static gboolean gst_drm_src_is_seekable (GstBaseSrc * src);
+static gboolean gst_drm_src_get_size (GstBaseSrc * src, guint64 * size);
+static GstFlowReturn gst_drm_src_create (GstBaseSrc * src, guint64 offset, guint length, GstBuffer ** buffer);
+static void gst_drm_src_uri_handler_init (gpointer g_iface, gpointer iface_data);
+
+G_DEFINE_TYPE_WITH_CODE (GstDrmSrc, gst_drm_src, GST_TYPE_BASE_SRC,
+                         G_IMPLEMENT_INTERFACE(GST_TYPE_URI_HANDLER, gst_drm_src_uri_handler_init));
+/**
+ * This function does the following:
+ *  1. Sets the class details
+ *  2. Adds the source pad template
+ *
+ * @param   g_class    [out]   gpointer
+ *
+ * @return  void
+ */
+static void gst_drm_src_base_init (gpointer g_class)
+{
+}
+/**
+ * This function does the following:
+ *  1. Installs the properties
+ *  2. Assigns the function pointers GObject class attributes
+ *
+ * @param   klass    [out]   GstDrmSrcClass Structure
+ *
+ * @return  void
+ */
+static void gst_drm_src_class_init (GstDrmSrcClass * klass)
+{
+       GObjectClass *gobject_class;
+       GstElementClass *gstelement_class;
+       GstBaseSrcClass *gstbasesrc_class;
+       gobject_class = G_OBJECT_CLASS (klass);
+        gstelement_class= GST_ELEMENT_CLASS (klass);
+       gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
+       // Assigns the function pointers GObject class attributes
+       gobject_class->set_property = gst_drm_src_set_property;
+       gobject_class->get_property = gst_drm_src_get_property;
+       //  1. Installs the properties
+       g_object_class_install_property (gobject_class, ARG_FD,
+               g_param_spec_int ("fd", "File-descriptor",
+               "File-descriptor for the file being mmap()d", 0, G_MAXINT, 0,
+               G_PARAM_READABLE));
+       g_object_class_install_property (gobject_class, ARG_LOCATION,
+               g_param_spec_string ("location", "File Location",
+               "Location of the file to read", NULL, G_PARAM_READWRITE));
+
+       // 2. Sets the class details
+       gst_element_class_set_details_simple (gstelement_class,
+               "DRM Source",
+               "Source/File",
+               "Read from arbitrary point in a standard/DRM file",
+               "Kishore Arepalli  <kishore.a@samsung.com> and Sadanand Dodawadakar <sadanand.d@samsung.com>");
+      // 3. Adds the source pad template
+       gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&srctemplate));
+       // 4. Assigns the function pointers GObject class attributes
+       gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_drm_src_finalize);
+       gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_drm_src_start);
+       gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_drm_src_stop);
+       gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_drm_src_is_seekable);
+       gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_drm_src_get_size);
+       gstbasesrc_class->create = GST_DEBUG_FUNCPTR (gst_drm_src_create);
+
+
+       gst_tag_register (GST_TAG_PLAYREADY, GST_TAG_FLAG_META,
+                       G_TYPE_STRING,
+                       "PlayReady File Path",
+                       "a tag that is specific to PlayReady File",
+                       NULL);
+}
+/**
+ * This function does the following:
+ *  1. Initilizes the parameters of GstDrmSrc
+ *
+ * @param   src    [out]   GstDrmSrc structure
+ * @param   g_class    [in]   GstDrmSrcClass structure
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on ERROR
+ */
+static void gst_drm_src_init (GstDrmSrc * src)
+{
+       // 1. Initilizes the parameters of GstDrmSrc
+       src->filename = NULL;
+       src->fd = 0;
+       src->uri = NULL;
+       src->is_regular = FALSE;
+       src->seekable = FALSE;
+}
+/**
+ * This function does the following:
+ *  1. deallocates the filename and uri
+ *  2. calls the parent class->finalize
+ *
+ * @param   object    [in]   GObject Structure
+ *
+ * @return  void
+ */
+static void gst_drm_src_finalize (GObject * object)
+{
+       GstDrmSrc *src;
+
+       src = GST_DRM_SRC (object);
+       //  1. deallocates the filename and uri
+       g_free (src->filename);
+       g_free (src->uri);
+       // 2. calls the parent class->finalize
+       G_OBJECT_CLASS (gst_drm_src_parent_class)->finalize (object);
+}
+/**
+ * This function does the following:
+ *  1. Checks the state
+ *  2. Checks the filename
+ *  3. Sets the filename
+ *
+ * @param   src    [in]   GstDrmSrc Structure
+ * @param   location    [in]   location of the file
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on ERROR
+ */
+static gboolean gst_drm_src_set_location (GstDrmSrc * src, const gchar * location)
+{
+       GstState state;
+
+       GST_OBJECT_LOCK (src);
+       //  1. Checks the state
+       state = GST_STATE (src);
+       if (state != GST_STATE_READY && state != GST_STATE_NULL)
+       {
+               GST_DEBUG_OBJECT (src, "setting location in wrong state");
+               GST_OBJECT_UNLOCK (src);
+               return FALSE;
+       }
+       GST_OBJECT_UNLOCK (src);
+       g_free (src->filename);
+       g_free (src->uri);
+       //  2. Checks the filename
+       if (location == NULL)
+       {
+               src->filename = NULL;
+               src->uri = NULL;
+       }
+       else
+       {
+               // 3. Sets the filename
+               src->filename = g_strdup (location);
+               src->uri = gst_uri_construct ("file", src->filename);
+       }
+       g_object_notify (G_OBJECT (src), "location");
+       return TRUE;
+}
+/**
+ * This function does the following:
+ *  1. Sets the location of the file.
+ *
+ * @param   object    [in]   GObject Structure
+ * @param   prop_id    [in]   id of the property
+ * @param   value    [in]   property value
+ * @param   pspec    [in]  GParamSpec Structure
+ *
+ * @return  void
+ */
+static void gst_drm_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec)
+{
+       GstDrmSrc *src;
+
+       g_return_if_fail (GST_IS_DRM_SRC (object));
+       src = GST_DRM_SRC (object);
+       switch (prop_id)
+       {
+               //  1. Sets the location of the file.
+               case ARG_LOCATION:
+                       gst_drm_src_set_location (src, g_value_get_string (value));
+                       break;
+               default:
+                       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+                       break;
+       }
+}
+/**
+ * This function does the following:
+ *  1. Provides the location of the file.
+ *  2. Provides the file descriptor.
+ *
+ * @param   object    [in]   GObject Structure
+ * @param   prop_id    [in]   id of the property
+ * @param   value    [out]   property value
+ * @param   pspec    [in]  GParamSpec Structure
+ *
+ * @return  void
+ */
+static void gst_drm_src_get_property (GObject * object, guint prop_id, GValue * value,GParamSpec * pspec)
+{
+       GstDrmSrc *src;
+
+       g_return_if_fail (GST_IS_DRM_SRC (object));
+       src = GST_DRM_SRC (object);
+       switch (prop_id)
+       {
+               //  1. Provides the location of the file.
+               case ARG_LOCATION:
+                       g_value_set_string (value, src->filename);
+                       break;
+               // 2. Provides the file descriptor.
+               case ARG_FD:
+                       g_value_set_int (value, src->fd);
+                       break;
+               default:
+                       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+                       break;
+       }
+}
+
+/**
+ * This function does the following:
+ *  1. Seeks to the specified position.
+ *  2. Allocates a buffer to push the data
+ *  3. Reads from the file and sets the related params
+ *
+ * @param   src    [in]   GstDrmSrc Structure
+ * @param   offset    [in]   offset of the file to seek
+ * @param   length    [in]   size of the data in bytes
+ * @param   buffer    [out]   GstBuffer to hold the contents
+ *
+ * @return  GstFlowReturn   Returns GST_FLOW_OK on success and ERROR on failure
+ */
+static GstFlowReturn gst_drm_src_create_read (GstDrmSrc * src, guint64 offset, guint length, GstBuffer ** buffer)
+{
+       int ret;
+       GstBuffer *buf;
+       GstMapInfo buf_info = GST_MAP_INFO_INIT;
+       // 1. Seeks to the specified position.
+       if (G_UNLIKELY (src->read_position != offset))
+       {
+               off_t res;
+               res = lseek (src->fd, offset, SEEK_SET);
+               if (G_UNLIKELY (res < 0 || res != offset))
+               {
+                       GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
+                       return GST_FLOW_ERROR;
+               }
+               src->read_position = offset;
+       }
+       // 2. Allocates a buffer to push the data
+       buf = gst_buffer_new_and_alloc (length);
+       GST_LOG_OBJECT (src, "Reading %d bytes", length);
+       // 3. Reads from the file and sets the related params
+       gst_buffer_map(buf, &buf_info, GST_MAP_WRITE);
+       if (!buf_info.data)
+               return GST_FLOW_ERROR;
+       ret = read (src->fd, buf_info.data, length);
+       gst_buffer_unmap(buf, &buf_info);
+       if (G_UNLIKELY (ret < 0))
+       {
+               GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
+               gst_buffer_unref (buf);
+               return GST_FLOW_ERROR;
+       }
+       if (G_UNLIKELY ((guint) ret < length && src->seekable))
+       {
+               GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),("unexpected end of file."));
+               gst_buffer_unref (buf);
+               return GST_FLOW_ERROR;
+       }
+       if (G_UNLIKELY (ret == 0 && length > 0))
+       {
+               GST_DEBUG ("non-regular file hits EOS");
+               gst_buffer_unref (buf);
+               return GST_FLOW_EOS;
+       }
+       length = ret;
+       GST_BUFFER_OFFSET (buf) = offset;
+       GST_BUFFER_OFFSET_END (buf) = offset + length;
+       *buffer = buf;
+       src->read_position += length;
+       return GST_FLOW_OK;
+}
+/**
+ * This function does the following:
+ *  1. Calls DRM file read chain method for drm files.
+ *  2. Calls normal file read chain method for standard files.
+ *
+ * @param   basesrc    [in]   BaseSrc Structure
+ * @param   size    [out]   Size of the file
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on ERROR
+ */
+static GstFlowReturn gst_drm_src_create (GstBaseSrc * basesrc, guint64 offset, guint length, GstBuffer ** buffer)
+{
+       GstDrmSrc *src = GST_DRM_SRC (basesrc);
+
+       // 1. Calls DRM file read chain method for drm files.
+
+       // 2. Calls normal file read chain method for standard files.
+       return gst_drm_src_create_read (src, offset, length, buffer);
+}
+/**
+ *
+ * @param   basesrc    [in]   BaseSrc Structure
+ *
+ * @return  gboolean   Returns TRUE if the file is seekable and FALSE if the file is not seekable
+ */
+static gboolean gst_drm_src_is_seekable (GstBaseSrc * basesrc)
+{
+       GstDrmSrc *src = GST_DRM_SRC (basesrc);
+       return src->seekable;
+}
+/**
+ * This function does the following:
+ *  1. Gets the filesize for drm file by using seek oprations
+ *  2. Gets the file size for standard file by using statistics
+ *
+ * @param   basesrc    [in]   BaseSrc Structure
+ * @param   size    [in]   Size of the file
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on ERROR
+ */
+static gboolean gst_drm_src_get_size (GstBaseSrc * basesrc, guint64 * size)
+{
+       struct stat stat_results;
+       GstDrmSrc *src = GST_DRM_SRC (basesrc);
+       unsigned int offset;
+
+       //  1. Gets the filesize for drm file by using seek oprations
+
+       // 2. Gets the file size for standard file by using statistics
+       if (fstat (src->fd, &stat_results) < 0)
+               return FALSE;
+       *size = stat_results.st_size;
+       return TRUE;
+}
+/**
+ * This function does the following:
+ *  1. Checks the filename
+ *  2. Opens the file and check statistics of the file
+ *  7. Checks the seeking for standard files
+ *
+ * @param   basesrc    [in]   BaseSrc Structure
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on ERROR
+ */
+static gboolean gst_drm_src_start (GstBaseSrc * basesrc)
+{
+       GstDrmSrc *src = GST_DRM_SRC (basesrc);
+       struct stat stat_results;
+       off_t ret;
+       // 1. Checks the filename
+       if (src->filename == NULL || src->filename[0] == '\0')
+       {
+               GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,("No file name specified for reading."), (NULL));
+               return FALSE;
+       }
+       // 2. Opens the file and check statistics of the file
+       GST_INFO_OBJECT (src, "opening file %s", src->filename);
+       src->fd = open (src->filename, O_RDONLY | O_BINARY);
+       if (src->fd < 0)
+       {
+               if(errno == ENOENT)
+               {
+                       GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),("No such file \"%s\"", src->filename));
+                       return FALSE;
+               }
+               GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("Could not open file \"%s\" for reading.", src->filename), GST_ERROR_SYSTEM);
+               return FALSE;
+       }
+       if (fstat (src->fd, &stat_results) < 0)
+       {
+               GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("Could not get info on \"%s\".", src->filename), (NULL));
+               close (src->fd);
+               return FALSE;
+       }
+       if (S_ISDIR (stat_results.st_mode))
+       {
+               GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("\"%s\" is a directory.", src->filename), (NULL));
+               close (src->fd);
+               return FALSE;
+       }
+       if (S_ISSOCK (stat_results.st_mode))
+       {
+               GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("File \"%s\" is a socket.", src->filename), (NULL));
+               close (src->fd);
+               return FALSE;
+       }
+       src->read_position = 0;
+
+       // 7. Checks the seeking for standard files
+       if (S_ISREG (stat_results.st_mode))
+               src->is_regular = TRUE;
+       ret = lseek (src->fd, 0, SEEK_END);
+       if (ret < 0)
+       {
+               GST_LOG_OBJECT (src, "disabling seeking, not in mmap mode and lseek "
+                       "failed: %s", g_strerror (errno));
+               src->seekable = FALSE;
+       }
+       else
+       {
+               src->seekable = TRUE;
+       }
+       lseek (src->fd, 0, SEEK_SET);
+       src->seekable = src->seekable && src->is_regular;
+       return TRUE;
+}
+/**
+ * This function does the following:
+ *  1. Closes the file desciptor and resets the flags
+ *
+ * @param   basesrc    [in]   BaseSrc Structure
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on ERROR
+ */
+static gboolean gst_drm_src_stop (GstBaseSrc * basesrc)
+{
+       GstDrmSrc *src = GST_DRM_SRC (basesrc);
+
+       // 1. Closes the file desciptor and resets the flags
+       if(src->fd > 0)
+               close (src->fd);
+       src->fd = 0;
+       src->is_regular = FALSE;
+       return TRUE;
+}
+/**
+ *
+ * @param   void
+ *
+ * @return  GstURIType   Returns GST_URI_SRC
+ */
+
+static GstURIType gst_drm_src_uri_get_type (GType type)
+{
+       return GST_URI_SRC;
+}
+
+/**
+ * This function does the following:
+ *  1. Defines the list of protocols
+ *
+ * @param   void
+ *
+ * @return  gchar **   Returns the protocol list
+ */
+
+static const gchar * const* gst_drm_src_uri_get_protocols (GType type)
+{
+    static const gchar *protocols[] = { "file", NULL };
+       return protocols;
+}
+/**
+ *
+ * @param   handler [in] GstURIHandler structure
+ *
+ * @return  gchar*   Returns the uri
+ */
+static gchar * gst_drm_src_uri_get_uri (GstURIHandler *handler)
+{
+       GstDrmSrc *src = GST_DRM_SRC (handler);
+    return g_strdup(src->uri);
+}
+/**
+ * This function does the following:
+ *  1. Checks the protocol
+ *  2. Checks the whether it is absolute or not
+ *  3 sets the location
+ *
+ * @param   handler [in] GstURIHandler structure
+ * @param   uri [in] uri string
+ *
+ * @return  gboolean   Returns TRUE on success and FALSE on Error
+ */
+static gboolean gst_drm_src_uri_set_uri (GstURIHandler *handler, const gchar * uri,GError ** error)
+{
+       gchar *protocol, *location;
+       gboolean ret;
+       GstDrmSrc *src = GST_DRM_SRC (handler);
+       // 1. Checks the protocol
+       protocol = gst_uri_get_protocol (uri);
+       if (strcmp (protocol, "file") != 0)
+       {
+               g_free (protocol);
+               return FALSE;
+       }
+       g_free (protocol);
+       if (g_str_has_prefix (uri, "file://localhost/"))
+       {
+               char *tmp;
+               tmp = g_strconcat ("file://", uri + 16, NULL);
+               location = gst_uri_get_location (tmp);
+               g_free (tmp);
+       }
+       else if (strcmp (uri, "file://") == 0)
+       {
+               gst_drm_src_set_location (src, NULL);
+               return TRUE;
+       }
+       else
+       {
+               location = gst_uri_get_location (uri);
+       }
+       if (!location)
+               return FALSE;
+       // 2. Checks the whether it is absolute or not
+       if (!g_path_is_absolute (location))
+       {
+               g_free (location);
+               return FALSE;
+       }
+       // 3 sets the location
+       ret = gst_drm_src_set_location (src, location);
+       g_free (location);
+       return ret;
+}
+/**
+ * This function does the following:
+ *  1. Assignes the function pointer for URI related stuff
+ *
+ * @param   g_iface [in] an interface to URI handler
+ * @param   iface_data [in] a gpointer
+ *
+ * @return  void
+ */
+static void gst_drm_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
+{
+       GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
+       // 1. Assigning the function pointer for URI related stuff
+       iface->get_type = gst_drm_src_uri_get_type;
+       iface->get_protocols = gst_drm_src_uri_get_protocols;
+       iface->get_uri = gst_drm_src_uri_get_uri;
+       iface->set_uri = gst_drm_src_uri_set_uri;
+}
+/**
+ * This function does the following:
+ *  1. Registers an element as drmsrc
+ *
+ * @param   i_pPlugin [in] a plug-in structure
+ *
+ * @return  gboolean TRUE on SUCCESS and FALSE on Error
+ */
+static gboolean plugin_init(GstPlugin* i_pPlugin)
+{
+       return gst_element_register(i_pPlugin, "drmsrc", GST_RANK_NONE, GST_TYPE_DRM_SRC);;
+}
+/**
+ * This function does the following:
+ *  1. plugin defination
+ *
+ */
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+                                                GST_VERSION_MINOR,
+                                                drmsrc,
+                                                "Plugin to read data from standad/DRM File",
+                                                plugin_init,
+                                                VERSION,
+                                                "LGPL",
+                                                "Samsung Electronics Co",
+                                                "http://www.samsung.com/")
+
diff --git a/drmsrc/src/gstdrmsrc.h b/drmsrc/src/gstdrmsrc.h
new file mode 100755 (executable)
index 0000000..44a7395
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * drmsrc
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+
+#ifndef __GST_DRM_SRC_H__
+#define __GST_DRM_SRC_H__
+
+#include <sys/types.h>
+#include <gst/gst.h>
+#include <gst/base/gstbasesrc.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <string.h>
+
+#ifndef S_ISREG
+#define S_ISREG(mode) ((mode)&_S_IFREG)
+#endif
+#ifndef S_ISDIR
+#define S_ISDIR(mode) ((mode)&_S_IFDIR)
+#endif
+#ifndef S_ISSOCK
+#define S_ISSOCK(x) (0)
+#endif
+#ifndef O_BINARY
+#define O_BINARY (0)
+#endif
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_DRM_SRC (gst_drm_src_get_type())
+#define GST_DRM_SRC(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DRM_SRC,GstDrmSrc))
+#define GST_DRM_SRC_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_DRM_SRC,GstDrmSrcClass))
+#define GST_IS_DRM_SRC(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_DRM_SRC))
+#define GST_IS_DRM_SRC_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_DRM_SRC))
+
+typedef struct _GstDrmSrc GstDrmSrc;
+typedef struct _GstDrmSrcClass GstDrmSrcClass;
+
+struct _GstDrmSrc 
+{
+       GstBaseSrc element;
+       gchar *filename;                        
+       gchar *uri;                              
+       gint fd;                                 
+       guint64 read_position;  
+      gboolean seekable;      
+       gboolean is_regular;    
+};
+
+struct _GstDrmSrcClass 
+{
+       GstBaseSrcClass parent_class;
+};
+
+GType gst_drm_src_get_type (void);
+
+G_END_DECLS
+
+#endif /* __GST_DRM_SRC_H__ */
diff --git a/encodebin/Makefile.am b/encodebin/Makefile.am
new file mode 100644 (file)
index 0000000..308a09c
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src\r
diff --git a/encodebin/src/Makefile.am b/encodebin/src/Makefile.am
new file mode 100644 (file)
index 0000000..c855890
--- /dev/null
@@ -0,0 +1,30 @@
+glib_enum_define=GST_RECORD
+glib_enum_prefix=gst_record
+
+plugindir = $(libdir)/gstreamer-@GST_MAJORMINOR@
+
+plugin_LTLIBRARIES = libgstencodebin.la 
+libgstencodebin_la_SOURCES = gstencodebin.c
+nodist_libgstencodebin_la_SOURCES = $(built_sources)
+libgstencodebin_la_CFLAGS = $(GST_PLUGINS_BASE_CFLAGS) $(GST_CFLAGS)
+libgstencodebin_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+libgstencodebin_la_LIBADD = \
+       $(GST_LIBS)\
+        $(GST_BASE_LIBS) \
+        $(GST_LIBS)
+if ISPROTECTOR_TARGET
+libgstencodebin_la_CFLAGS += -DUSE_ENCODER_QUEUE_SET 
+libgstencodebin_la_CFLAGS += -DVIDEO_ENC_QUE_TIME=4 -DAUDIO_ENC_QUE_TIME=4
+endif
+
+if ISVOLANS_TARGET
+libgstencodebin_la_CFLAGS += -DUSE_ENCODER_QUEUE_SET 
+libgstencodebin_la_CFLAGS += -DVIDEO_ENC_QUE_TIME=4 -DAUDIO_ENC_QUE_TIME=4
+endif
+
+BUILT_SOURCES = $(built_headers) $(built_sources)
+
+CLEANFILES = $(BUILT_SOURCES)
+
+include $(top_srcdir)/common/glib-gen.mak
+
diff --git a/encodebin/src/gstencodebin.c b/encodebin/src/gstencodebin.c
new file mode 100755 (executable)
index 0000000..1967a51
--- /dev/null
@@ -0,0 +1,3097 @@
+/*
+ * GStreamer encodebin
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+#include <gst/gst.h>
+#include <gst/video/video.h>
+
+#include "gstencodebin.h"
+
+#define _GST_ELEMENT_LINK_MANY                 gst_element_link_many
+#define _GST_ELEMENT_LINK                      gst_element_link
+#define _GST_PAD_LINK                          gst_pad_link
+
+#ifndef VIDEO_ENC_QUE_TIME
+#define VIDEO_ENC_QUE_TIME             1
+#endif
+#ifndef AUDIO_ENC_QUE_TIME
+#define AUDIO_ENC_QUE_TIME     1
+#endif
+
+//define USE_ENCODER_QUEUE_SET
+#ifdef USE_ENCODER_QUEUE_SET
+#define ENCODER_QUEUE_SET(x_queue, x_byte, x_buffer, x_time /*sec*/) \
+{\
+g_object_set(G_OBJECT(x_queue), \
+                       "max-size-bytes", (guint)x_byte, \
+                       "max-size-buffers", (guint)x_buffer, \
+                       "max-size-time", (guint64)(x_time*GST_SECOND), \
+                       NULL); \
+                       GST_INFO("Set to [%s], max [%d] byte, max [%d] buffer, max [%d] time(sec) ", GST_OBJECT_NAME(x_queue), x_byte, x_buffer, x_time);\
+}
+#else
+#define ENCODER_QUEUE_SET(x_queue, x_byte, x_buffer, x_time) 
+#endif
+
+#define _GST_PAD_LINK_UNREF( srcpad, sinkpad, if_fail_goto )\
+{\
+       GstPadLinkReturn ret = GST_PAD_LINK_OK;\
+       if (srcpad == NULL || sinkpad == NULL) {\
+               if (srcpad == NULL) {\
+                       GST_ERROR("srcpad is NULL");\
+               } else {\
+                       gst_object_unref(srcpad);\
+                       srcpad = NULL;\
+               }\
+               if (sinkpad == NULL) {\
+                       GST_ERROR("sinkpad is NULL");\
+               } else {\
+                       gst_object_unref(sinkpad);\
+                       sinkpad = NULL;\
+               }\
+               goto if_fail_goto;\
+       }\
+       ret = _GST_PAD_LINK(srcpad, sinkpad);\
+       gst_object_unref(srcpad); srcpad = NULL;\
+       gst_object_unref(sinkpad); sinkpad = NULL;\
+       if (ret != GST_PAD_LINK_OK) goto if_fail_goto;\
+}
+
+#define _GST_PAD_UNLINK_UNREF( srcpad, sinkpad)\
+{\
+       if (srcpad && sinkpad) {\
+               gst_pad_unlink(srcpad, sinkpad);\
+       }\
+       if (srcpad) {\
+               gst_object_unref(srcpad);\
+               srcpad = NULL;\
+       }\
+       if (sinkpad) {\
+               gst_object_unref(sinkpad);\
+               sinkpad = NULL;\
+       }\
+}
+
+#define DEFAULT_PROP_PROFILE            0
+#define DEFAULT_PROP_HIGH_SPEED         0
+#define DEFAULT_PROP_VENC_NAME          "avenc_h263"
+#define DEFAULT_PROP_AENC_NAME          "secenc_amr"
+#define DEFAULT_PROP_IENC_NAME          "jpegenc"
+#define DEFAULT_PROP_MUX_NAME           "avmux_3gp"
+#define DEFAULT_PROP_VCONV_NAME         "videoconvert"
+
+/* props */
+enum
+{
+       PROP_0,
+       // encodebin mode :  a/v, audio only, stillshot
+       PROP_PROFILE,
+       //support slow motion capture
+       PROP_HIGH_SPEED,
+       //elements name
+       PROP_VENC_NAME,
+       PROP_AENC_NAME,
+       PROP_IENC_NAME,
+       PROP_MUX_NAME,
+       PROP_VCONV_NAME,
+       //caps
+       PROP_VCAPS,
+       PROP_ACAPS,
+       PROP_ICAPS,
+       //functions
+       PROP_AUTO_AUDIO_CONVERT,
+       PROP_AUTO_AUDIO_RESAMPLE,
+       PROP_AUTO_COLORSPACE,
+       PROP_BLOCK,
+       PROP_PAUSE,
+       PROP_VENC_QUEUE,
+       PROP_AENC_QUEUE,
+       //elements pointer
+       PROP_VIDEO_ENC,
+       PROP_AUDIO_ENC,
+       PROP_IMAGE_ENC,
+       PROP_MUX,
+       PROP_VIDEO_CONV,
+       //options
+       PROP_USE_VIDEO_TOGGLE,
+};
+
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE
+/* signals */
+enum
+{
+  SIGNAL_STREAM_BLOCK,
+  SIGNAL_STREAM_UNBLOCK,       
+  SIGNAL_STREAM_PAUSE,
+  SIGNAL_STREAM_RESUME,  
+  LAST_SIGNAL
+};
+#endif
+
+typedef enum {
+       ENCODEBIN_ELEMENT_VENC,
+       ENCODEBIN_ELEMENT_AENC,
+       ENCODEBIN_ELEMENT_IENC,
+       ENCODEBIN_ELEMENT_MUX,
+       ENCODEBIN_ELEMENT_VIDEO_CONV
+}GstEncodeBinElement;
+
+typedef enum {
+       ENCODEBIN_MUX_AUDIO_SINK,
+       ENCODEBIN_MUX_VIDEO_SINK,
+}GstEncodeBinMuxSinkPad;
+
+
+/* FIX ME */
+
+#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
+# define ENDIANNESS   "LITTLE_ENDIAN, BIG_ENDIAN"
+#else
+# define ENDIANNESS   "BIG_ENDIAN, LITTLE_ENDIAN"
+#endif
+
+/* generic templates */
+#define STATIC_AUDIO_CAPS \
+GST_STATIC_CAPS ( \
+  "audio/x-raw, " \
+    "format = (string) { F64LE, F64BE }, " \
+    "rate = (int) [ 1, MAX ], " \
+    "channels = (int) [ 1, 8 ]; " \
+  "audio/x-raw, " \
+    "format = (string) { F32LE, F32BE }, " \
+    "rate = (int) [ 1, MAX ], " \
+    "channels = (int) [ 1, 8 ]; " \
+  "audio/x-raw, " \
+    "format = (string) { S32LE, S32BE, U32LE, U32BE }, " \
+    "rate = (int) [ 1, MAX ], " \
+    "channels = (int) [ 1, 8 ]; " \
+  "audio/x-raw, "   \
+    "format = (string) { S24LE, S24BE, U24LE, U24BE }, " \
+    "rate = (int) [ 1, MAX ], " \
+    "channels = (int) [ 1, 8 ]; "       \
+  "audio/x-raw, " \
+    "format = (string) { S16LE, S16BE, U16LE, U16BE }, " \
+    "rate = (int) [ 1, MAX ], " \
+    "channels = (int) [ 1, 8 ]; " \
+  "audio/x-raw, " \
+    "format = (string) { S8, U8 }, " \
+    "rate = (int) [ 1, MAX ], " \
+    "channels = (int) [ 1, 8 ]; " \
+)
+
+#define STATIC_VIDEO_CAPS \
+GST_STATIC_CAPS ( \
+  GST_VIDEO_CAPS_MAKE("I420") ";" \
+  GST_VIDEO_CAPS_MAKE("YV12") ";" \
+  GST_VIDEO_CAPS_MAKE("YUY2") ";" \
+  GST_VIDEO_CAPS_MAKE("RGB") ";" \
+  GST_VIDEO_CAPS_MAKE("BGR") ";" \
+  GST_VIDEO_CAPS_MAKE("Y42B") ";" \
+  GST_VIDEO_CAPS_MAKE("Y444") ";" \
+  GST_VIDEO_CAPS_MAKE("BGRA") ";" \
+  GST_VIDEO_CAPS_MAKE("ARGB") ";" \
+  GST_VIDEO_CAPS_MAKE("ABGR") ";" \
+  GST_VIDEO_CAPS_MAKE("RGBA") ";" \
+  GST_VIDEO_CAPS_MAKE("BGRx") ";" \
+  GST_VIDEO_CAPS_MAKE("xBGR") ";" \
+  GST_VIDEO_CAPS_MAKE("xRGB") ";" \
+  GST_VIDEO_CAPS_MAKE("RGBx") ";" \
+  GST_VIDEO_CAPS_MAKE("YUV9") ";" \
+  GST_VIDEO_CAPS_MAKE("YVU9") ";" \
+  GST_VIDEO_CAPS_MAKE("Y41B") ";" \
+  GST_VIDEO_CAPS_MAKE("RGB16") ";" \
+  GST_VIDEO_CAPS_MAKE("RGB15") ";" \
+  GST_VIDEO_CAPS_MAKE("GRAY8") ";" \
+  GST_VIDEO_CAPS_MAKE("RGB8P") ";" \
+  GST_VIDEO_CAPS_MAKE("UYVY") ";" \
+  GST_VIDEO_CAPS_MAKE("IYU1") ";" \
+  GST_VIDEO_CAPS_MAKE("AYUV") \
+)
+
+
+static GstStaticPadTemplate encoder_bin_src_template =
+GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS_ANY);
+
+static GstStaticPadTemplate encoder_bin_video_sink_template =
+GST_STATIC_PAD_TEMPLATE ("video",
+    GST_PAD_SINK,
+    GST_PAD_REQUEST,
+    STATIC_VIDEO_CAPS
+    );
+
+static GstStaticPadTemplate encoder_bin_audio_sink_template =
+GST_STATIC_PAD_TEMPLATE ("audio",
+    GST_PAD_SINK,
+    GST_PAD_REQUEST,
+    STATIC_AUDIO_CAPS
+    );
+
+static GstStaticPadTemplate encoder_bin_image_sink_template =
+GST_STATIC_PAD_TEMPLATE ("image",
+    GST_PAD_SINK,
+    GST_PAD_REQUEST,
+    GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("I420"))
+    );
+
+GST_DEBUG_CATEGORY_STATIC (gst_encode_bin_debug);
+#define GST_CAT_DEFAULT gst_encode_bin_debug
+
+static void gst_encode_bin_class_init (GstEncodeBinClass *klass);
+static void gst_encode_bin_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
+static void gst_encode_bin_set_property (GObject * object,  guint prop_id, const GValue * value, GParamSpec * pspec);
+static void gst_encode_bin_init (GstEncodeBin * encodebin);
+static void gst_encode_bin_dispose (GObject * object);
+static void gst_encode_bin_finalize (GObject * object);
+static GstPad *gst_encode_bin_request_new_pad (GstElement *element, GstPadTemplate *templ, const gchar* name, const GstCaps *caps);
+
+static GstStateChangeReturn gst_encode_bin_change_state (GstElement * element, GstStateChange transition);
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+static void gst_encode_bin_release_pad (GstElement * element, GstPad * pad);
+static gint pad_compare_name (GstPad * pad1, const gchar * name);
+static gboolean gst_encode_bin_add_element_by_name (GstEncodeBin *encodebin, GstEncodeBinElement type, const gchar *name);
+#if 0 //disable unused function
+static gboolean gst_encode_bin_change_profile(GstEncodeBin *encodebin, gboolean profile);
+static void gst_encode_bin_replace_element (GstEncodeBin *encodebin, gint type, GstElement * newelement);
+static gboolean gst_encode_bin_replace_element_by_name(GstEncodeBin *encodebin, GstEncodeBinElement type, const gchar *name);
+static gboolean gst_encode_bin_replace_element_by_object(GstEncodeBin *encodebin, GstEncodeBinElement type, GstElement * element);
+#endif //disable unused function
+static gboolean gst_encode_bin_remove_element (GstEncodeBin *encodebin, GstElement * element);
+static gboolean gst_encode_bin_link_elements (GstEncodeBin *encodebin);
+static gboolean gst_encode_bin_unlink_elements (GstEncodeBin *encodebin);
+static gboolean gst_encode_bin_init_video_elements (GstElement *element, gpointer user_data);
+static gboolean gst_encode_bin_init_audio_elements (GstElement *element, gpointer user_data);
+static gboolean gst_encode_bin_init_image_elements (GstElement *element, gpointer user_data);
+static gboolean gst_encode_bin_block(GstEncodeBin *encodebin, gboolean value);
+static gboolean gst_encode_bin_pause(GstEncodeBin *encodebin, gboolean value);
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+static gboolean gst_encode_bin_release_pipeline (GstElement *element, gpointer user_data);
+static GstPad* gst_encode_bin_get_mux_sink_pad(GstElement *mux, GstEncodeBinMuxSinkPad type);
+
+//Data probe
+static GstPadProbeReturn gst_encode_bin_video_probe(GstPad *pad, GstPadProbeInfo *info, GstEncodeBin *encodebin);
+static GstPadProbeReturn gst_encode_bin_audio_probe(GstPad *pad, GstPadProbeInfo *info, GstEncodeBin *encodebin);
+static GstPadProbeReturn gst_encode_bin_video_probe_hs(GstPad *pad, GstPadProbeInfo *info, GstEncodeBin *encodebin);
+
+static GstElementClass *parent_class;
+
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE
+static guint gst_encode_bin_signals[LAST_SIGNAL] = { 0 };
+#endif
+
+typedef enum {
+       GST_ENCODE_BIN_PROFILE_AV,
+       GST_ENCODE_BIN_PROFILE_AUDIO,
+       GST_ENCODE_BIN_PROFILE_IMAGE,
+} GstEncodeBinProfile;
+
+GType
+gst_encode_bin_profile_get_type (void)
+{
+       static GType encode_bin_profile_type = 0;
+       static const GEnumValue profile_types[] = {
+               {GST_ENCODE_BIN_PROFILE_AV, "Audio and Video Recording", "A/V"},
+               {GST_ENCODE_BIN_PROFILE_AUDIO, "Audio Only Recording", "Audio"},
+               {GST_ENCODE_BIN_PROFILE_IMAGE, "Image Stillshot", "Image"},
+               {0, NULL, NULL}
+       };
+
+       if (!encode_bin_profile_type) {
+               encode_bin_profile_type =
+               g_enum_register_static ("GstEncodeBinProfile",profile_types);
+       }
+       return encode_bin_profile_type;
+}
+
+GType
+gst_encode_bin_get_type (void)
+{
+       static GType gst_encode_bin_type = 0;
+
+       if (!gst_encode_bin_type) {
+               static const GTypeInfo gst_encode_bin_info = {
+                       sizeof (GstEncodeBinClass),
+                       NULL,
+                       NULL,
+                       (GClassInitFunc) gst_encode_bin_class_init,
+                       NULL,
+                       NULL,
+                       sizeof (GstEncodeBin),
+                       0,
+                       (GInstanceInitFunc) gst_encode_bin_init,
+                       NULL
+       };
+
+       gst_encode_bin_type =
+               g_type_register_static (GST_TYPE_BIN, "GstEncodeBin",
+               &gst_encode_bin_info, 0);
+  }
+
+       return gst_encode_bin_type;
+}
+
+static void
+queue_overun_cb (GstElement * queue, GstEncodeBin *encodebin)
+{
+#if 0
+       guint queue_size = 0;
+       guint queue_bufnum = 0;
+//     guint64 queue_time= (guint64)0;
+
+       GstClockTime now = gst_util_get_timestamp ();
+
+       g_object_get(G_OBJECT(queue), "current-level-bytes", &queue_size, 
+                                                               "current-level-buffers", &queue_bufnum,
+       //                                                      "current-level-time", &queue_time,
+                                                               NULL);
+       GST_ELEMENT_WARNING (encodebin, STREAM, TOO_LAZY,
+           ("[%" GST_TIME_FORMAT "][%s], [%u b], [%u]", 
+           GST_TIME_ARGS(now), GST_OBJECT_NAME(queue), queue_size, queue_bufnum), (NULL)); 
+#else
+       GST_ELEMENT_WARNING (encodebin, STREAM, TOO_LAZY,
+           ("%s overrun", GST_OBJECT_NAME(queue)), (NULL)); 
+#endif
+}
+
+static void
+gst_encode_bin_get_property (GObject * object,
+    guint prop_id, GValue * value, GParamSpec * pspec)
+{
+       GstEncodeBin *encodebin;
+
+       encodebin = GST_ENCODE_BIN (object);
+
+       switch (prop_id) {
+               case PROP_PROFILE:
+                       g_value_set_enum (value, encodebin->profile);
+                       break;
+               case PROP_HIGH_SPEED:
+                       g_value_set_int (value, encodebin->high_speed_fps);
+                       break;
+               //elements name
+               case PROP_VENC_NAME:
+                       g_value_set_string (value, encodebin->venc_name);
+                       break;
+               case PROP_AENC_NAME:
+                       g_value_set_string (value, encodebin->aenc_name);
+                       break;
+               case PROP_IENC_NAME:
+                       g_value_set_string (value, encodebin->ienc_name);
+                       break; 
+               case PROP_MUX_NAME:
+                       g_value_set_string (value, encodebin->mux_name);
+                       break;
+               case PROP_VCONV_NAME:
+                       g_value_set_string (value, encodebin->vconv_name);
+                       break;
+               //caps
+               case PROP_VCAPS:
+                       gst_value_set_caps (value, encodebin->vcaps);
+                       break;
+               case PROP_ACAPS:
+                       gst_value_set_caps (value, encodebin->acaps);
+                       break;
+               case PROP_ICAPS:
+                       gst_value_set_caps (value, encodebin->icaps);
+                       break;
+               //functions
+               case PROP_AUTO_AUDIO_CONVERT:
+                       g_value_set_boolean (value, encodebin->auto_audio_convert);
+                       break;
+               case PROP_AUTO_AUDIO_RESAMPLE:
+                       g_value_set_boolean (value, encodebin->auto_audio_resample);
+                       break;
+               case PROP_AUTO_COLORSPACE:
+                       g_value_set_boolean (value, encodebin->auto_color_space);
+                       break;
+               case PROP_BLOCK:
+                       g_value_set_boolean (value, encodebin->block);
+                       break;
+               case PROP_PAUSE:
+                       g_value_set_boolean (value, encodebin->pause);
+                       break;
+               case PROP_VENC_QUEUE:
+//                     g_value_set_boolean (value, encodebin->use_venc_queue);
+                       if((encodebin->video_encode_queue == NULL) && (encodebin->profile == GST_ENCODE_BIN_PROFILE_AV)) {
+                               encodebin->video_encode_queue = gst_element_factory_make ("queue", "video_encode_queue");
+                               if(encodebin->video_encode_queue != NULL) 
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->video_encode_queue);
+                       }
+                       g_value_set_object (value, encodebin->video_encode_queue);              
+                       break;          
+               case PROP_AENC_QUEUE:
+//                     g_value_set_boolean (value, encodebin->use_aenc_queue);
+                       if((encodebin->audio_encode_queue == NULL) && (encodebin->profile <= GST_ENCODE_BIN_PROFILE_AUDIO)) {
+                               encodebin->audio_encode_queue = gst_element_factory_make ("queue", "audio_encode_queue");
+                               if(encodebin->audio_encode_queue != NULL)
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->audio_encode_queue);
+                       }
+                       g_value_set_object (value, encodebin->audio_encode_queue);
+                       break;
+               //elements pointer
+               case PROP_VIDEO_ENC:
+                       if((encodebin->video_encode == NULL) && (encodebin->profile == GST_ENCODE_BIN_PROFILE_AV)) {
+                               encodebin->video_encode = gst_element_factory_make (encodebin->venc_name, "video_encode");
+                               if(encodebin->video_encode != NULL)
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->video_encode);
+                       }
+                       g_value_set_object (value, encodebin->video_encode);
+                       break;
+               case PROP_AUDIO_ENC:
+                       if(encodebin->audio_encode == NULL && (encodebin->profile <= GST_ENCODE_BIN_PROFILE_AUDIO)) {
+                               encodebin->audio_encode = gst_element_factory_make (encodebin->aenc_name, "audio_encode");
+                               if(encodebin->audio_encode != NULL)
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->audio_encode);
+                       }
+                       g_value_set_object (value, encodebin->audio_encode);
+                       break;
+               case PROP_IMAGE_ENC:
+                       if(encodebin->image_encode == NULL && (encodebin->profile == GST_ENCODE_BIN_PROFILE_IMAGE)) {
+                               encodebin->image_encode = gst_element_factory_make (encodebin->ienc_name, "image_encode");
+                               if(encodebin->image_encode != NULL)
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->image_encode);
+                       }
+                       g_value_set_object (value, encodebin->image_encode);
+                       break;  
+               case PROP_MUX:
+                       if(encodebin->mux == NULL && (encodebin->profile <= GST_ENCODE_BIN_PROFILE_AUDIO)) {
+                               encodebin->mux = gst_element_factory_make (encodebin->mux_name, "mux");
+                               if(encodebin->mux != NULL)
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->mux);
+                       }
+                       g_value_set_object (value, encodebin->mux);
+                       break;
+               case PROP_VIDEO_CONV:
+                       if(encodebin->color_space == NULL && (encodebin->profile != GST_ENCODE_BIN_PROFILE_AUDIO)) {
+                               encodebin->color_space = gst_element_factory_make (encodebin->vconv_name, "video_convert");
+                               if(encodebin->color_space != NULL)
+                                       gst_bin_add(GST_BIN(encodebin), encodebin->color_space);
+                       }
+                       g_value_set_object (value, encodebin->color_space);
+                       break;
+               case PROP_USE_VIDEO_TOGGLE:
+                       g_value_set_boolean( value, encodebin->use_video_toggle );
+                       break;
+               default:
+                       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+                       break;
+       }
+}
+
+static void
+gst_encode_bin_set_property (GObject * object,
+    guint prop_id, const GValue * value, GParamSpec * pspec)
+{
+       GstEncodeBin *encodebin;
+
+       encodebin = GST_ENCODE_BIN (object);
+
+       switch (prop_id) {
+               case PROP_PROFILE:
+                       encodebin->profile = g_value_get_enum (value);
+                       /*
+                       gboolean newprofile = g_value_get_enum (value);
+                       if(encodebin->profile != newprofile) {
+                         gst_encode_bin_change_profile(encodebin, newprofile);
+                       encodebin->profile = newprofile;
+                               }      
+                       */
+                       break;
+               case PROP_HIGH_SPEED:
+                       encodebin->high_speed_fps = g_value_get_int (value);
+                       break;
+               case PROP_VENC_NAME: {
+                       const gchar  *new_name;
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AV) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       new_name = g_value_get_string (value);
+
+                       if(encodebin->video_encode == NULL) {
+                               if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_VENC, new_name))
+                                       encodebin->venc_name = g_strdup (new_name);
+                       } else {
+                               if(strcmp (encodebin->venc_name, new_name)) {
+                                       gst_encode_bin_remove_element(encodebin, encodebin->video_encode);
+                                       if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_VENC, new_name))
+                                               encodebin->venc_name = g_strdup (new_name);
+                               }
+                       }
+                       break;
+               }  
+               case PROP_AENC_NAME: {
+                       const gchar  *new_name;
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       new_name = g_value_get_string (value);
+
+                       if(encodebin->audio_encode == NULL) {
+                               if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_AENC, new_name))             
+                                       encodebin->aenc_name = g_strdup (new_name);
+                       } else {
+                               if(strcmp (encodebin->aenc_name, new_name)) {
+                                       gst_encode_bin_remove_element(encodebin, encodebin->audio_encode);
+                                       if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_AENC, new_name))             
+                                               encodebin->aenc_name = g_strdup (new_name);
+                               }
+                       }
+                       break;
+               }
+               case PROP_IENC_NAME: {
+                       const gchar  *new_name;
+                       if(encodebin->profile < GST_ENCODE_BIN_PROFILE_IMAGE) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       new_name = g_value_get_string (value);
+
+                       if(encodebin->image_encode == NULL) {
+                               if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_IENC, new_name))             
+                                       encodebin->ienc_name = g_strdup (new_name);
+                       } else {
+                               if(strcmp (encodebin->ienc_name, new_name)) {
+                                       gst_encode_bin_remove_element(encodebin, encodebin->image_encode);
+                                       if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_IENC, new_name))             
+                                               encodebin->ienc_name = g_strdup (new_name);
+                               }
+                       }
+                       break; 
+               }
+               case PROP_MUX_NAME: {
+                       const gchar  *new_name;
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match");
+                               break;
+                       }
+                       new_name = g_value_get_string (value);
+
+                       if(encodebin->mux == NULL) {
+                               if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_MUX, new_name))
+                                       encodebin->mux_name = g_strdup (new_name);
+                       } else {
+                               if(strcmp (encodebin->mux_name, new_name)) {
+                                       gst_encode_bin_remove_element(encodebin, encodebin->mux);
+                                       if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_MUX, new_name))
+                                               encodebin->mux_name = g_strdup (new_name);
+                               }
+                       }
+                       break;
+               }
+               case PROP_VCONV_NAME: {
+                       const gchar  *new_name;
+                       if (encodebin->profile == GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match");
+                               break;
+                       }
+                       new_name = g_value_get_string(value);
+
+                       if (encodebin->color_space == NULL) {
+                               if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_VIDEO_CONV, new_name))
+                                       encodebin->vconv_name = g_strdup (new_name);
+                       } else {
+                               if(strcmp (encodebin->vconv_name, new_name)) {
+                                       gst_encode_bin_remove_element(encodebin, encodebin->color_space);
+                                       if(gst_encode_bin_add_element_by_name(encodebin, ENCODEBIN_ELEMENT_VIDEO_CONV, new_name))
+                                               encodebin->vconv_name = g_strdup (new_name);
+                               }
+                       }
+                       break;
+               }
+               //caps
+               case PROP_VCAPS: {
+                       GstCaps *new_caps;
+                       GstCaps *old_caps;
+                       const GstCaps *new_caps_val = gst_value_get_caps (value);
+
+                       if (new_caps_val == NULL) {
+                               new_caps = gst_caps_new_any ();
+                       } else {
+                               new_caps = (GstCaps *) new_caps_val;
+                               gst_caps_ref (new_caps);
+                       }
+
+                       old_caps = encodebin->vcaps;
+                       encodebin->vcaps = new_caps;
+                       gst_caps_unref (old_caps);
+                       break;
+               }
+               case PROP_ACAPS: {
+                       GstCaps *new_caps;
+                       GstCaps *old_caps;
+                       const GstCaps *new_caps_val = gst_value_get_caps (value);
+
+                       if (new_caps_val == NULL) {
+                               new_caps = gst_caps_new_any ();
+                       } else {
+                               new_caps = (GstCaps *) new_caps_val;
+                               gst_caps_ref (new_caps);
+                       }
+
+                       old_caps = encodebin->acaps;
+                       encodebin->acaps = new_caps;
+                       gst_caps_unref (old_caps);
+                       break;
+               }
+               case PROP_ICAPS: {
+                       GstCaps *new_caps;
+                       GstCaps *old_caps;
+                       const GstCaps *new_caps_val = gst_value_get_caps (value);
+
+                       if (new_caps_val == NULL) {
+                               new_caps = gst_caps_new_any ();
+                       } else {
+                               new_caps = (GstCaps *) new_caps_val;
+                               gst_caps_ref (new_caps);
+                       }
+
+                       old_caps = encodebin->icaps;
+                       encodebin->icaps = new_caps;
+                       gst_caps_unref (old_caps);
+                       break;
+               }
+               //functions
+               case PROP_AUTO_AUDIO_CONVERT:
+                  encodebin->auto_audio_convert = g_value_get_boolean (value);
+                 break;
+               case PROP_AUTO_AUDIO_RESAMPLE:
+                 encodebin->auto_audio_resample = g_value_get_boolean (value);
+                 break;
+               case PROP_AUTO_COLORSPACE:
+                 encodebin->auto_color_space = g_value_get_boolean (value);
+                 break;
+               case PROP_BLOCK: {
+                       gboolean newval = g_value_get_boolean (value);
+                       if(encodebin->block != newval) {
+                               if(!gst_encode_bin_block(encodebin, newval)) {
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE            
+                                       if(newval) {
+                                               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_BLOCK], 0, FALSE);
+                                       } else {
+                                               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_UNBLOCK], 0, FALSE);
+                                       }
+#endif                                 
+                                       break;
+                               }                               
+                       }
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE            
+                       if(newval) {
+                               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_BLOCK], 0, TRUE);
+                       } else {
+                               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_UNBLOCK], 0, TRUE);
+                       }
+#endif                 
+                       break;
+               }
+               case PROP_PAUSE: {
+                       gboolean newval = g_value_get_boolean (value);
+                       if(encodebin->pause != newval) {
+                               if(!gst_encode_bin_pause(encodebin, newval))
+                                       break;
+                       }
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE            
+                       if(newval) {
+                               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_PAUSE], 0, TRUE);
+                       } else {
+                               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_RESUME], 0, TRUE);
+                       }
+#endif                 
+                       break;
+               }
+               case PROP_VENC_QUEUE:
+//               encodebin->use_venc_queue = g_value_get_boolean (value);
+               {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AV) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->video_encode_queue);
+                               encodebin->video_encode_queue = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->video_encode_queue)); // take ownership ??
+                               gst_bin_add(GST_BIN(encodebin), encodebin->video_encode_queue);
+                       }
+                       break;
+               }
+                 break;                
+               case PROP_AENC_QUEUE:
+//               encodebin->use_aenc_queue = g_value_get_boolean (value);
+               {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->audio_encode_queue);
+                               encodebin->audio_encode_queue = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->audio_encode_queue));
+                               gst_bin_add(GST_BIN(encodebin), encodebin->audio_encode_queue);
+                       }
+                       break;
+               }
+                 break;                  
+               case PROP_VIDEO_ENC: 
+               {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AV) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->video_encode);
+                               encodebin->video_encode = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->video_encode)); // take ownership ??
+                               gst_bin_add(GST_BIN(encodebin), encodebin->video_encode);
+                       }
+                       break;
+               }
+               case PROP_AUDIO_ENC: 
+               {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->audio_encode);
+                               encodebin->audio_encode = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->audio_encode));
+                               gst_bin_add(GST_BIN(encodebin), encodebin->audio_encode);
+                       }
+                       break;
+               }
+               case PROP_IMAGE_ENC: {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile < GST_ENCODE_BIN_PROFILE_IMAGE) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->image_encode);
+                               encodebin->image_encode = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->image_encode));
+                               gst_bin_add(GST_BIN(encodebin), encodebin->image_encode);
+                       }
+                       break;
+               }
+               case PROP_MUX: {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->mux);
+                               encodebin->mux = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->mux));
+                               gst_bin_add(GST_BIN(encodebin), encodebin->mux);
+                       }
+                       break;
+               }
+               case PROP_VIDEO_CONV: {
+                       GstElement *newelement = g_value_get_object (value);
+                       if(encodebin->profile == GST_ENCODE_BIN_PROFILE_AUDIO) {
+                               GST_WARNING_OBJECT(encodebin, "Profile isn't match, change profile first!");
+                               break;
+                       }
+                       if(newelement != NULL) {
+                               gst_encode_bin_remove_element(encodebin, encodebin->color_space);
+                               encodebin->color_space = newelement;
+                               gst_object_ref_sink (GST_OBJECT_CAST (encodebin->color_space));
+                               gst_bin_add(GST_BIN(encodebin), encodebin->color_space);
+                       }
+                       break;
+               }
+               case PROP_USE_VIDEO_TOGGLE:
+                       encodebin->use_video_toggle = g_value_get_boolean( value );
+                       break;
+               default:
+                       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+                       break;
+       }
+}
+
+static GstPad *
+gst_encode_bin_request_new_pad (GstElement *element, GstPadTemplate *templ,
+        const gchar* name, const GstCaps *caps)
+{
+       GstEncodeBin *encodebin = NULL;
+       GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
+       GstPad *pad = NULL;
+
+       g_return_val_if_fail (templ != NULL, NULL);
+
+       if (templ->direction != GST_PAD_SINK) {
+               GST_WARNING_OBJECT (GST_IS_ENCODE_BIN (element), "encodebin: request pad that is not a SINK pad\n");
+               return NULL;
+       }
+
+       g_return_val_if_fail (GST_IS_ENCODE_BIN (element), NULL);
+
+       encodebin = GST_ENCODE_BIN (element);
+  
+ /* FIXME */
+       if (templ == gst_element_class_get_pad_template (klass, "audio")) {
+               if (encodebin->profile <= GST_ENCODE_BIN_PROFILE_AUDIO) {
+                       gst_encode_bin_init_audio_elements(element, NULL); //??
+                       
+                       if(encodebin->audio_sinkpad == NULL)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->audio_queue, "sink");
+                               encodebin->audio_sinkpad = gst_ghost_pad_new ("audio", pad);
+                               gst_object_unref(pad);
+                               pad = NULL;
+                       }
+                       else
+                       {
+                               GST_WARNING_OBJECT (GST_IS_ENCODE_BIN (element), "encodebin: audio pad is aleady existed, return existing audio pad\n");                        
+                               return encodebin->audio_sinkpad;
+                       }
+                       
+                       gst_element_add_pad (element, encodebin->audio_sinkpad);
+                       return encodebin->audio_sinkpad;
+               } else
+                       return NULL;
+       } else if (templ == gst_element_class_get_pad_template (klass, "video")) {
+               if (encodebin->profile == GST_ENCODE_BIN_PROFILE_AV) {
+                       gst_encode_bin_init_video_elements(element, NULL); //??
+
+                       if(encodebin->video_sinkpad == NULL)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->video_queue, "sink");
+                               encodebin->video_sinkpad = gst_ghost_pad_new ("video", pad);        
+                               gst_object_unref(pad);
+                               pad = NULL;
+                       }
+                       else
+                       {
+                               GST_WARNING_OBJECT (GST_IS_ENCODE_BIN (element), "encodebin: video pad is aleady existed, return existing video pad\n");                                                
+                               return encodebin->video_sinkpad;
+                       }
+                       
+                       gst_element_add_pad (element, encodebin->video_sinkpad);
+                       return encodebin->video_sinkpad;
+               } else if (encodebin->profile == GST_ENCODE_BIN_PROFILE_IMAGE) {
+                       gst_encode_bin_init_image_elements(element, NULL); //??
+
+                       if(encodebin->image_sinkpad == NULL)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->image_queue, "sink");
+                               encodebin->image_sinkpad = gst_ghost_pad_new ("image", pad);
+                               gst_object_unref(pad);
+                               pad = NULL;                             
+                       }
+                       else
+                       {
+                               GST_WARNING_OBJECT (GST_IS_ENCODE_BIN (element), "encodebin: image pad is aleady existed, return existing image pad\n");                        
+                               return encodebin->image_sinkpad;
+                       }
+                       
+                       gst_element_add_pad (element, encodebin->image_sinkpad);
+                       return encodebin->image_sinkpad;
+               } else
+                       return NULL;
+       } else {
+               if (encodebin->profile == GST_ENCODE_BIN_PROFILE_IMAGE) {
+                       gst_encode_bin_init_image_elements(element, NULL); //??
+                       
+                       if(encodebin->image_sinkpad == NULL)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->image_queue, "sink");
+                               encodebin->image_sinkpad = gst_ghost_pad_new ("image", pad);
+                               gst_object_unref(pad);
+                               pad = NULL;                             
+                       }
+                       else
+                       {
+                               GST_WARNING_OBJECT (GST_IS_ENCODE_BIN (element), "encodebin: image pad is aleady existed, return existing image pad\n");                        
+                               return encodebin->image_sinkpad;
+                       }
+                       
+                       gst_element_add_pad (element, encodebin->image_sinkpad);
+                       return encodebin->image_sinkpad;
+               } else
+                       return NULL;        
+       }  
+}
+
+static void
+gst_encode_bin_class_init (GstEncodeBinClass *klass)
+{
+       GObjectClass *gobject_klass;
+       GstElementClass *gstelement_klass;
+       GstBinClass *gstbin_klass;
+       GParamSpec *spec = NULL;
+
+       gobject_klass = (GObjectClass *) klass;
+       gstelement_klass = (GstElementClass *) klass;
+       gstbin_klass = (GstBinClass *) klass;
+       
+       parent_class = g_type_class_peek_parent (klass);
+
+       gobject_klass->get_property = gst_encode_bin_get_property;
+       gobject_klass->set_property = gst_encode_bin_set_property;
+       gobject_klass->dispose = GST_DEBUG_FUNCPTR (gst_encode_bin_dispose);    
+       gobject_klass->finalize = GST_DEBUG_FUNCPTR (gst_encode_bin_finalize);
+
+
+       spec = g_param_spec_enum("profile", "PROFILE", "Profile of the media to record",
+                                GST_TYPE_ENCODE_BIN_PROFILE, DEFAULT_PROP_PROFILE,
+                                G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property (gobject_klass, PROP_PROFILE, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_int("high-speed-fps", "high speed rec. fps", "framerate for high speed recording",
+                               0, G_MAXINT, DEFAULT_PROP_HIGH_SPEED, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property (gobject_klass, PROP_HIGH_SPEED, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_string("venc-name", "video encoder name", "the name of video encoder to use",
+                                  DEFAULT_PROP_VENC_NAME, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property (gobject_klass, PROP_VENC_NAME, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_string("aenc-name", "audio encoder name", "the name of audio encoder to use",
+                                  DEFAULT_PROP_AENC_NAME, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property (gobject_klass, PROP_AENC_NAME, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_string("ienc-name", "image encoder name", "the name of image encoder to use",
+                                  DEFAULT_PROP_IENC_NAME, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_IENC_NAME, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_string("mux-name", "muxer name", "the name of muxer to use",
+                                  DEFAULT_PROP_MUX_NAME, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_MUX_NAME, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_string("vconv-name", "Video converter name", "the name of video color converter to use",
+                                  DEFAULT_PROP_VCONV_NAME, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_VCONV_NAME, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boxed("vcaps", "caps for video","caps for video recording",
+                                 GST_TYPE_CAPS, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_VCAPS, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boxed("acaps", "caps for audio","caps for audio recording",
+                                 GST_TYPE_CAPS, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_ACAPS, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boxed("icaps", "caps for image","caps for image stillshot",
+                                 GST_TYPE_CAPS, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_ICAPS, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("auto-audio-convert", "auto audio convert",
+                                   "Support for auto audio convert", TRUE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_AUTO_AUDIO_CONVERT, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("auto-audio-resample", "auto audio resample",
+                                   "Support for auto audio resample", TRUE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_AUTO_AUDIO_RESAMPLE, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("auto-colorspace", "auto colorspace",
+                                   "Support for auto colorspace", TRUE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_AUTO_COLORSPACE, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("block", "stream block",
+                                   "Support for stream block", FALSE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_BLOCK, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("runtime-pause", "recording pause",
+                                   "Support for recording pause/resume", FALSE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_PAUSE, spec);
+               spec = NULL;
+       }
+
+#if 0
+       spec = g_param_spec_boolean("use-venc-queue", "use queue between venc and mux",
+                                   "add queue between venc and mux(only for custom optimization)", FALSE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property (gobject_klass, PROP_VENC_QUEUE, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("use-aenc-queue", "use queue between aenc and mux",
+                                   "add queue between aenc and mux(only for custom optimization)", FALSE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property (gobject_klass, PROP_AENC_QUEUE, spec);
+               spec = NULL;
+       }
+#else
+       spec = g_param_spec_object("use-venc-queue", "Video Encoder queue",
+                                  "add queue between venc and mux(only for custom optimization)",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_VENC_QUEUE, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_object("use-aenc-queue", "Audio Encoder queue",
+                                  "add queue between aenc and mux(only for custom optimization)",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_AENC_QUEUE, spec);
+               spec = NULL;
+       }
+#endif
+
+       spec = g_param_spec_object("video-encode", "Video Encoder",
+                                  "the video encoder element to use",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_VIDEO_ENC, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_object("audio-encode", "Audio Encoder",
+                                  "the audio encoder element to use",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_AUDIO_ENC, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_object("image-encode", "Image Encoder",
+                                  "the Image encoder element to use",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_IMAGE_ENC, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_object("mux", "Muxer",
+                                  "the muxer element to use",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_MUX, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_object("video-convert", "Video converter",
+                                  "the video converter element to use",
+                                  GST_TYPE_ELEMENT, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_VIDEO_CONV, spec);
+               spec = NULL;
+       }
+
+       spec = g_param_spec_boolean("use-video-toggle", "Use video toggle",
+                                   "Use video toggle while AV recording", TRUE, G_PARAM_READWRITE);
+       if (spec) {
+               g_object_class_install_property(gobject_klass, PROP_USE_VIDEO_TOGGLE, spec);
+               spec = NULL;
+       }
+
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE
+       gst_encode_bin_signals[SIGNAL_STREAM_BLOCK] =
+               g_signal_new ("stream-block", G_TYPE_FROM_CLASS (klass),
+               G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstEncodeBinClass, stream_block), 
+               NULL, NULL, g_cclosure_marshal_VOID__BOOLEAN, G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
+
+       gst_encode_bin_signals[SIGNAL_STREAM_UNBLOCK] =
+               g_signal_new ("stream-unblock", G_TYPE_FROM_CLASS (klass),
+               G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstEncodeBinClass, stream_unblock), 
+               NULL, NULL, g_cclosure_marshal_VOID__BOOLEAN, G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
+
+       gst_encode_bin_signals[SIGNAL_STREAM_PAUSE] =
+               g_signal_new ("stream-pause", G_TYPE_FROM_CLASS (klass),
+               G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstEncodeBinClass, stream_pause), 
+               NULL, NULL, g_cclosure_marshal_VOID__BOOLEAN, G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
+
+       gst_encode_bin_signals[SIGNAL_STREAM_RESUME] =
+               g_signal_new ("stream-resume", G_TYPE_FROM_CLASS (klass),
+               G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstEncodeBinClass, stream_resume), 
+               NULL, NULL, g_cclosure_marshal_VOID__BOOLEAN, G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
+#endif
+
+       gst_element_class_add_pad_template (gstelement_klass,
+         gst_static_pad_template_get (&encoder_bin_src_template));
+       gst_element_class_add_pad_template (gstelement_klass,
+         gst_static_pad_template_get (&encoder_bin_audio_sink_template));
+       gst_element_class_add_pad_template (gstelement_klass,
+         gst_static_pad_template_get (&encoder_bin_video_sink_template));
+       gst_element_class_add_pad_template (gstelement_klass,
+         gst_static_pad_template_get (&encoder_bin_image_sink_template));
+
+       gst_element_class_set_static_metadata(gstelement_klass, "Samsung Electronics Co. Encoder Bin",
+                                                        "Generic/Bin/Encoder",
+                                                        "Autoplug and encode to muxed media",
+                                                        "Jeonghoon Park <jh1979.park@samsung.com>, Wonhyung Cho <wh01.cho@samsung.com>, Sangho Park <sangho.g.park@samsung.com>");
+
+       gstelement_klass->request_new_pad =
+         GST_DEBUG_FUNCPTR (gst_encode_bin_request_new_pad);
+       gstelement_klass->release_pad = 
+         GST_DEBUG_FUNCPTR (gst_encode_bin_release_pad);
+       gstelement_klass->change_state =
+         GST_DEBUG_FUNCPTR (gst_encode_bin_change_state);
+}
+
+static void
+gst_encode_bin_init (GstEncodeBin *encodebin)
+{
+       encodebin->mutex = g_mutex_new();
+
+       if (encodebin->srcpad == NULL) {
+               encodebin->srcpad = gst_ghost_pad_new_no_target ("src", GST_PAD_SRC);
+               gst_element_add_pad (GST_ELEMENT(encodebin), encodebin->srcpad);
+       }
+
+       encodebin->video_sinkpad = NULL;
+       encodebin->audio_sinkpad = NULL;
+       encodebin->image_sinkpad = NULL;
+       encodebin->mux_audio_sinkpad = NULL;
+       encodebin->mux_video_sinkpad = NULL;
+       
+       encodebin->profile = DEFAULT_PROP_PROFILE;
+       encodebin->fps = 0;
+       encodebin->high_speed_fps = DEFAULT_PROP_HIGH_SPEED;
+       encodebin->multiple = 1;
+
+       encodebin->auto_audio_convert = TRUE;
+       encodebin->auto_audio_resample = TRUE;
+       encodebin->auto_color_space = TRUE;
+       encodebin->block = FALSE;
+       encodebin->pause= FALSE;
+       encodebin->use_video_toggle = TRUE;
+       encodebin->use_venc_queue= FALSE;
+       encodebin->use_aenc_queue= FALSE;
+
+       encodebin->venc_name = g_strdup(DEFAULT_PROP_VENC_NAME);
+       encodebin->aenc_name = g_strdup(DEFAULT_PROP_AENC_NAME);
+       encodebin->ienc_name = g_strdup(DEFAULT_PROP_IENC_NAME);
+       encodebin->mux_name = g_strdup(DEFAULT_PROP_MUX_NAME);
+       encodebin->vconv_name = g_strdup(DEFAULT_PROP_VCONV_NAME);
+
+       encodebin->vcaps = gst_caps_new_any ();
+       encodebin->acaps = gst_caps_new_any ();
+       encodebin->icaps = gst_caps_new_any ();
+
+       encodebin->audio_queue = NULL;
+       encodebin->video_queue = NULL;
+       encodebin->video_encode_queue = NULL;
+       encodebin->image_queue = NULL;
+
+       encodebin->audio_encode = NULL;
+       encodebin->video_encode = NULL;
+       encodebin->image_encode = NULL;
+
+       encodebin->vcapsfilter = NULL;
+       encodebin->acapsfilter = NULL;
+       encodebin->icapsfilter = NULL;
+
+       encodebin->video_toggle = NULL;
+       encodebin->image_toggle = NULL;
+       encodebin->color_space = NULL;
+       encodebin->audio_conv = NULL;
+       encodebin->audio_sample = NULL;
+
+       encodebin->mux = NULL;
+
+       encodebin->paused_time = 0;
+       encodebin->total_offset_time = 0;
+
+       encodebin->vsink_probeid = 0;
+       encodebin->vsink_hs_probeid = 0;
+       encodebin->asink_probeid = 0;
+       encodebin->veque_sig_id = 0;
+       encodebin->aeque_sig_id = 0;
+}
+
+static void
+gst_encode_bin_dispose (GObject * object)
+{
+       GstEncodeBin *encodebin = GST_ENCODE_BIN (object);
+
+       g_free(encodebin->venc_name);
+       encodebin->venc_name = NULL;
+
+       g_free(encodebin->aenc_name);
+       encodebin->aenc_name = NULL;    
+
+       g_free(encodebin->ienc_name);
+       encodebin->ienc_name = NULL;
+
+       g_free(encodebin->mux_name);
+       encodebin->mux_name = NULL;
+
+       g_free(encodebin->vconv_name);
+       encodebin->vconv_name = NULL;
+
+       gst_caps_replace (&encodebin->vcaps, NULL);
+       gst_caps_replace (&encodebin->acaps, NULL);
+       gst_caps_replace (&encodebin->icaps, NULL);
+
+       if (encodebin->srcpad != NULL) {
+               gst_element_remove_pad(GST_ELEMENT(encodebin), encodebin->srcpad);
+               encodebin->srcpad = NULL;
+       }
+
+       G_OBJECT_CLASS (parent_class)->dispose (object);
+
+       encodebin->video_sinkpad = NULL;
+       encodebin->audio_sinkpad = NULL;
+       encodebin->image_sinkpad = NULL;
+       encodebin->mux_audio_sinkpad = NULL;
+       encodebin->mux_video_sinkpad = NULL;
+
+       encodebin->audio_queue = NULL;
+       encodebin->video_queue = NULL;
+       encodebin->image_queue = NULL;
+
+       encodebin->audio_encode = NULL;
+       encodebin->video_encode = NULL;
+       encodebin->video_encode_queue = NULL;
+       encodebin->image_encode = NULL;
+
+       encodebin->vcapsfilter = NULL;
+       encodebin->acapsfilter = NULL;
+       encodebin->icapsfilter = NULL;
+
+       encodebin->video_toggle = NULL;
+       encodebin->image_toggle = NULL;
+       encodebin->color_space = NULL;
+       encodebin->audio_conv = NULL;
+       encodebin->audio_sample = NULL;
+       
+       if (encodebin->mux && GST_IS_ELEMENT(encodebin->mux)) {
+               int remain_count= 0;
+               remain_count = GST_OBJECT_REFCOUNT_VALUE(encodebin->mux);
+               while (remain_count) {
+                       gst_object_unref(encodebin->mux);
+                       remain_count--;
+               }
+       }
+
+       encodebin->mux = NULL;
+}
+
+static void
+gst_encode_bin_finalize (GObject * object)
+{
+       GstEncodeBin *encodebin = GST_ENCODE_BIN (object);
+
+       g_mutex_free (encodebin->mutex);
+
+       G_OBJECT_CLASS (parent_class)->finalize (object);
+}
+
+static GstStateChangeReturn
+gst_encode_bin_change_state (GstElement * element, GstStateChange transition)
+{
+       GstStateChangeReturn ret;
+       GstEncodeBin *encode_bin;
+
+       encode_bin = GST_ENCODE_BIN (element);
+
+       switch (transition) {
+               case GST_STATE_CHANGE_NULL_TO_READY:
+                       gst_encode_bin_link_elements(encode_bin);
+                       break;
+               case GST_STATE_CHANGE_READY_TO_PAUSED:
+                       /* reset time related values */
+                       encode_bin->paused_time = 0;
+                       encode_bin->total_offset_time = 0;
+                       break;
+               case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+                       break;
+               case GST_STATE_CHANGE_PAUSED_TO_READY:
+                       break;
+               default:
+                       break;
+       }
+
+       ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
+
+       switch (transition) {
+       case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+               break;
+       case GST_STATE_CHANGE_PAUSED_TO_READY:
+               break;
+       case GST_STATE_CHANGE_READY_TO_NULL:
+               gst_encode_bin_unlink_elements(encode_bin);     
+               break;          
+       default:
+               break;
+       }
+
+//  if (ret == GST_STATE_CHANGE_FAILURE)
+//    goto done;
+//done:
+       return ret;
+}
+
+static void
+gst_encode_bin_release_all_pads (GstEncodeBin *encodebin)
+{
+       gst_element_remove_pad(GST_ELEMENT(encodebin), encodebin->video_sinkpad);
+       gst_element_remove_pad(GST_ELEMENT(encodebin), encodebin->audio_sinkpad);
+       gst_element_remove_pad(GST_ELEMENT(encodebin), encodebin->image_sinkpad);
+}
+
+static void
+gst_encode_bin_release_pad (GstElement * element, GstPad * pad)
+{
+       GstEncodeBin *encodebin = GST_ENCODE_BIN (element);
+       GstPad *muxpad = NULL;
+       
+       if(!pad_compare_name(pad, "video")) {
+#if 0          
+               gst_encode_bin_remove_element(encodebin, encodebin->video_queue);
+               encodebin->video_queue = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->video_toggle);
+               encodebin->video_toggle = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->color_space);
+               encodebin->color_space = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->vcapsfilter);
+               encodebin->vcapsfilter = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->video_encode_queue);
+               encodebin->video_encode_queue =  NULL;          
+               gst_encode_bin_remove_element(encodebin, encodebin->video_encode);
+               encodebin->video_encode =  NULL;
+
+               gst_element_release_request_pad(encodebin->mux, encodebin->mux_video_sinkpad);  
+               encodebin->mux_video_sinkpad = NULL;
+
+               if(encodebin->mux_audio_sinkpad == NULL) {
+                       gst_encode_bin_remove_element(encodebin, encodebin->mux);
+                       encodebin->mux = NULL;
+               }
+               else 
+               {
+                       encodebin->mux_audio_sinkpad = NULL;
+               }
+#endif 
+
+               if(encodebin->mux_video_sinkpad != NULL)
+               {       
+                       gst_element_release_request_pad(encodebin->mux, encodebin->mux_video_sinkpad);
+                       encodebin->mux_video_sinkpad = NULL;
+               }
+               
+               gst_pad_set_active (pad, FALSE); //??
+               gst_element_remove_pad(element, pad);
+               encodebin->video_sinkpad = NULL;
+       } else if(!pad_compare_name(pad, "audio")) {
+#if 0
+               gst_encode_bin_remove_element(encodebin, encodebin->audio_queue);
+               encodebin->audio_queue = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->audio_sample);
+               encodebin->audio_sample = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->audio_conv);
+               encodebin->audio_conv = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->acapsfilter);
+               encodebin->acapsfilter = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->audio_encode_queue);
+               encodebin->audio_encode_queue =  NULL;                  
+               gst_encode_bin_remove_element(encodebin, encodebin->audio_encode);
+               encodebin->audio_encode = NULL;
+
+               encodebin->mux_audio_sinkpad;
+               gst_element_release_request_pad(encodebin->mux, encodebin->mux_audio_sinkpad);
+               muxpad = NULL;
+
+               if(encodebin->mux_video_sinkpad == NULL) {
+                       gst_encode_bin_remove_element(encodebin, encodebin->mux);
+                       encodebin->mux = NULL;
+               }
+               else 
+               {
+                       encodebin->mux_video_sinkpad = NULL;
+               }
+#endif         
+               if(encodebin->mux_audio_sinkpad != NULL)
+               {
+                       gst_element_release_request_pad(encodebin->mux, encodebin->mux_audio_sinkpad);
+//                     gst_object_unref(encodebin->mux_audio_sinkpad);         //***
+                       encodebin->mux_audio_sinkpad = NULL;
+               }
+
+               gst_pad_set_active (pad, FALSE); //??           
+               gst_element_remove_pad(element, pad);
+               encodebin->audio_sinkpad = NULL;
+       } else {
+#if 0
+               gst_encode_bin_remove_element(encodebin, encodebin->image_queue);
+               encodebin->image_queue = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->image_toggle);
+               encodebin->image_toggle = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->color_space);
+               encodebin->color_space = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->icapsfilter);
+               encodebin->icapsfilter = NULL;
+               gst_encode_bin_remove_element(encodebin, encodebin->image_encode);
+               encodebin->image_encode = NULL;
+#endif         
+               gst_pad_set_active (pad, FALSE); //??           
+               gst_element_remove_pad(element, pad);
+               encodebin->image_sinkpad = NULL;
+       }
+}
+
+static gint
+pad_compare_name (GstPad * pad1, const gchar * name)
+{
+       gint result;
+
+       GST_OBJECT_LOCK (pad1);
+               result = strcmp (GST_PAD_NAME (pad1), name);
+       GST_OBJECT_UNLOCK (pad1);
+
+       return result;
+}
+
+static gboolean 
+gst_encode_bin_add_element_by_name (GstEncodeBin *encodebin, GstEncodeBinElement type, const gchar *name)
+{
+       switch(type) {
+               case ENCODEBIN_ELEMENT_VENC:
+                       encodebin->video_encode = gst_element_factory_make (name, "video_encode");
+                       if(encodebin->video_encode != NULL) {
+                               gst_bin_add(GST_BIN(encodebin), encodebin->video_encode);
+                               g_free(encodebin->venc_name);
+                               encodebin->venc_name = NULL;
+                       } else {
+                               goto element_make_fail;
+                       }
+                       break;
+               case ENCODEBIN_ELEMENT_AENC:
+                       encodebin->audio_encode = gst_element_factory_make (name, "audio_encode");
+                       if(encodebin->audio_encode != NULL) {
+                               gst_bin_add(GST_BIN(encodebin), encodebin->audio_encode);
+                               g_free(encodebin->aenc_name);
+                               encodebin->aenc_name = NULL;
+                       } else {
+                               goto element_make_fail;
+                       }
+                       break;
+               case ENCODEBIN_ELEMENT_IENC:
+                       encodebin->image_encode = gst_element_factory_make (name, "image_encode");
+                       if(encodebin->image_encode != NULL) {
+                               gst_bin_add(GST_BIN(encodebin), encodebin->image_encode);
+                               g_free(encodebin->ienc_name);
+                               encodebin->ienc_name = NULL;
+                       } else {
+                               goto element_make_fail;
+                       }
+                       break;
+               case ENCODEBIN_ELEMENT_MUX:
+                       encodebin->mux = gst_element_factory_make (name, "mux");
+                       if(encodebin->mux != NULL) {
+                               gst_bin_add(GST_BIN(encodebin), encodebin->mux);
+                               g_free(encodebin->mux_name);
+                               encodebin->mux_name = NULL;
+                       } else {
+                               goto element_make_fail;
+                       }
+                       break;
+               case ENCODEBIN_ELEMENT_VIDEO_CONV:
+                       encodebin->color_space = gst_element_factory_make(name, "video_convert");
+                       if (encodebin->color_space != NULL) {
+                               gst_bin_add(GST_BIN(encodebin), encodebin->color_space);
+                               g_free(encodebin->vconv_name);
+                               encodebin->vconv_name = NULL;
+                       } else {
+                               goto element_make_fail;
+                       }
+                       break;
+               default:
+                       GST_WARNING_OBJECT(encodebin, "Invalid element type = %d", type);
+                       break;
+       }
+
+       return TRUE;
+       
+element_make_fail:
+       GST_WARNING_OBJECT(encodebin, "no such element factory \"%s\"!", name);
+       return FALSE;
+}
+
+#if 0 //disable unused function
+static gboolean 
+gst_encode_bin_change_profile(GstEncodeBin *encodebin, gboolean newprofile)
+{
+
+  gst_encode_bin_remove_element(encodebin, encodebin->video_encode);
+  gst_encode_bin_remove_element(encodebin, encodebin->audio_encode);
+  gst_encode_bin_remove_element(encodebin, encodebin->image_encode);
+  gst_encode_bin_remove_element(encodebin, encodebin->mux);
+
+  switch (newprofile) {
+    case GST_ENCODE_BIN_PROFILE_AV :
+       encodebin->audio_encode = gst_element_factory_make (encodebin->aenc_name, "audio_encode");
+       encodebin->video_encode = gst_element_factory_make (encodebin->venc_name,"video_encode");
+       encodebin->mux = gst_element_factory_make (encodebin->mux_name,"mux");
+
+         gst_bin_add_many (GST_BIN (encodebin),
+                           encodebin->audio_encode,
+                           encodebin->video_encode,
+                           encodebin->mux,
+                           NULL);
+       break;
+    case GST_ENCODE_BIN_PROFILE_AUDIO :
+       encodebin->audio_encode = gst_element_factory_make (encodebin->aenc_name, "audio_encode");
+       encodebin->mux = gst_element_factory_make (encodebin->mux_name,"mux");
+
+         gst_bin_add_many (GST_BIN (encodebin),
+                           encodebin->audio_encode,
+                           encodebin->mux,
+                           NULL);
+       break;
+    case GST_ENCODE_BIN_PROFILE_IMAGE :
+       encodebin->image_encode = gst_element_factory_make (encodebin->ienc_name,"image_encode");
+
+       gst_bin_add_many (GST_BIN (encodebin),
+                           encodebin->image_encode,
+                           NULL);
+       break;
+    default:
+      GST_WARNING_OBJECT(encodebin, "Invalid profile number = %d", encodebin->profile);
+      return FALSE;
+      break;
+       }
+  return TRUE;
+
+}
+
+static void 
+gst_encode_bin_replace_element (GstEncodeBin *encodebin, gint type, GstElement * newelement)
+{
+  if(newelement == NULL) {
+       GST_ERROR_OBJECT(encodebin, "some elements are null\n");
+       return;
+  }
+  switch(type) {
+    case PROP_VIDEO_ENC:
+       gst_encode_bin_remove_element(encodebin, encodebin->video_encode);
+       encodebin->video_encode = newelement;
+       gst_object_ref (encodebin->video_encode);
+       gst_object_sink (GST_OBJECT_CAST (encodebin->video_encode)); // take ownership ??
+       gst_bin_add(GST_BIN(encodebin),  encodebin->video_encode);
+       break;
+    case PROP_AUDIO_ENC:
+       gst_encode_bin_remove_element(encodebin, encodebin->audio_encode);
+       encodebin->audio_encode = newelement;
+       gst_object_ref (encodebin->audio_encode);
+       gst_object_sink (GST_OBJECT_CAST (encodebin->audio_encode));
+       gst_bin_add(GST_BIN(encodebin),  encodebin->audio_encode);
+       break;  
+    case PROP_IMAGE_ENC:
+       gst_encode_bin_remove_element(encodebin, encodebin->image_encode);
+       encodebin->image_encode = newelement;
+       gst_object_ref (encodebin->image_encode);
+       gst_object_sink (GST_OBJECT_CAST (encodebin->image_encode));
+       gst_bin_add(GST_BIN(encodebin), encodebin->image_encode);
+       break;
+    case PROP_MUX:
+       gst_encode_bin_remove_element(encodebin, encodebin->mux);
+       encodebin->mux = newelement;
+       gst_object_ref (encodebin->mux);
+       gst_object_sink (GST_OBJECT_CAST (encodebin->mux));
+       gst_bin_add(GST_BIN(encodebin),  encodebin->mux);
+       break;
+    default:
+       GST_WARNING_OBJECT(encodebin, "Invalid type = %d", type);
+      return;
+       break;
+  }
+}
+
+static gboolean 
+gst_encode_bin_replace_element_by_name(GstEncodeBin *encodebin, GstEncodeBinElement type, const gchar *name)
+{
+       GstPad *sink1, *sink2, *src, *peersink1, *peersink2, *peersrc;
+       
+       switch(type) {
+               case ENCODEBIN_ELEMENT_VENC:
+                       if(encodebin->video_encode == NULL) {
+                               encodebin->video_encode = gst_element_factory_make (name, "video_encode");
+                               gst_bin_add(GST_BIN(encodebin), encodebin->video_encode);
+                       } else {
+                               sink1 = gst_element_get_static_pad(encodebin->video_encode, "sink");
+                               src = gst_element_get_static_pad(encodebin->video_encode, "src");
+                               if(sink1 != NULL) {
+                                       peersink1 = gst_pad_get_peer(sink1);
+                                       if(peersink1 != NULL) {
+                                               if(!gst_pad_unlink(peersink1, sink1)) {
+                                                       goto unlink_fail;
+                                               }
+                                       }
+                               }
+
+                               if(src !=NULL) {
+                                       peersrc = gst_pad_get_peer(src);
+                                       if(peersrc != NULL) {
+                                               if(!gst_pad_unlink(src, peersrc)) {
+                                                       goto unlink_fail;
+                                               }
+                                       }
+                               }
+                               
+                               if(gst_encode_bin_remove_element(encodebin, encodebin->video_encode)) {
+                                       if(encodebin->video_encode = gst_element_factory_make (name, "video_encode") != NULL) {
+                                               gst_bin_add(GST_BIN(encodebin), encodebin->video_encode);
+                                               if(peersink1 != NULL) {
+                                                       if(!gst_pad_link(peersink1, gst_element_get_pad(encodebin->video_encode, "sink"))) {
+                                                               goto link_fail;
+                                                       }
+                                               }
+                                               
+                                               if(peersrc != NULL) {
+                                                       if(!gst_pad_link(gst_element_get_pad(encodebin->video_encode, "src"), peersrc)) {
+                                                               goto link_fail;
+                                                       }
+                                               }
+                                       } else {
+                                               GST_ERROR_OBJECT(encodebin, "gst_encode_bin_replace_element_by_name() new element[%d] make fail\n", type);
+                                               return FALSE;                                   
+                                       }
+                               } else {
+                                       GST_ERROR_OBJECT(encodebin, "gst_encode_bin_replace_element_by_name() old element[%d] remove fail\n", type);
+                                       return FALSE;
+                               }                               
+                       }                       
+                       break;
+               case ENCODEBIN_ELEMENT_AENC:
+                       break;
+               case ENCODEBIN_ELEMENT_IENC:
+                       break;
+               case ENCODEBIN_ELEMENT_MUX:
+                       break;
+               default :
+                       GST_WARNING_OBJECT(encodebin, "Invalid element type = %d", type);
+                       break;
+       }
+       gst_object_unref(sink1);
+       gst_object_unref(sink2);
+       gst_object_unref(src);
+       gst_object_unref(peersink1);    
+       gst_object_unref(peersink2);    
+       gst_object_unref(peersrc);              
+       return TRUE;
+
+unlink_fail:
+       gst_object_unref(sink1);
+       gst_object_unref(sink2);
+       gst_object_unref(src);
+       gst_object_unref(peersink1);    
+       gst_object_unref(peersink2);    
+       gst_object_unref(peersrc);      
+       GST_ERROR_OBJECT(encodebin, "gst_encode_bin_replace_element_by_name() old element[%d] unlink fail\n", type);
+       return FALSE;
+
+       
+link_fail:
+       gst_object_unref(sink1);
+       gst_object_unref(sink2);
+       gst_object_unref(src);
+       gst_object_unref(peersink1);    
+       gst_object_unref(peersink2);    
+       gst_object_unref(peersrc);      
+       GST_ERROR_OBJECT(encodebin, "gst_encode_bin_replace_element_by_name() new element[%d] link fail\n", type);
+       return FALSE;                   
+}
+
+static gboolean 
+gst_encode_bin_replace_element_by_object(GstEncodeBin *encodebin, GstEncodeBinElement type, GstElement * element)
+{
+       GstPad *sink1, *sink2, *src, *peersink1, *peersink2, *peersrc;
+       
+       switch(type)
+               case ENCODEBIN_ELEMENT_VENC:
+                       if(encodebin->video_encode == NULL) {
+                               encodebin->video_encode = element
+                       }
+                       break;
+               case ENCODEBIN_ELEMENT_AENC:
+                       break;
+               case ENCODEBIN_ELEMENT_IENC:
+                       break;
+               case ENCODEBIN_ELEMENT_MUX:
+                       break;
+               default :
+                       GST_WARNING_OBJECT (encodebin,"Invalid element type = %d", type);
+                       break;
+}
+#endif //disable unused function
+
+static gboolean 
+gst_encode_bin_remove_element (GstEncodeBin *encodebin, GstElement * element)
+{
+       GstObject *parent;
+       gchar *ename = NULL;
+       GST_INFO_OBJECT (encodebin, "gst_encode_bin_remove_element");
+
+       if (element == NULL) {
+               GST_INFO_OBJECT (encodebin, "element is already NULL");
+               return TRUE;
+       }
+
+       gst_element_set_state (element, GST_STATE_NULL);
+       parent = gst_element_get_parent (element);
+
+       if (parent != NULL) {
+               if(!gst_bin_remove (GST_BIN_CAST (parent), element)) {
+                       gst_object_unref (parent);
+                       ename = gst_element_get_name (element);
+                       GST_ERROR_OBJECT (encodebin, "gst_encode_bin_remove_element() [%s] remove fail", ename);
+                       g_free (ename);
+                       return FALSE;
+               } else {
+                       gst_object_unref(parent);
+               }
+       } else {
+               gst_object_unref(element);
+       }
+
+       return TRUE;
+  }
+
+static gboolean 
+gst_encode_bin_link_elements (GstEncodeBin *encodebin)  // need to return ????
+{
+       GstPad *srcpad = NULL, *sinkpad = NULL;
+       switch(encodebin->profile) {
+               case GST_ENCODE_BIN_PROFILE_AV :
+                       if (!gst_caps_is_any(encodebin->vcaps)) {
+                               gchar *caps_str = NULL;
+                               caps_str = gst_caps_to_string(encodebin->vcaps);
+                               if (caps_str) {
+                                       GST_INFO_OBJECT(encodebin, "vconv caps [%s]", caps_str);
+                                       g_free(caps_str);
+                                       caps_str = NULL;
+                               }
+
+                               g_object_set(encodebin->vcapsfilter, "caps", encodebin->vcaps, NULL);
+                       }
+
+                       if (encodebin->auto_color_space) {
+                               if(encodebin->color_space == NULL) {
+                                       encodebin->color_space = gst_element_factory_make (encodebin->vconv_name, "video_convert");
+                                       gst_bin_add (GST_BIN (encodebin), encodebin->color_space);
+                               }
+
+                               srcpad = gst_element_get_static_pad(encodebin->video_queue, "src");
+                               if( encodebin->video_toggle )
+                               {
+                                       sinkpad = gst_element_get_static_pad(encodebin->video_toggle, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);
+                                       
+                                       srcpad = gst_element_get_static_pad(encodebin->video_toggle, "src");
+                               }
+                               sinkpad = gst_element_get_static_pad(encodebin->color_space, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);
+
+                               srcpad = gst_element_get_static_pad(encodebin->color_space, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->vcapsfilter, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);
+
+                               srcpad = gst_element_get_static_pad(encodebin->vcapsfilter, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->video_encode, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);
+#if 0
+                               if(encodebin->use_venc_queue)
+                               {
+                                       if(encodebin->video_encode_queue == NULL) {
+                                           encodebin->video_encode_queue  = gst_element_factory_make ("queue","video_encode_queue");
+                                           gst_bin_add (GST_BIN (encodebin), encodebin->video_encode_queue);
+                                               
+                                           ENCODER_QUEUE_SET(encodebin->video_encode_queue, 0, 0, VIDEO_ENC_QUE_TIME);
+                                           encodebin->veque_sig_id = g_signal_connect( G_OBJECT(encodebin->video_encode_queue), "overrun", 
+                                                                                                                               G_CALLBACK(queue_overun_cb), encodebin);
+                                                       
+                                       }       
+
+                                       srcpad = gst_element_get_static_pad(encodebin->video_encode, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->video_encode_queue, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);  
+                               }
+#else
+                               if(encodebin->video_encode_queue)
+                               {
+                                   ENCODER_QUEUE_SET(encodebin->video_encode_queue, 0, 0, VIDEO_ENC_QUE_TIME);
+                                   encodebin->veque_sig_id = g_signal_connect( G_OBJECT(encodebin->video_encode_queue), "overrun", 
+                                                                                                                               G_CALLBACK(queue_overun_cb), encodebin);
+#if 0
+                                   g_object_set(G_OBJECT(encodebin->video_queue), 
+                                               "max-size-bytes", (guint)0, 
+                                               "max-size-buffers", (guint)1,   
+                                               "max-size-time", (guint64)0, 
+                                               NULL); 
+#endif
+                                       srcpad = gst_element_get_static_pad(encodebin->video_encode, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->video_encode_queue, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);  
+                               }
+#endif
+                                                                
+                       }
+                       else {
+                               srcpad = gst_element_get_static_pad(encodebin->video_queue, "src");
+                               if( encodebin->video_toggle )
+                               {
+                                       sinkpad = gst_element_get_static_pad(encodebin->video_toggle, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);  
+
+                                       srcpad = gst_element_get_static_pad(encodebin->video_toggle, "src");
+                               }
+                               sinkpad = gst_element_get_static_pad(encodebin->vcapsfilter, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);  
+
+                               srcpad = gst_element_get_static_pad(encodebin->vcapsfilter, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->video_encode, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);                                  
+ #if 0
+                               if(encodebin->use_venc_queue)
+                               {
+                                       if(encodebin->video_encode_queue == NULL) {
+                                           encodebin->video_encode_queue  = gst_element_factory_make ("queue","video_encode_queue");
+                                           gst_bin_add (GST_BIN (encodebin), encodebin->video_encode_queue);
+                                               
+                                           ENCODER_QUEUE_SET(encodebin->video_encode_queue, 0, 0, VIDEO_ENC_QUE_TIME);
+                                           encodebin->veque_sig_id = g_signal_connect( G_OBJECT(encodebin->video_encode_queue), "overrun", 
+                                                                                                                               G_CALLBACK(queue_overun_cb), encodebin);                                                        
+                                       }
+                                       
+                                       srcpad = gst_element_get_static_pad(encodebin->video_encode, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->video_encode_queue, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);
+                                       
+                               }                       
+#else
+                               if(encodebin->video_encode_queue)
+                               {
+                                   ENCODER_QUEUE_SET(encodebin->video_encode_queue, 0, 0, VIDEO_ENC_QUE_TIME);
+                                   encodebin->veque_sig_id = g_signal_connect( G_OBJECT(encodebin->video_encode_queue), "overrun", 
+                                                                                                                               G_CALLBACK(queue_overun_cb), encodebin);
+#if 0                                  
+                                   g_object_set(G_OBJECT(encodebin->video_queue), 
+                                               "max-size-bytes", (guint)0, 
+                                               "max-size-buffers", (guint)1,   
+                                               "max-size-time", (guint64)0, 
+                                               NULL);                                  
+#endif
+
+                                       srcpad = gst_element_get_static_pad(encodebin->video_encode, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->video_encode_queue, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);  
+                               }
+#endif                         
+               
+                       }
+
+//                     gst_element_get_request_pad (encodebin->mux, "video_%d");
+#if 0
+                       if(encodebin->use_venc_queue)
+                       {
+                               srcpad = gst_element_get_static_pad(encodebin->video_encode_queue, "src");
+                               sinkpad = encodebin->mux_video_sinkpad = gst_encode_bin_get_mux_sink_pad(encodebin->mux, ENCODEBIN_MUX_VIDEO_SINK);
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);                          
+                       }
+#else
+                       if(encodebin->video_encode_queue)
+                       {
+                               srcpad = gst_element_get_static_pad(encodebin->video_encode_queue, "src");
+                               sinkpad = encodebin->mux_video_sinkpad = gst_encode_bin_get_mux_sink_pad(encodebin->mux, ENCODEBIN_MUX_VIDEO_SINK);
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);                          
+                       }
+#endif
+                       else
+                       {
+                               srcpad = gst_element_get_static_pad(encodebin->video_encode, "src");
+                               sinkpad = encodebin->mux_video_sinkpad = gst_encode_bin_get_mux_sink_pad(encodebin->mux, ENCODEBIN_MUX_VIDEO_SINK);
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, video_link_fail);                  
+                       }
+
+                       srcpad = gst_element_get_static_pad(encodebin->mux, "src");
+                       if(gst_ghost_pad_get_target(GST_GHOST_PAD (encodebin->srcpad)) != srcpad)
+                               gst_ghost_pad_set_target(GST_GHOST_PAD (encodebin->srcpad), srcpad);
+                       gst_object_unref(srcpad);
+                       srcpad = NULL;                  
+               
+                       /* For pause/resume control */
+//                     encodebin->vsink_probeid = gst_pad_add_data_probe (gst_element_get_static_pad (encodebin->video_queue, "sink"),
+                       sinkpad = gst_element_get_static_pad (encodebin->video_queue, "sink");
+                       encodebin->vsink_probeid = gst_pad_add_probe(sinkpad, GST_PAD_PROBE_TYPE_BUFFER, (GstPadProbeCallback)gst_encode_bin_video_probe, encodebin, NULL);
+                       gst_object_unref(sinkpad);
+                       sinkpad = NULL;
+    
+                       if(encodebin->high_speed_fps > DEFAULT_PROP_HIGH_SPEED)
+                       {
+//                             encodebin->vsink_hs_probeid = gst_pad_add_data_probe (gst_element_get_static_pad (encodebin->video_encode, "sink"),
+                               sinkpad = gst_element_get_static_pad (encodebin->video_encode, "sink");
+                               encodebin->vsink_hs_probeid = gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_BUFFER, (GstPadProbeCallback)gst_encode_bin_video_probe_hs, encodebin, NULL);
+                               gst_object_unref(sinkpad);
+                               sinkpad = NULL;                         
+                       }                       
+                       
+                       if(encodebin->audio_queue == NULL)
+                       {
+                               GST_WARNING_OBJECT(encodebin, "Audio pad isn't requested, recording video only mode");
+                               break;
+                       }
+               case GST_ENCODE_BIN_PROFILE_AUDIO :
+                       if(!gst_caps_is_any(encodebin->acaps))
+                       {                       
+                               g_object_set(encodebin->acapsfilter, "caps", encodebin->acaps, NULL);
+                       }
+                       if (encodebin->auto_audio_convert ||encodebin->auto_audio_resample) {
+                               if (!encodebin->auto_audio_convert) {
+                                       if(encodebin->audio_sample == NULL) {
+                                               encodebin->audio_sample = gst_element_factory_make ("audioresample","audio_sample");
+                                              gst_bin_add (GST_BIN (encodebin), encodebin->audio_sample);
+                                       }
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_queue, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_sample, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_sample, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->acapsfilter, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);
+
+                                       srcpad = gst_element_get_static_pad(encodebin->acapsfilter, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_encode, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                                  
+#if 0                                  
+                                       if(encodebin->use_aenc_queue)
+                                       {
+                                               if(encodebin->audio_encode_queue == NULL) {
+                                                   encodebin->audio_encode_queue  = gst_element_factory_make ("queue","audio_encode_queue");
+                                                   gst_bin_add (GST_BIN (encodebin), encodebin->audio_encode_queue);
+                                                 
+                                                  ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                                  encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                           
+                                               }       
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+                                       }                                       
+#else
+                                       if(encodebin->audio_encode_queue)
+                                       {
+                                 
+                                               ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                               encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                           
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+                                       }
+#endif
+                                       
+                               } else if (!encodebin->auto_audio_resample) {
+                                         if (encodebin->audio_conv == NULL) {
+                                               encodebin->audio_conv = gst_element_factory_make ("audioconvert","audio_conv");
+                                             gst_bin_add (GST_BIN (encodebin), encodebin->audio_conv);
+                                          }    
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_queue, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_conv, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_conv, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->acapsfilter, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);
+
+                                       srcpad = gst_element_get_static_pad(encodebin->acapsfilter, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_encode, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                                  
+#if 0                                  
+                                       if(encodebin->use_aenc_queue)
+                                       {
+                                               if(encodebin->audio_encode_queue == NULL) {
+                                                   encodebin->audio_encode_queue  = gst_element_factory_make ("queue","audio_encode_queue");
+                                                   gst_bin_add (GST_BIN (encodebin), encodebin->audio_encode_queue);
+
+                                                   ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                                  encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                                        
+                                               }
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                                          
+                               
+                                       }                                       
+#else
+                                       if(encodebin->audio_encode_queue)
+                                       {
+                                 
+                                               ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                               encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                           
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+                                       }
+#endif                                 
+                                       
+                               } else {
+                                       if(encodebin->audio_sample == NULL) {
+                                               encodebin->audio_sample = gst_element_factory_make ("audioresample","audio_sample");
+                                              gst_bin_add (GST_BIN (encodebin), encodebin->audio_sample);
+                                       }
+                                       if (encodebin->audio_conv == NULL) {
+                                               encodebin->audio_conv = gst_element_factory_make ("audioconvert","audio_conv");
+                                             gst_bin_add (GST_BIN (encodebin), encodebin->audio_conv);
+                                       }
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_queue, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_conv, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_conv, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_sample, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_sample, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->acapsfilter, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                                          
+
+                                       srcpad = gst_element_get_static_pad(encodebin->acapsfilter, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_encode, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+#if 0                                  
+                                       if(encodebin->use_aenc_queue)
+                                       {
+                                               if(encodebin->audio_encode_queue == NULL) {
+                                                   encodebin->audio_encode_queue  = gst_element_factory_make ("queue","audio_encode_queue");
+                                                   gst_bin_add (GST_BIN (encodebin), encodebin->audio_encode_queue);
+                                                       
+                                                   ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                                  encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                                
+                                               }       
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);
+                                       
+                                       }                       
+#else
+                                       if(encodebin->audio_encode_queue)
+                                       {
+                                 
+                                               ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                               encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                           
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+                                       }
+#endif                                 
+                                       
+                               }
+                       }else {
+
+                               srcpad = gst_element_get_static_pad(encodebin->audio_queue, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->acapsfilter, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                  
+
+                               srcpad = gst_element_get_static_pad(encodebin->acapsfilter, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                                  
+#if 0
+                               if(encodebin->use_aenc_queue)
+                               {
+                                       if(encodebin->audio_encode_queue == NULL) {
+                                           encodebin->audio_encode_queue  = gst_element_factory_make ("queue","audio_encode_queue");
+                                           gst_bin_add (GST_BIN (encodebin), encodebin->audio_encode_queue);
+                                               
+                                           ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                          encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                               G_CALLBACK(queue_overun_cb), encodebin);                                
+                                       }               
+
+                                       srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                       sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                       _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);                                  
+                               }                               
+#else
+                                       if(encodebin->audio_encode_queue)
+                                       {
+                                 
+                                               ENCODER_QUEUE_SET(encodebin->audio_encode_queue, 0, 0, AUDIO_ENC_QUE_TIME);
+                                               encodebin->aeque_sig_id = g_signal_connect( G_OBJECT(encodebin->audio_encode_queue), "overrun", 
+                                                                                                                       G_CALLBACK(queue_overun_cb), encodebin);                                           
+
+                                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                                               sinkpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "sink");
+                                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+                                       }
+#endif                                 
+                               
+                       }
+#if 0                  
+                       if(encodebin->use_aenc_queue)
+                       {
+                               srcpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "src");
+                               sinkpad = encodebin->mux_audio_sinkpad = gst_encode_bin_get_mux_sink_pad(encodebin->mux, ENCODEBIN_MUX_AUDIO_SINK);
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+
+                       }
+#else
+
+                       if(encodebin->audio_encode_queue)
+                       {
+                               srcpad = gst_element_get_static_pad(encodebin->audio_encode_queue, "src");
+                               sinkpad = encodebin->mux_audio_sinkpad = gst_encode_bin_get_mux_sink_pad(encodebin->mux, ENCODEBIN_MUX_AUDIO_SINK);
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+
+                       }
+#endif
+                       else
+                       {       
+                               srcpad = gst_element_get_static_pad(encodebin->audio_encode, "src");
+                               sinkpad = encodebin->mux_audio_sinkpad = gst_encode_bin_get_mux_sink_pad(encodebin->mux, ENCODEBIN_MUX_AUDIO_SINK);
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, audio_link_fail);  
+                       }
+
+                       srcpad = gst_element_get_static_pad(encodebin->mux, "src");
+                       if(gst_ghost_pad_get_target(GST_GHOST_PAD (encodebin->srcpad)) != srcpad)
+                               gst_ghost_pad_set_target(GST_GHOST_PAD (encodebin->srcpad), srcpad);
+                       gst_object_unref(srcpad);
+                       srcpad = NULL;
+
+                       /* For pause/resume control */
+                       sinkpad = gst_element_get_static_pad (encodebin->audio_queue, "sink");
+                       encodebin->asink_probeid = gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_BUFFER, (GstPadProbeCallback)gst_encode_bin_audio_probe, encodebin, NULL);
+                       gst_object_unref(sinkpad);
+                       sinkpad = NULL;
+
+                       break;
+               case GST_ENCODE_BIN_PROFILE_IMAGE :
+                       if(!gst_caps_is_any(encodebin->icaps))
+                       {                               
+                               g_object_set(encodebin->icapsfilter, "caps", encodebin->icaps, NULL);
+                       }
+                               
+                       if (encodebin->auto_color_space) {
+                               if(encodebin->color_space == NULL) {
+                                   encodebin->color_space  = gst_element_factory_make ("videoconvert","color_space");
+                                   gst_bin_add (GST_BIN (encodebin), encodebin->color_space);
+                               }
+
+                               srcpad = gst_element_get_static_pad(encodebin->image_queue, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->image_toggle, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);
+
+                               srcpad = gst_element_get_static_pad(encodebin->image_toggle, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->color_space, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);          
+
+                               srcpad = gst_element_get_static_pad(encodebin->color_space, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->icapsfilter, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);  
+
+                               srcpad = gst_element_get_static_pad(encodebin->icapsfilter, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->image_encode, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);                                  
+
+                       }
+                       else {
+                               
+                               srcpad = gst_element_get_static_pad(encodebin->image_queue, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->image_toggle, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);
+
+                               srcpad = gst_element_get_static_pad(encodebin->image_toggle, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->icapsfilter, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);          
+
+                               srcpad = gst_element_get_static_pad(encodebin->icapsfilter, "src");
+                               sinkpad = gst_element_get_static_pad(encodebin->image_encode, "sink");
+                               _GST_PAD_LINK_UNREF(srcpad, sinkpad, image_link_fail);                                  
+
+                       }
+                       srcpad =  gst_element_get_static_pad (encodebin->image_encode, "src");
+                       if(gst_ghost_pad_get_target(GST_GHOST_PAD (encodebin->srcpad)) != srcpad)
+                               gst_ghost_pad_set_target(GST_GHOST_PAD (encodebin->srcpad), srcpad);
+                       gst_object_unref(srcpad);
+                       srcpad = NULL;
+                       break;
+               default:
+                     GST_WARNING_OBJECT(encodebin, "Invalid profile number = %d", encodebin->profile);
+                     return FALSE;
+                     break;
+       }
+//     gst_pad_set_active(encodebin->srcpad, TRUE);    
+       return TRUE;
+
+video_link_fail:
+       // remove elements
+       gst_encode_bin_remove_element(encodebin, encodebin->color_space);
+       GST_WARNING_OBJECT(encodebin, "encodebin link video elements fail");
+       return FALSE;
+       
+audio_link_fail:
+       // remove element 
+       gst_encode_bin_remove_element(encodebin, encodebin->audio_conv);        
+       gst_encode_bin_remove_element(encodebin, encodebin->audio_sample);      
+       GST_WARNING_OBJECT(encodebin, "encodebin link audio elements fail");
+       return FALSE;
+
+image_link_fail:
+       // remove element 
+       gst_encode_bin_remove_element(encodebin, encodebin->color_space);       
+       GST_WARNING_OBJECT(encodebin, "encodebin link image elements fail");
+       return FALSE;
+
+       
+}
+
+static gboolean 
+gst_encode_bin_unlink_elements (GstEncodeBin *encodebin)
+{
+       GstPad *pad = NULL, *muxpad = NULL;
+       
+       switch(encodebin->profile) {
+               case GST_ENCODE_BIN_PROFILE_AV :
+                       if (encodebin->auto_color_space) {
+                               if (encodebin->video_toggle) {
+                                       gst_element_unlink_many(
+                                               encodebin->video_queue,
+                                               encodebin->video_toggle,
+                                               encodebin->color_space,
+                                               encodebin->vcapsfilter,
+                                               encodebin->video_encode,
+                                               //encodebin->video_encode_queue,
+                                               NULL);
+                               } else {
+                                       gst_element_unlink_many(
+                                               encodebin->video_queue,
+                                               encodebin->color_space,
+                                               encodebin->vcapsfilter,
+                                               encodebin->video_encode,
+                                               //encodebin->video_encode_queue,
+                                               NULL);
+                               }
+                       } else {
+                               if (encodebin->video_toggle) {
+                                       gst_element_unlink_many(
+                                               encodebin->video_queue,
+                                               encodebin->video_toggle,
+                                               encodebin->vcapsfilter,
+                                               encodebin->video_encode,
+                                               //encodebin->video_encode_queue,
+                                               NULL);
+                               } else {
+                                       gst_element_unlink_many(
+                                               encodebin->video_queue,
+                                               encodebin->vcapsfilter,
+                                               encodebin->video_encode,
+                                               //encodebin->video_encode_queue,
+                                               NULL);
+                               }
+                       }
+
+                       if(encodebin->mux_video_sinkpad != NULL)
+                       {
+#if 0                  
+                               if(encodebin->use_venc_queue)
+                               {
+                                       gst_element_unlink(encodebin->video_encode, encodebin->video_encode_queue);
+
+                                       pad = gst_element_get_static_pad (encodebin->video_encode_queue, "src");
+                                       gst_pad_unlink(pad, muxpad);
+                                       gst_object_unref(pad);
+                                       pad = NULL;
+
+                                       if ( g_signal_handler_is_connected ( encodebin->video_encode_queue, encodebin->veque_sig_id) )
+                                       {
+                                               g_signal_handler_disconnect (  encodebin->video_encode_queue, encodebin->veque_sig_id );
+                                       }
+                               }
+#else
+                               if(encodebin->video_encode_queue)
+                               {
+                                       gst_element_unlink(encodebin->video_encode, encodebin->video_encode_queue);
+
+                                       pad = gst_element_get_static_pad (encodebin->video_encode_queue, "src");
+                                       gst_pad_unlink(pad, encodebin->mux_video_sinkpad);
+                                       gst_object_unref(pad);
+                                       pad = NULL;
+
+                                       if ( g_signal_handler_is_connected ( encodebin->video_encode_queue, encodebin->veque_sig_id) )
+                                       {
+                                               g_signal_handler_disconnect (  encodebin->video_encode_queue, encodebin->veque_sig_id );
+                                       }
+                               }
+#endif
+                               else
+                               {
+                                       pad = gst_element_get_static_pad (encodebin->video_encode, "src");
+                                       gst_pad_unlink(pad, encodebin->mux_video_sinkpad);
+                                       gst_object_unref(pad);
+                                       pad = NULL;
+                               }
+
+                               gst_element_release_request_pad(encodebin->mux, encodebin->mux_video_sinkpad);
+//                             gst_object_unref(encodebin->mux_video_sinkpad); //***
+                               encodebin->mux_video_sinkpad = NULL;
+                       }
+
+                       if(encodebin->vsink_probeid)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->video_queue, "sink");
+                               gst_pad_remove_probe(pad, encodebin->vsink_probeid);
+                               encodebin->vsink_probeid = 0;
+                               gst_object_unref(pad);
+                               pad = NULL;                                     
+                       }
+               
+
+                       if(encodebin->vsink_hs_probeid)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->video_encode, "sink");
+                               gst_pad_remove_probe(pad, encodebin->vsink_hs_probeid);
+                               encodebin->vsink_hs_probeid = 0;
+                               gst_object_unref(pad);
+                               pad = NULL;
+                       }
+
+                       if(encodebin->audio_queue == NULL)
+                       {
+                               break;
+                       }
+               case GST_ENCODE_BIN_PROFILE_AUDIO :
+                       if (encodebin->auto_audio_convert ||encodebin->auto_audio_resample) {
+                               if (!encodebin->auto_audio_convert) {
+                                               gst_element_unlink_many  (
+                                                       encodebin->audio_queue,
+                                                       encodebin->audio_sample,
+                                                       encodebin->acapsfilter,
+                                                       encodebin->audio_encode,
+                                                       NULL);  
+                               } else if (!encodebin->auto_audio_resample) {
+                                               gst_element_unlink_many  (
+                                                       encodebin->audio_queue,
+                                                       encodebin->audio_conv,                                  
+                                                       encodebin->acapsfilter,
+                                                       encodebin->audio_encode,
+                                                       NULL);  
+                               } else {
+                                               gst_element_unlink_many  (
+                                                       encodebin->audio_queue,
+                                                       encodebin->audio_conv,
+                                                       encodebin->audio_sample,                                                                                
+                                                       encodebin->acapsfilter,
+                                                       encodebin->audio_encode,
+                                                       NULL);                                  
+                               }
+                       }
+                       else {
+                               gst_element_unlink_many  (
+                                       encodebin->audio_queue,
+                                       encodebin->acapsfilter,
+                                       encodebin->audio_encode,
+                                       NULL);  
+                       }
+
+                       if(encodebin->mux_audio_sinkpad != NULL)
+                       {
+#if 0                  
+                               if(encodebin->use_aenc_queue)
+                               {
+                                       gst_element_unlink(encodebin->audio_encode, encodebin->audio_encode_queue);
+
+                                       pad = gst_element_get_static_pad (encodebin->audio_encode_queue, "src");
+                                       gst_pad_unlink(pad, muxpad);
+                                       gst_object_unref(pad);
+                                       pad = NULL;     
+
+                                       if ( g_signal_handler_is_connected ( encodebin->audio_encode_queue, encodebin->veque_sig_id) )
+                                       {
+                                               g_signal_handler_disconnect (  encodebin->audio_encode_queue, encodebin->veque_sig_id );
+                                       }                                       
+                               }
+#else
+                               if(encodebin->audio_encode_queue)
+                               {
+                                       gst_element_unlink(encodebin->audio_encode, encodebin->audio_encode_queue);
+
+                                       pad = gst_element_get_static_pad (encodebin->audio_encode_queue, "src");
+                                       gst_pad_unlink(pad, encodebin->mux_audio_sinkpad);
+                                       gst_object_unref(pad);
+                                       pad = NULL;     
+
+                                       if ( g_signal_handler_is_connected ( encodebin->audio_encode_queue, encodebin->veque_sig_id) )
+                                       {
+                                               g_signal_handler_disconnect (  encodebin->audio_encode_queue, encodebin->veque_sig_id );
+                                       }                                       
+                               }
+#endif
+                               else
+                               {
+                                       pad = gst_element_get_static_pad (encodebin->audio_encode, "src");
+                                       gst_pad_unlink(pad, encodebin->mux_audio_sinkpad);
+                                       gst_object_unref(pad);
+                                       pad = NULL;
+                               }                       
+
+                               gst_element_release_request_pad(encodebin->mux, encodebin->mux_audio_sinkpad);
+//                             gst_object_unref(encodebin->mux_audio_sinkpad);         //***
+                               encodebin->mux_audio_sinkpad = NULL;
+                       }
+
+                       if(encodebin->asink_probeid)
+                       {
+                               pad = gst_element_get_static_pad (encodebin->audio_queue, "sink"); 
+                               gst_pad_remove_probe(pad, encodebin->asink_probeid);
+                               encodebin->asink_probeid =0;
+                               gst_object_unref(pad);
+                               pad = NULL;
+                       }
+
+                       break;
+               case GST_ENCODE_BIN_PROFILE_IMAGE :
+                       if (encodebin->auto_color_space) {
+                               gst_element_unlink_many  (
+                                       encodebin->image_queue,
+                                       encodebin->image_toggle,
+                                       encodebin->color_space,
+                                       encodebin->icapsfilter,                                                         
+                                       encodebin->image_encode,
+                                       NULL);
+                       }
+                       else {
+                               gst_element_unlink_many  (
+                                       encodebin->image_queue,
+                                       encodebin->image_toggle,        
+                                       encodebin->icapsfilter,                                                                                                                         
+                                       encodebin->image_encode,
+                                       NULL);  
+                       }
+                       break;
+               default:
+                         GST_WARNING_OBJECT(encodebin, "Invalid profile number = %d", encodebin->profile);
+                         return FALSE;
+                 break;
+       }
+       //      gst_pad_set_active(encodebin->srcpad, TRUE);    
+       return TRUE;
+
+}
+
+static gboolean 
+gst_encode_bin_init_video_elements (GstElement *element, gpointer user_data)
+{
+       GstEncodeBin *encodebin = GST_ENCODE_BIN (element);
+
+       if(encodebin->profile != GST_ENCODE_BIN_PROFILE_AV)
+               return FALSE;
+
+       if(encodebin->video_queue == NULL) {
+               encodebin->video_queue = gst_element_factory_make ("queue","video_queue");
+               gst_bin_add (GST_BIN (element), encodebin->video_queue);
+       }
+
+       if( encodebin->use_video_toggle )
+       {
+               if( encodebin->video_toggle == NULL )
+               {
+                       encodebin->video_toggle = gst_element_factory_make ("toggle","video_toggle");
+                       gst_bin_add (GST_BIN (element), encodebin->video_toggle);
+               }
+               GST_INFO_OBJECT( encodebin, "Video toggle is Enabled" );
+       }
+       else
+       {
+               GST_INFO_OBJECT( encodebin, "Video toggle is Disabled" );
+       }
+
+       if(encodebin->vcapsfilter == NULL) {
+               encodebin->vcapsfilter = gst_element_factory_make ("capsfilter","vcapsfilter");
+               gst_bin_add (GST_BIN (element), encodebin->vcapsfilter);
+       }  
+#if 0
+       encodebin->vcaps = gst_caps_new_simple("video/x-raw",
+               "format", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('I', '4', '2', '0'),
+               "width", G_TYPE_INT, 320,
+               "height", G_TYPE_INT, 240,
+               "framerate", GST_TYPE_FRACTION, 30, 1,
+               NULL);  
+
+#endif
+       if(encodebin->video_encode == NULL) {
+               encodebin->video_encode = gst_element_factory_make (encodebin->venc_name, "video_encode");
+               gst_bin_add (GST_BIN (element), encodebin->video_encode);
+       }
+
+#if 0
+       if(encodebin->video_encode_queue == NULL) {
+               encodebin->video_encode_queue = gst_element_factory_make ("queue", "video_encode_queue");
+               gst_bin_add (GST_BIN (element), encodebin->video_encode_queue);
+       }
+
+       g_object_set(G_OBJECT(encodebin->video_encode_queue), "max-size-bytes", (unsigned int)0, NULL);
+#endif
+
+       if(encodebin->mux == NULL) {
+               encodebin->mux = gst_element_factory_make (encodebin->mux_name, "mux");
+               gst_bin_add (GST_BIN (element), encodebin->mux);
+       }
+
+       if (!encodebin->video_encode 
+//             || !encodebin->video_encode_queue 
+               || !encodebin->mux 
+               || !encodebin->video_queue 
+               || !encodebin->vcapsfilter
+               || !encodebin->srcpad )
+       {
+               GST_ERROR_OBJECT(encodebin, "Faild create element \n");
+               return FALSE;
+       }
+       
+       if( encodebin->use_video_toggle && !encodebin->video_toggle )
+       {
+               GST_ERROR_OBJECT(encodebin, "Faild create video toggle element \n");
+               return FALSE;
+       }
+
+#if 0  
+  if (encodebin->auto_color_space && (encodebin->color_space == NULL)) {
+      encodebin->color_space = gst_element_factory_make ("videoconvert","color_space");
+      gst_bin_add (GST_BIN (element), encodebin->color_space);
+   }  
+#endif  
+  return TRUE;
+}
+
+static gboolean 
+gst_encode_bin_init_audio_elements (GstElement *element, gpointer user_data)
+{
+       GstEncodeBin *encodebin = GST_ENCODE_BIN (element);
+
+       if(encodebin->profile > GST_ENCODE_BIN_PROFILE_AUDIO)
+               return FALSE;
+
+       if(encodebin->audio_queue == NULL) {
+               encodebin->audio_queue = gst_element_factory_make ("queue","audio_queue");
+               gst_bin_add (GST_BIN (element), encodebin->audio_queue);
+       }
+
+       if(encodebin->acapsfilter == NULL) {
+               encodebin->acapsfilter = gst_element_factory_make ("capsfilter","acapsfilter");
+               gst_bin_add (GST_BIN (element), encodebin->acapsfilter);
+       }    
+#if 0
+encodebin->acaps = gst_caps_new_simple("audio/x-raw",
+       "rate", G_TYPE_INT, 8000,
+       "channels", G_TYPE_INT, 2,
+       "depth", G_TYPE_INT, 16,
+       NULL);
+#endif
+
+       if(encodebin->audio_encode == NULL) {
+               encodebin->audio_encode = gst_element_factory_make (encodebin->aenc_name, "audio_encode");
+               gst_bin_add (GST_BIN (element), encodebin->audio_encode);
+       }
+
+       if(encodebin->mux == NULL) {
+               encodebin->mux = gst_element_factory_make (encodebin->mux_name, "mux");
+               gst_bin_add (GST_BIN (element), encodebin->mux);
+       }
+
+       if (!encodebin->audio_encode 
+               || !encodebin->audio_queue
+               || !encodebin->mux
+               || !encodebin->acapsfilter      
+               || !encodebin->srcpad )
+       {
+               GST_ERROR_OBJECT(encodebin, "Faild create element \n");
+               return FALSE;
+       }
+#if 0
+       if (encodebin->auto_audio_convert && (encodebin->audio_conv == NULL)) {
+               encodebin->audio_conv = gst_element_factory_make ("audioconvert","audio_conv");
+               gst_bin_add (GST_BIN (element), encodebin->audio_conv);
+       } 
+
+       if (encodebin->auto_audio_resample && (encodebin->audio_sample == NULL)) {
+               encodebin->audio_sample = gst_element_factory_make ("audioresample","audio_sample");
+               gst_bin_add (GST_BIN (element), encodebin->audio_sample);
+       } 
+#endif
+       return TRUE;
+}
+
+
+static gboolean 
+gst_encode_bin_init_image_elements (GstElement *element, gpointer user_data)
+{
+       GstEncodeBin *encodebin = GST_ENCODE_BIN (element);
+
+       if(encodebin->profile < GST_ENCODE_BIN_PROFILE_IMAGE)
+               return FALSE;
+
+       if(encodebin->image_queue == NULL) {
+               encodebin->image_queue = gst_element_factory_make ("queue","image_queue");
+               gst_bin_add (GST_BIN (element), encodebin->image_queue);
+       }
+
+       if(encodebin->image_toggle == NULL) {
+               encodebin->image_toggle = gst_element_factory_make ("toggle","image_toggle");
+               gst_bin_add (GST_BIN (element), encodebin->image_toggle);
+       }
+
+       if(encodebin->icapsfilter == NULL) {
+               encodebin->icapsfilter = gst_element_factory_make ("capsfilter","icapsfilter");
+               gst_bin_add (GST_BIN (element), encodebin->icapsfilter);
+       }  
+
+       if(encodebin->image_encode == NULL) {
+               encodebin->image_encode = gst_element_factory_make (encodebin->ienc_name, "image_encode");
+               gst_bin_add (GST_BIN (element), encodebin->image_encode);
+       }  
+
+       if (!encodebin->image_encode 
+               || !encodebin->image_queue
+               || !encodebin->image_toggle
+               || !encodebin->icapsfilter
+               || !encodebin->srcpad )
+       {
+               GST_ERROR_OBJECT(encodebin, "Faild create element \n");
+               return FALSE;
+       }
+#if 0
+       if (encodebin->auto_color_space && (encodebin->color_space == NULL)) {
+               encodebin->color_space = gst_element_factory_make ("videoconvert","color_space");
+               gst_bin_add (GST_BIN (element), encodebin->color_space);
+       }  
+#endif
+       return TRUE;
+}
+
+static gboolean gst_encode_bin_block(GstEncodeBin *encodebin, gboolean value)
+{
+  
+       if(value) { //block stream
+               switch(encodebin->profile) {
+                       case GST_ENCODE_BIN_PROFILE_AV:
+                               if(encodebin->audio_queue == NULL && encodebin->video_queue == NULL) {
+                                       goto block_fail;
+                               } else {
+                                       if(g_object_class_find_property(G_OBJECT_GET_CLASS(GST_OBJECT(encodebin->video_queue)), 
+                                               "empty-buffers") == NULL) {
+                                               GST_ERROR_OBJECT(encodebin, "The queue element doesn't support 'empty-buffers' property");
+                                               goto block_fail;
+                                       }
+                                       if( encodebin->video_toggle )
+                                       {
+                                               g_object_set(encodebin->video_toggle, "block-data", TRUE , NULL);
+                                               GST_INFO_OBJECT( encodebin, "video_toggle block-data TRUE" );
+                                       }
+                                       
+                                       g_object_set(encodebin->video_queue, "empty-buffers", TRUE , NULL);
+                                       GST_INFO_OBJECT( encodebin, "video_queue empty-buffers TRUE" );
+                                       if(encodebin->audio_queue != NULL)
+                                       {
+                                               g_object_set(encodebin->audio_queue, "empty-buffers", TRUE , NULL);
+                                               GST_INFO_OBJECT( encodebin, "audio_queue empty-buffers TRUE" );
+                                       }
+                               }
+                               break;
+                       case GST_ENCODE_BIN_PROFILE_AUDIO:
+                               if(encodebin->audio_queue == NULL) {
+                                       goto block_fail;                                        
+                               } else {
+                                       if(g_object_class_find_property(G_OBJECT_GET_CLASS(GST_OBJECT(encodebin->audio_queue)), 
+                                               "empty-buffers") == NULL) {
+                                               GST_ERROR_OBJECT(encodebin, "The queue element doesn't support 'empty-buffers' property");
+                                               goto block_fail;
+                                       }                               
+                                       g_object_set(encodebin->audio_queue, "empty-buffers", TRUE , NULL);
+                                       GST_INFO_OBJECT( encodebin, "audio_queue empty-buffers TRUE" );
+                               }
+                               break;
+                       case GST_ENCODE_BIN_PROFILE_IMAGE:
+                               if(encodebin->image_toggle == NULL) {
+                                       goto block_fail;
+                               } else {
+                                       g_object_set(encodebin->image_toggle, "block_data", TRUE, NULL);
+                                       GST_INFO_OBJECT( encodebin, "image_toggle block_data TRUE" );
+                               }
+                               break;   
+                       default:
+                               GST_WARNING_OBJECT (encodebin,"Invalid profile number = %d", encodebin->profile);
+                               goto block_fail;
+                               break;    
+               }
+       } else { //release blocked-stream
+               switch(encodebin->profile) {
+                       case GST_ENCODE_BIN_PROFILE_AV:
+                               if(encodebin->audio_queue == NULL && encodebin->video_queue == NULL) {
+                                       goto unblock_fail;
+                               } else {
+                                       if(g_object_class_find_property(G_OBJECT_GET_CLASS(GST_OBJECT(encodebin->video_queue)), 
+                                               "empty-buffers") == NULL) {
+                                               GST_ERROR_OBJECT(encodebin, "The queue element doesn't support 'empty-buffers' property");
+                                               goto unblock_fail;
+                                       }                               
+                                       if( encodebin->video_toggle )
+                                       {
+                                               g_object_set(encodebin->video_toggle, "block-data", FALSE , NULL);
+                                               GST_INFO_OBJECT( encodebin, "video_toggle block-data FALSE" );
+                                       }
+                                       
+                                       if(encodebin->audio_queue != NULL)
+                                       {                                       
+                                               g_object_set(encodebin->audio_queue, "empty-buffers", FALSE , NULL);
+                                               GST_INFO_OBJECT( encodebin, "audio_queue empty-buffers FALSE" );
+                                       }
+                                       g_object_set(encodebin->video_queue, "empty-buffers", FALSE , NULL);
+                                       GST_INFO_OBJECT( encodebin, "video_queue empty-buffers FALSE" );
+                               }
+                               break;
+                       case GST_ENCODE_BIN_PROFILE_AUDIO:
+                               if(encodebin->audio_queue == NULL) {
+                                       goto unblock_fail;                                      
+                               } else {                
+                                       if(g_object_class_find_property(G_OBJECT_GET_CLASS(GST_OBJECT(encodebin->audio_queue)), 
+                                               "empty-buffers") == NULL) {
+                                               GST_ERROR_OBJECT(encodebin, "The queue element doesn't support 'empty-buffers' property");
+                                               goto unblock_fail;
+                                       }                               
+                                       g_object_set(encodebin->audio_queue, "empty-buffers", FALSE , NULL);
+                                       GST_INFO_OBJECT( encodebin, "audio_queue empty-buffers FALSE" );
+                               }
+                               break;
+                       case GST_ENCODE_BIN_PROFILE_IMAGE:
+                               if(encodebin->image_toggle == NULL) {
+                                       goto unblock_fail;
+                               } else {                                
+                                       g_object_set(encodebin->image_toggle, "block_data", FALSE, NULL);
+                                       GST_INFO_OBJECT( encodebin, "image_toggle block_data FALSE" );
+                               }
+                               break;   
+                       default:
+                               GST_WARNING_OBJECT (encodebin,"Invalid profile number = %d", encodebin->profile);
+                               goto unblock_fail;
+                               break;    
+               }       
+       }
+       encodebin->block = value;
+       return TRUE;
+
+block_fail:
+       GST_ERROR_OBJECT(encodebin, "encodebin block failed");
+       return FALSE;
+       
+unblock_fail:  
+       GST_ERROR_OBJECT(encodebin, "encodebin unblock failed");        
+       return FALSE;  
+}
+
+static gboolean gst_encode_bin_pause(GstEncodeBin *encodebin, gboolean value)
+{
+       GstClock *clock = NULL;
+
+       if(value) { 
+               /* pause stream*/
+               //Block src of encode bin
+               if (!gst_encode_bin_block(encodebin, TRUE))
+               {
+                       GST_WARNING_OBJECT (encodebin, "Fail to block Encodebin.");
+                       goto pause_fail;
+               }
+
+               if (encodebin->paused_time == 0)
+               {
+                       //get steam time
+                       if (clock = GST_ELEMENT_CLOCK(encodebin))               //before PLAYING, this would be NULL. Need to check.
+                       {
+                               GstClockTime current_time, base_time;
+
+                               current_time = gst_clock_get_time(clock);
+                               base_time = gst_element_get_base_time(GST_ELEMENT(encodebin));
+
+                               encodebin->paused_time = current_time - base_time;
+                               
+                               GST_INFO_OBJECT (encodebin, "Encodebin is in running-pause at [%"GST_TIME_FORMAT"]."
+                                       , GST_TIME_ARGS(encodebin->paused_time));
+                       }
+                       else
+                       {
+                               encodebin->paused_time = 0;
+                               encodebin->total_offset_time = 0;
+                               
+                               GST_WARNING_OBJECT (encodebin, "There is no clock in Encodebin.");
+                       }
+               }
+#if 0 //def GST_ENCODE_BIN_SIGNAL_ENABLE               
+               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_PAUSE], 0, TRUE);
+#endif         
+       }
+       else { 
+               /* release paused-stream*/
+               if (encodebin->paused_time != 0)
+               {
+                       if (clock = GST_ELEMENT_CLOCK(encodebin))
+                       {
+                               GstClockTime current_time, base_time;
+                               GstClockTime paused_gap;
+
+                               current_time = gst_clock_get_time(clock);
+                               base_time = gst_element_get_base_time(GST_ELEMENT(encodebin));
+                               paused_gap = current_time - base_time - encodebin->paused_time;
+                               
+                               encodebin->total_offset_time += paused_gap;
+                               encodebin->paused_time = 0;
+                               
+                               GST_INFO_OBJECT (encodebin, "Encodebin now resumes. Offset delay [%"GST_TIME_FORMAT"], Total offset delay [%"GST_TIME_FORMAT"]"
+                                       , GST_TIME_ARGS(paused_gap) , GST_TIME_ARGS(encodebin->total_offset_time));
+                       }
+                       else
+                       {
+                               encodebin->paused_time = 0;
+                               encodebin->total_offset_time = 0;
+                               
+                               GST_WARNING_OBJECT (encodebin, "There is no clock in Encodebin.");
+                       }
+               }
+
+               //TODO : How about qos?
+
+               //Unblock src of encode bin
+               if (!gst_encode_bin_block(encodebin, FALSE))
+               {
+                       GST_WARNING_OBJECT (encodebin, "Fail to Unblock Encodebin.");
+                       goto resume_fail;
+               }
+#if 0 //def GST_ENCODE_BIN_SIGNAL_ENABLE               
+               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_RESUME], 0, TRUE);
+#endif         
+       }
+       encodebin->pause = value;
+       return TRUE;
+
+pause_fail:
+       GST_WARNING_OBJECT (encodebin, "Fail to pause Encodebin");
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE            
+               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_PAUSE], 0, FALSE);
+#endif 
+       return FALSE;
+
+resume_fail:   
+       GST_WARNING_OBJECT (encodebin, "Fail to resume Encodebin");
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE            
+               g_signal_emit (G_OBJECT (encodebin), gst_encode_bin_signals[SIGNAL_STREAM_RESUME], 0, FALSE);
+#endif         
+       return FALSE;   
+}
+
+static gboolean
+gst_encode_bin_release_pipeline (GstElement *element,
+      gpointer user_data)
+{
+#if 0
+  GstEncodeBin *encodebin = GST_ENCODE_BIN (element);
+
+  gst_element_set_state (encodebin->audio_queue, GST_STATE_NULL);
+  gst_element_set_state (encodebin->audio_encode, GST_STATE_NULL);
+  gst_element_set_state (encodebin->video_queue, GST_STATE_NULL);
+  gst_element_set_state (encodebin->video_encode, GST_STATE_NULL);
+  gst_element_set_state (encodebin->mux, GST_STATE_NULL);
+
+  if (encodebin->auto_video_scale) {
+    gst_element_set_state (encodebin->video_scale, GST_STATE_NULL);
+    gst_element_unlink (encodebin->video_queue, encodebin->video_scale);
+    gst_element_unlink (encodebin->video_scale, encodebin->video_encode);
+    gst_bin_remove (GST_BIN (element), encodebin->video_scale);
+
+    encodebin->video_scale = NULL;
+  } else {
+    gst_element_unlink (encodebin->video_queue, encodebin->video_encode);
+  }
+
+  gst_pad_unlink (gst_element_get_pad (encodebin->audio_encode, "src"), 
+                       encodebin->mux_audio_sinkpad);
+  gst_pad_unlink (gst_element_get_pad (encodebin->video_encode, "src"), 
+                       encodebin->mux_video_sinkpad);
+
+  gst_bin_remove_many (GST_BIN (element),
+                               encodebin->audio_queue,
+                               encodebin->audio_encode,
+                               encodebin->video_queue,
+                               encodebin->video_encode,
+                               encodebin->mux,
+                               NULL);
+
+  encodebin->audio_queue = NULL;
+  encodebin->audio_encode = NULL;
+  encodebin->video_queue = NULL;
+  encodebin->video_encode = NULL;
+  encodebin->mux = NULL;
+#endif
+  return TRUE;
+}
+
+static GstPadProbeReturn
+gst_encode_bin_video_probe(GstPad *pad, GstPadProbeInfo *info, GstEncodeBin *encodebin)
+{
+       if (!encodebin)
+       {
+               GST_WARNING_OBJECT (encodebin, "encodebin is Null.");
+               return GST_PAD_PROBE_OK;
+       }
+       
+       //Adjusting timestamp of video source
+       GST_BUFFER_TIMESTAMP(gst_pad_probe_info_get_buffer(info)) -= encodebin->total_offset_time;
+
+       return GST_PAD_PROBE_OK;
+}
+
+static GstPadProbeReturn
+gst_encode_bin_video_probe_hs(GstPad *pad, GstPadProbeInfo *info, GstEncodeBin *encodebin)
+{
+       if (!encodebin)
+       {
+               GST_WARNING_OBJECT (encodebin, "encodebin is Null.");
+               return GST_PAD_PROBE_OK;
+       }
+       
+       GST_BUFFER_TIMESTAMP(gst_pad_probe_info_get_buffer(info))       *= encodebin->multiple;
+       return GST_PAD_PROBE_OK;
+}
+
+static GstPadProbeReturn
+gst_encode_bin_audio_probe(GstPad *pad, GstPadProbeInfo *info, GstEncodeBin *encodebin)
+{
+       if (!encodebin)
+       {
+               GST_WARNING_OBJECT (encodebin, "encodebin is Null.");
+               return GST_PAD_PROBE_OK;
+       }
+       
+       //Adjusting timestamp of video source
+       GST_BUFFER_TIMESTAMP(gst_pad_probe_info_get_buffer(info)) -= encodebin->total_offset_time;
+
+       return GST_PAD_PROBE_OK;
+}
+
+static GstPad*
+gst_encode_bin_get_mux_sink_pad(GstElement *mux, GstEncodeBinMuxSinkPad type)
+{
+       GstElementClass *elemclass = NULL;
+       GList *walk = NULL;
+       GstPad *pad = NULL;
+
+       elemclass = GST_ELEMENT_GET_CLASS (mux);
+
+       walk = gst_element_class_get_pad_template_list (elemclass);
+
+       while (walk) {
+               GstPadTemplate *templ;
+
+               templ = (GstPadTemplate *) walk->data;
+               if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SINK) {
+                       /* ENHANCE ME: Please add other specific mux's case */
+                       if (((type == ENCODEBIN_MUX_AUDIO_SINK) && strstr(GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "audio")) ||  //audio, audio_%d,... ex)ffmux_3gp
+                               ((type == ENCODEBIN_MUX_VIDEO_SINK) && strstr(GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "video")) ||      //video, video_%d,... ex)ffmux_3gp
+                               strstr(GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "sink")  //sink, sink_%d, wavparse_sink, ... ex)oggmux, wavparse
+                       ) {
+                               g_print("PRINT TEMPLATE(%s)\n", GST_PAD_TEMPLATE_NAME_TEMPLATE (templ));
+                               pad = gst_element_get_request_pad (mux, GST_PAD_TEMPLATE_NAME_TEMPLATE (templ));
+                               break;
+                       }
+               }
+               walk = g_list_next (walk);
+       }
+
+       return pad;
+}
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+  GST_DEBUG_CATEGORY_INIT (gst_encode_bin_debug, "encodebin", 0, "encoder bin");
+
+#ifdef ENABLE_NLS
+  GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
+      LOCALEDIR);
+  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
+#endif /* ENABLE_NLS */
+
+  return gst_element_register (plugin, "encodebin", GST_RANK_NONE,
+      GST_TYPE_ENCODE_BIN);
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+    GST_VERSION_MINOR,
+    encodebin,
+    "EXT encoder bin", 
+    plugin_init, VERSION, "LGPL", "Samsung Electronics Co", "http://www.samsung.com/")
diff --git a/encodebin/src/gstencodebin.h b/encodebin/src/gstencodebin.h
new file mode 100644 (file)
index 0000000..136fc92
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+ * GStreamer encodebin
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifndef __GST_ENCODE_BIN_H__
+#define __GST_ENCODE_BIN_H__
+
+#include <gst/gst.h>
+#include <gst/base/gstcollectpads.h>
+#include <gst/riff/riff-ids.h>
+
+G_BEGIN_DECLS
+
+#define GST_CAT_DEFAULT gst_encode_bin_debug
+
+#define GST_TYPE_ENCODE_BIN_PROFILE (gst_encode_bin_profile_get_type())
+GType gst_encode_bin_profile_get_type (void);
+
+#define GST_TYPE_ENCODE_BIN             (gst_encode_bin_get_type())
+#define GST_ENCODE_BIN(obj)             (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_ENCODE_BIN,GstEncodeBin))
+#define GST_ENCODE_BIN_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_ENCODE_BIN,GstEncodeBinClass))
+#define GST_IS_ENCODE_BIN(obj)          (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_ENCODE_BIN))
+#define GST_IS_ENCODE_BIN_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_ENCODE_BIN))
+
+#define GST_ENCODE_BIN_GET_LOCK(encodebin) (((GstEncodeBin*)encodebin)->mutex)
+#define GST_ENCODE_BIN_LOCK(encodebin)     g_mutex_lock (GST_ENCODE_BIN_GET_LOCK(encodebin))
+#define GST_ENCODE_BIN_UNLOCK(encodebin)   g_mutex_unlock (GST_ENCODE_BIN_GET_LOCK(encodebin))
+
+/* Signal enable */
+#define GST_ENCODE_BIN_SIGNAL_ENABLE
+
+typedef struct _GstEncodeBinPad {
+  GstCollectData *collect;
+
+  gboolean is_video;
+  gboolean connected;
+
+  gchar *tag;
+
+  gst_riff_strh hdr;
+} GstEncodeBinPad;
+
+typedef struct _GstEncodeBin GstEncodeBin;
+typedef struct _GstEncodeBinClass GstEncodeBinClass;
+
+struct _GstEncodeBin
+{
+  GstBin bin;                   /* we extend GstBin */
+
+  GMutex *mutex;
+
+  /* pads */
+  GstPad *srcpad;
+  GstPad *video_sinkpad;
+  GstPad *audio_sinkpad;
+  GstPad *image_sinkpad;
+  GstPad *mux_audio_sinkpad;
+  GstPad *mux_video_sinkpad;
+
+  /* sinkpads, video first */
+  GSList *sinkpads;
+
+  /* video restricted to 1 pad */
+  guint video_pads, audio_pads;
+
+  gint profile;
+  gint fps;
+  gint high_speed_fps;
+  gint multiple;
+  gchar *venc_name;
+  gchar *aenc_name;
+  gchar *ienc_name;
+  gchar *mux_name;
+  gchar *vconv_name;
+
+  GstCaps *vcaps;
+  GstCaps *acaps;
+  GstCaps *icaps;
+
+  gboolean auto_audio_convert;
+  gboolean auto_audio_resample;
+  gboolean auto_color_space;
+  gboolean block;
+  gboolean pause;
+  gboolean use_video_toggle;
+  gboolean use_venc_queue;
+  gboolean use_aenc_queue;
+
+  GstElement *audio_queue;
+  GstElement *video_queue;
+  GstElement *video_encode_queue;
+  GstElement *audio_encode_queue;
+  GstElement *image_queue;
+
+  GstElement *audio_encode;
+  GstElement *video_encode;
+  GstElement *image_encode;
+
+  GstElement *vcapsfilter;
+  GstElement *acapsfilter;
+  GstElement *icapsfilter;
+
+  GstElement *video_toggle;
+  GstElement *image_toggle;
+  GstElement *color_space;
+  GstElement *audio_conv;
+  GstElement *audio_sample;
+
+  GstElement *mux;
+
+  /* pause/resume variables */
+  GstClockTime paused_time;             /* pipeline time when pausing */
+  GstClockTime total_offset_time;       /* delayed time which is due to pause */
+  gulong vsink_probeid;
+  gulong vsink_hs_probeid;
+  gulong asink_probeid;
+  gulong veque_sig_id;
+  gulong aeque_sig_id;
+};
+
+struct _GstEncodeBinClass
+{
+  GstBinClass parent_class;
+
+#ifdef GST_ENCODE_BIN_SIGNAL_ENABLE
+  /* signal we fire when stream block/pause function called */
+  void (*stream_block) (GstElement * element, gboolean result);  
+  void (*stream_unblock) (GstElement * element, gboolean result);  
+  void (*stream_pause) (GstElement * element, gboolean result);
+  void (*stream_resume) (GstElement * element, gboolean result);
+#endif
+
+};
+
+GType gst_encode_bin_get_type (void);
+
+G_END_DECLS
+
+
+#endif /* __GST_ENCODE_BIN_H__ */
diff --git a/evaspixmapsink/Makefile.am b/evaspixmapsink/Makefile.am
new file mode 100644 (file)
index 0000000..997547e
--- /dev/null
@@ -0,0 +1,14 @@
+plugin_LTLIBRARIES = libgstevaspixmapsink.la
+
+libgstevaspixmapsink_la_SOURCES = evaspixmapsink.c
+libgstevaspixmapsink_la_CFLAGS = $(GST_CFLAGS) $(X_CFLAGS) $(EFL_CFLAGS) \
+       $(XFIXES_CFLAGS) $(DRI2PROTO_CFLAGS) $(DRI2_CFLAGS) $(X11_CFLAGS) $(XDAMAGE_CFLAGS) $(XV_CFLAGS) $(MMCOMMON_CFLAGS) $(GST_VIDEO_CFLAGS) $(TBM_CFLAGS)
+libgstevaspixmapsink_la_LIBADD = \
+       $(GST_LIBS) -lgstvideo-$(GST_MAJORMINOR) \
+       $(X_LIBS) $(XVIDEO_LIBS) $(XSHM_LIBS) $(LIBM) \
+       $(EFL_LIBS) \
+       $(XFIXES_LIBS) $(DRI2PROTO_LIBS) $(DRI2_LIBS) $(X11_LIBS) $(XDAMAGE_LIBS) $(XV_LIBS) $(GST_VIDEO_LIBS) $(TBM_LIBS)
+libgstevaspixmapsink_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+libgstxvimagesink_la_LIBTOOLFLAGS = --tag=disable-static
+
+noinst_HEADERS = evaspixmapsink.h
diff --git a/evaspixmapsink/evaspixmapsink.c b/evaspixmapsink/evaspixmapsink.c
new file mode 100755 (executable)
index 0000000..05b1297
--- /dev/null
@@ -0,0 +1,5261 @@
+/*
+ * EvasPixmapSink
+ *
+ * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Sangchul Lee <sc11.lee@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/* Our interfaces */
+#include <gst/video/navigation.h>
+#include <gst/video/colorbalance.h>
+#include <gst/video/propertyprobe.h>
+#include <gst/video/gstvideosink.h>
+
+/* Helper functions */
+#include <gst/video/video.h>
+
+/* Object header */
+#include "evaspixmapsink.h"
+
+/* Samsung extension headers */
+/* For xv extension header for buffer transfer (output) */
+#include "xv_types.h"
+
+/* headers for drm */
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <X11/Xmd.h>
+#include <dri2/dri2.h>
+#include <libdrm/drm.h>
+#include <mm_types.h>
+
+#ifdef DUMP_IMG
+#include <stdio.h>
+#endif
+
+/* max channel count *********************************************************/
+#define MM_VIDEO_BUFFER_MAX_PLANE         (4)
+
+#if 0
+#define FUNCTION_ENTER()       GST_INFO("<ENTER>")
+#else
+#define FUNCTION_ENTER()
+#endif
+
+/* Debugging category */
+#include <gst/gstinfo.h>
+GST_DEBUG_CATEGORY_STATIC (gst_debug_evaspixmapsink);
+#define GST_CAT_DEFAULT gst_debug_evaspixmapsink
+GST_DEBUG_CATEGORY_STATIC (GST_CAT_PERFORMANCE);
+
+enum
+{
+  UPDATE_FALSE,
+  UPDATE_TRUE
+};
+
+enum
+{
+  DEGREE_0,
+  DEGREE_90,
+  DEGREE_180,
+  DEGREE_270,
+  DEGREE_NUM,
+};
+
+enum
+{
+  DISP_GEO_METHOD_LETTER_BOX = 0,
+  DISP_GEO_METHOD_ORIGIN_SIZE,
+  DISP_GEO_METHOD_FULL_SCREEN,
+  DISP_GEO_METHOD_CROPPED_FULL_SCREEN,
+  DISP_GEO_METHOD_ORIGIN_SIZE_OR_LETTER_BOX,
+  DISP_GEO_METHOD_CUSTOM_ROI,
+  DISP_GEO_METHOD_NUM,
+};
+
+enum
+{
+  FLIP_NONE = 0,
+  FLIP_HORIZONTAL,
+  FLIP_VERTICAL,
+  FLIP_BOTH,
+  FLIP_NUM,
+};
+
+#define DEF_DISPLAY_GEOMETRY_METHOD DISP_GEO_METHOD_LETTER_BOX
+#define DEF_DISPLAY_FLIP                                FLIP_NONE
+#define GST_TYPE_EVASPIXMAPSINK_FLIP                    (gst_evaspixmapsink_flip_get_type())
+#define GST_TYPE_EVASPIXMAPSINK_ROTATE_ANGLE            (gst_evaspixmapsink_rotate_angle_get_type())
+#define GST_TYPE_EVASPIXMAPSINK_DISPLAY_GEOMETRY_METHOD (gst_evaspixmapsink_display_geometry_method_get_type())
+#define SIZE_FOR_UPDATE_VISIBILITY                      sizeof(gchar)
+#define EPIPE_REQUEST_LIMIT                             20
+
+static GType
+gst_evaspixmapsink_flip_get_type (void)
+{
+  FUNCTION_ENTER ();
+
+  static GType evaspixmapsink_flip_type = 0;
+  static const GEnumValue flip_type[] = {
+    {FLIP_NONE, "Flip NONE", "FLIP_NONE"},
+    {FLIP_HORIZONTAL, "Flip HORIZONTAL", "FLIP_HORIZONTAL"},
+    {FLIP_VERTICAL, "Flip VERTICAL", "FLIP_VERTICAL"},
+    {FLIP_BOTH, "Flip BOTH", "FLIP_BOTH"},
+    {FLIP_NUM, NULL, NULL},
+  };
+
+  if (!evaspixmapsink_flip_type) {
+    evaspixmapsink_flip_type =
+        g_enum_register_static ("GstEvasPixmapSinkFlipType", flip_type);
+  }
+
+  return evaspixmapsink_flip_type;
+}
+
+static GType
+gst_evaspixmapsink_rotate_angle_get_type (void)
+{
+  FUNCTION_ENTER ();
+
+  static GType evaspixmapsink_rotate_angle_type = 0;
+  static const GEnumValue rotate_angle_type[] = {
+    {0, "No rotate", "DEGREE_0"},
+    {1, "Rotate 90 degree", "DEGREE_90"},
+    {2, "Rotate 180 degree", "DEGREE_180"},
+    {3, "Rotate 270 degree", "DEGREE_270"},
+    {4, NULL, NULL},
+  };
+
+  if (!evaspixmapsink_rotate_angle_type) {
+    evaspixmapsink_rotate_angle_type =
+        g_enum_register_static ("GstEvasPixmapSinkRotateAngleType",
+        rotate_angle_type);
+  }
+
+  return evaspixmapsink_rotate_angle_type;
+}
+
+static GType
+gst_evaspixmapsink_display_geometry_method_get_type (void)
+{
+  FUNCTION_ENTER ();
+
+  static GType evaspixmapsink_display_geometry_method_type = 0;
+  static const GEnumValue display_geometry_method_type[] = {
+    {0, "Letter box", "LETTER_BOX"},
+    {1, "Origin size", "ORIGIN_SIZE"},
+    {2, "Full-screen", "FULL_SCREEN"},
+    {3, "Cropped Full-screen", "CROPPED_FULL_SCREEN"},
+    {4, "Origin size(if screen size is larger than video size(width/height)) or Letter box(if video size(width/height) is larger than screen size)", "ORIGIN_SIZE_OR_LETTER_BOX"},
+    {5, "Explicitely described destination ROI", "CUSTOM_ROI"},
+    {6, NULL, NULL},
+  };
+
+  if (!evaspixmapsink_display_geometry_method_type) {
+    evaspixmapsink_display_geometry_method_type =
+        g_enum_register_static ("GstEvasPixmapSinkDisplayGeometryMethodType",
+        display_geometry_method_type);
+  }
+
+  return evaspixmapsink_display_geometry_method_type;
+}
+
+static int
+get_millis_time ()
+{
+  FUNCTION_ENTER ();
+
+  struct timespec tp;
+  clock_gettime (CLOCK_MONOTONIC, &tp);
+  return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L);
+}
+
+static int log_warn_count = 0;
+static Display *g_display_id = NULL;
+
+typedef struct
+{
+  unsigned long flags;
+  unsigned long functions;
+  unsigned long decorations;
+  long input_mode;
+  unsigned long status;
+}
+MotifWmHints, MwmHints;
+
+#define MWM_HINTS_DECORATIONS   (1L << 1)
+
+static void gst_evaspixmapsink_reset (GstEvasPixmapSink * evaspixmapsink);
+static void gst_evaspixmap_buffer_finalize (GstEvasPixmapBuffer *
+    evaspixmapbuf);
+static void gst_evaspixmapsink_navigation_init (GstNavigationInterface * iface);
+static void gst_evaspixmapsink_colorbalance_init (GstColorBalanceInterface *
+    iface);
+static void
+gst_evaspixmapsink_property_probe_interface_init (GstPropertyProbeInterface *
+    iface);
+static void gst_evaspixmapsink_xcontext_clear (GstEvasPixmapSink *
+    evaspixmapsink);
+static void gst_evaspixmapsink_xpixmap_destroy (GstEvasPixmapSink *
+    evaspixmapsink, GstXPixmap * xpixmap);
+static void gst_evaspixmapsink_xpixmap_update_geometry (GstEvasPixmapSink *
+    evaspixmapsink, int idx);
+static gboolean gst_evaspixmap_buffer_put (GstEvasPixmapSink * evaspixmapsink,
+    GstEvasPixmapBuffer * evaspixmapbuf);
+static gboolean gst_evaspixmapsink_xpixmap_link (GstEvasPixmapSink *
+    evaspixmapsink);
+static void gst_evaspixmapsink_xpixmap_clear (GstEvasPixmapSink *
+    evaspixmapsink, GstXPixmap * xpixmap);
+static gint gst_evaspixmapsink_get_format_from_info (GstXContext * context,
+    GstVideoInfo * info);
+static void drm_close_gem (GstEvasPixmapSink * evaspixmapsink,
+    unsigned int gem_handle);
+static void
+gst_evaspixmapsink_xpixmap_fillblack (tbm_bufmgr bufmgr, Display * disp,
+    Pixmap pixmap);
+static GstFlowReturn gst_evaspixmapsink_epipe_reset (GstEvasPixmapSink *
+    evaspixmapsink);
+#ifdef DUMP_IMG
+int util_write_rawdata (const char *file, const void *data, unsigned int size);
+int g_cnt = 0;
+typedef struct _BufferInfo
+{
+  Display *dpy;
+  Pixmap pixmap;
+  int width;
+  int height;
+
+  /* Dri2 */
+  int drm_fd;
+  tbm_bufmgr bufmgr;
+  void *virtual;
+  DRI2Buffer *dri2_buffers;
+  tbm_bo bo;
+} BufferInfo;
+
+static BufferInfo *g_bufinfo[NUM_OF_PIXMAP];
+static void *gst_evaspixmapsink_get_buffer (Display * dpy, Pixmap pixmap,
+    int width, int height, int i);
+void gst_evaspixmapsink_free_buffer (int i);
+static Bool gst_evaspixmapsink_init_dri2 (BufferInfo * bufinfo);
+#endif
+/* Default template - initiated with class struct to allow gst-register to work
+   without X running */
+static GstStaticPadTemplate gst_evaspixmapsink_sink_template_factory =
+GST_STATIC_PAD_TEMPLATE ("sink",
+    GST_PAD_SINK,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("video/x-raw, "
+        "framerate = (fraction) [ 0, MAX ], "
+        "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ]")
+    );
+
+enum
+{
+  PROP_0,
+  PROP_CONTRAST,
+  PROP_BRIGHTNESS,
+  PROP_HUE,
+  PROP_SATURATION,
+  PROP_DISPLAY,
+  PROP_SYNCHRONOUS,
+  PROP_PIXEL_ASPECT_RATIO,
+  PROP_FORCE_ASPECT_RATIO,
+  PROP_DEVICE,
+  PROP_DEVICE_NAME,
+  PROP_DOUBLE_BUFFER,
+  PROP_AUTOPAINT_COLORKEY,
+  PROP_COLORKEY,
+  PROP_PIXMAP_WIDTH,
+  PROP_PIXMAP_HEIGHT,
+  PROP_DISPLAY_GEOMETRY_METHOD,
+  PROP_ZOOM,
+  PROP_DST_ROI_X,
+  PROP_DST_ROI_Y,
+  PROP_DST_ROI_W,
+  PROP_DST_ROI_H,
+  PROP_STOP_VIDEO,
+  PROP_FLIP,
+  PROP_ROTATE_ANGLE,
+  PROP_EVAS_OBJECT,
+  PROP_VISIBLE,
+  PROP_ORIGIN_SIZE,
+};
+
+#define gst_evaspixmapsink_parent_class parent_class
+
+/* ============================================================= */
+/*                                                               */
+/*                       Private Methods                         */
+/*                                                               */
+/* ============================================================= */
+
+/* evaspixmap buffers */
+
+#define GST_TYPE_EVASPIXMAP_BUFFER (gst_evaspixmap_buffer_get_type())
+
+//#define GST_IS_EVASPIXMAP_BUFFER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_EVASPIXMAP_BUFFER))
+//#define GST_EVASPIXMAP_BUFFER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_EVASPIXMAP_BUFFER, GstEvasPixmapBuffer))
+
+//G_DEFINE_BOXED_TYPE(GstEvasPixmapBuffer, gst_evaspixmap_buffer, NULL, gst_evaspixmap_buffer_finalize);
+
+static void
+ecore_pipe_callback_handler (void *data, void *buffer, unsigned int nbyte)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = (GstEvasPixmapSink *) data;
+  guint idx = 0;
+  GstXPixmap *xpixmap = NULL;
+  int i = 0;
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[START]");
+
+  if (!data) {
+    GST_WARNING_OBJECT (evaspixmapsink, "data is NULL..");
+    return;
+  }
+
+  g_mutex_lock (&evaspixmapsink->flow_lock);
+
+  evaspixmapsink->epipe_request_count--;
+  if (!evaspixmapsink->eo) {
+    GST_WARNING_OBJECT (evaspixmapsink, "evas object is NULL..");
+    g_mutex_unlock (&evaspixmapsink->flow_lock);
+    return;
+  }
+  if (!evaspixmapsink->xcontext) {
+    GST_WARNING_OBJECT (evaspixmapsink, "xcontext is NULL..");
+    g_mutex_unlock (&evaspixmapsink->flow_lock);
+    return;
+  }
+
+  /* setting evas object hide and show */
+  if (nbyte == SIZE_FOR_UPDATE_VISIBILITY) {
+    if (!evaspixmapsink->visible) {
+      evas_object_hide (evaspixmapsink->eo);
+      GST_INFO_OBJECT (evaspixmapsink, "object hide");
+    } else {
+      if (!evas_object_image_native_surface_get (evaspixmapsink->eo)) {
+        GST_WARNING_OBJECT (evaspixmapsink,
+            "native surface is not set, skip evas_object_show()..");
+      } else {
+        evas_object_show (evaspixmapsink->eo);
+        GST_INFO_OBJECT (evaspixmapsink, "object show");
+      }
+    }
+    g_mutex_unlock (&evaspixmapsink->flow_lock);
+    return;
+  }
+
+  /* mapping evas object with xpixmap */
+  if (evaspixmapsink->do_link) {
+    GST_DEBUG_OBJECT (evaspixmapsink, "do link");
+    evas_object_image_size_set (evaspixmapsink->eo, evaspixmapsink->w,
+        evaspixmapsink->h);
+    if (evaspixmapsink->xpixmap[idx]->pixmap) {
+      Evas_Native_Surface surf;
+      surf.version = EVAS_NATIVE_SURFACE_VERSION;
+      surf.type = EVAS_NATIVE_SURFACE_X11;
+      surf.data.x11.visual =
+          ecore_x_default_visual_get (ecore_x_display_get (),
+          ecore_x_default_screen_get ());
+      surf.data.x11.pixmap = evaspixmapsink->xpixmap[idx]->pixmap;
+      evas_object_image_native_surface_set (evaspixmapsink->eo, &surf);
+      evaspixmapsink->do_link = FALSE;
+      evaspixmapsink->last_updated_idx = idx;
+    } else {
+      GST_WARNING_OBJECT (evaspixmapsink, "pixmap is NULL..");
+      return;
+    }
+
+    /* flush previous pool */
+    for (i = 0; i < NUM_OF_PREV_PIXMAP; i++) {
+      if (evaspixmapsink->prev[i]->pixmap || evaspixmapsink->prev[i]->gc
+          || evaspixmapsink->prev[i]->damage)
+        GST_LOG_OBJECT (evaspixmapsink,
+            "Free pixmap(%ld), gc(%p), destroy previous damage(%ld)",
+            evaspixmapsink->prev[i]->pixmap,
+            evaspixmapsink->prev[i]->gc, evaspixmapsink->prev[i]->damage);
+      g_mutex_lock (&evaspixmapsink->x_lock);
+      if (evaspixmapsink->prev[i]->pixmap)
+        XFreePixmap (evaspixmapsink->xcontext->disp,
+            evaspixmapsink->prev[i]->pixmap);
+      if (evaspixmapsink->prev[i]->gc)
+        XFreeGC (evaspixmapsink->xcontext->disp, evaspixmapsink->prev[i]->gc);
+      if (evaspixmapsink->prev[i]->damage)
+        XDamageDestroy (evaspixmapsink->xcontext->disp,
+            evaspixmapsink->prev[i]->damage);
+
+      XSync (evaspixmapsink->xcontext->disp, FALSE);
+      evaspixmapsink->prev[i]->pixmap = 0;
+      evaspixmapsink->prev[i]->gc = NULL;
+      evaspixmapsink->prev[i]->damage = 0;
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+    }
+    int ret = GST_FLOW_OK;
+    ret = gst_evaspixmapsink_epipe_reset (evaspixmapsink);
+    if (ret != GST_FLOW_OK) {
+      GST_ERROR_OBJECT (evaspixmapsink,
+          "evas epipe reset ret=%d, need to check", ret);
+      return GST_STATE_CHANGE_FAILURE;
+    }
+    if (evaspixmapsink->visible
+        && !evas_object_visible_get (evaspixmapsink->eo)) {
+      evas_object_show (evaspixmapsink->eo);
+      GST_WARNING_OBJECT (evaspixmapsink, "object show (lazy)");
+    }
+
+  } else {
+    GST_DEBUG_OBJECT (evaspixmapsink, "update");
+    /* update evas image object size */
+    if (evaspixmapsink->use_origin_size) {
+      evas_object_geometry_get (evaspixmapsink->eo, NULL, NULL,
+          &evaspixmapsink->w, &evaspixmapsink->h);
+    }
+
+    g_mutex_lock (&evaspixmapsink->pixmap_ref_lock);
+
+    /* find a oldest damaged pixmap */
+    int temp_time = 0;
+    for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+      if (evaspixmapsink->last_updated_idx == i) {
+        continue;
+      } else {
+        xpixmap = evaspixmapsink->xpixmap[i];
+        if (xpixmap->ref > 0 && xpixmap->damaged_time) {
+          if (temp_time == 0) {
+            temp_time = xpixmap->damaged_time;
+            idx = i;
+          } else {
+            if (temp_time > xpixmap->damaged_time) {
+              temp_time = xpixmap->damaged_time;
+              idx = i;
+            }
+          }
+        }
+      }
+    }
+
+    xpixmap = evaspixmapsink->xpixmap[idx];
+    if (xpixmap->pixmap) {
+      GST_LOG ("last_update_idx (%d)", evaspixmapsink->last_updated_idx);
+      if (evaspixmapsink->last_updated_idx != idx) {
+        Evas_Native_Surface surf;
+        surf.version = EVAS_NATIVE_SURFACE_VERSION;
+        surf.type = EVAS_NATIVE_SURFACE_X11;
+        surf.data.x11.visual =
+            ecore_x_default_visual_get (ecore_x_display_get (),
+            ecore_x_default_screen_get ());
+        surf.data.x11.pixmap = xpixmap->pixmap;
+        if (evaspixmapsink->eo) {
+          evas_object_image_native_surface_set (evaspixmapsink->eo, NULL);
+        }
+        evas_object_image_native_surface_set (evaspixmapsink->eo, &surf);
+        GST_LOG_OBJECT (evaspixmapsink,
+            "update, native_surface_set of xpixmap[%d]", idx);
+        xpixmap = evaspixmapsink->xpixmap[evaspixmapsink->last_updated_idx];
+        if (xpixmap->ref > 0 && xpixmap->damaged_time > 0) {
+          xpixmap->ref--;
+          xpixmap->damaged_time = 0;
+          GST_INFO_OBJECT (evaspixmapsink,
+              "last updated pixmap[%d] ref-count DECREASED : pixmap(%ld), refcount(%d), damaged_time(%d), idx(%d)",
+              evaspixmapsink->last_updated_idx, xpixmap->pixmap, xpixmap->ref,
+              xpixmap->damaged_time);
+        } else {
+          GST_LOG
+              ("skip decreasing refcount : pixmap(%ld), refcount(%d), damaged_time(%d), idx(%d)",
+              xpixmap->pixmap, xpixmap->ref, xpixmap->damaged_time,
+              evaspixmapsink->last_updated_idx);
+        }
+        evaspixmapsink->last_updated_idx = idx;
+        GST_LOG ("last_update_idx (%d)", evaspixmapsink->last_updated_idx);
+      }
+
+      evas_object_image_fill_set (evaspixmapsink->eo, 0, 0, evaspixmapsink->w,
+          evaspixmapsink->h);
+      evas_object_image_data_update_add (evaspixmapsink->eo, 0, 0,
+          evaspixmapsink->w, evaspixmapsink->h);
+      //GST_LOG_OBJECT (evaspixmapsink,"request to update : pixmap idx(%d), ref(%d)", idx, xpixmap->ref);
+    } else {
+      GST_ERROR_OBJECT (evaspixmapsink, "pixmap is NULL..");
+    }
+    g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+  }
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+}
+
+static void
+evas_callback_resize_event (void *data, Evas * e, Evas_Object * obj,
+    void *event_info)
+{
+  FUNCTION_ENTER ();
+
+  int w = 0;
+  int h = 0;
+  int ret = GST_FLOW_OK;
+#ifdef COMPARE_RATIO
+  float former_ratio = 0;
+  float ratio = 0;
+  float abs_margin = 0;
+#endif
+  GstEvasPixmapSink *evaspixmapsink = (GstEvasPixmapSink *) data;
+  GST_DEBUG_OBJECT (evaspixmapsink, "[START]");
+
+  evas_object_geometry_get (evaspixmapsink->eo, NULL, NULL, &w, &h);
+  GST_DEBUG_OBJECT (evaspixmapsink, "resized : w(%d), h(%d)", w, h);
+  if (!evaspixmapsink->use_origin_size &&
+      (evaspixmapsink->w != w || evaspixmapsink->h != h)) {
+#ifdef COMPARE_RATIO
+    former_ratio = (float) evaspixmapsink->w / evaspixmapsink->h;
+    ratio = (float) w / h;
+#endif
+    evaspixmapsink->w = w;
+    evaspixmapsink->h = h;
+
+#ifdef COMPARE_RATIO
+    GST_DEBUG_OBJECT (evaspixmapsink, "resized : ratio(%.3f=>%.3f)",
+        former_ratio, ratio);
+    if (former_ratio >= ratio) {
+      abs_margin = former_ratio - ratio;
+    } else {
+      abs_margin = ratio - former_ratio;
+    }
+    /* re-link_pixmap can only be set when ratio is changed */
+    if (abs_margin >= MARGIN_OF_ERROR) {
+#endif
+      if (!gst_evaspixmapsink_xpixmap_link (evaspixmapsink)) {
+        GST_ERROR_OBJECT (evaspixmapsink,
+            "link evas image object with pixmap failed...");
+        return;
+      }
+#ifdef COMPARE_RATIO
+    }
+#endif
+  }
+
+  ret = gst_evaspixmapsink_epipe_reset (evaspixmapsink);
+  if (ret != GST_FLOW_OK) {
+    GST_ERROR_OBJECT (evaspixmapsink,
+        "evas epipe reset ret=%d, need to check", ret);
+    return GST_STATE_CHANGE_FAILURE;
+  }
+
+  if (GST_STATE (evaspixmapsink) >= GST_STATE_PAUSED) {
+    g_mutex_lock (&evaspixmapsink->flow_lock);
+    gst_evaspixmap_buffer_put (evaspixmapsink, evaspixmapsink->evas_pixmap_buf);
+    g_mutex_unlock (&evaspixmapsink->flow_lock);
+  }
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+}
+
+static inline gboolean
+is_evas_image_object (Evas_Object * obj)
+{
+  FUNCTION_ENTER ();
+
+  const char *type;
+  if (!obj) {
+    return FALSE;
+  }
+  type = evas_object_type_get (obj);
+  if (!type) {
+    return FALSE;
+  }
+  if (strcmp (type, "image") == 0) {
+    return TRUE;
+  }
+  return FALSE;
+}
+
+static void
+evas_callback_del_event (void *data, Evas * e, Evas_Object * obj,
+    void *event_info)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = data;
+  if (!evaspixmapsink) {
+    GST_WARNING ("evaspixmapsink is NULL..");
+    return;
+  }
+  GST_DEBUG_OBJECT (evaspixmapsink, "[START]");
+
+  evas_object_event_callback_del (evaspixmapsink->eo, EVAS_CALLBACK_RESIZE,
+      evas_callback_resize_event);
+  if (evaspixmapsink->eo) {
+    evas_object_image_native_surface_set (evaspixmapsink->eo, NULL);
+    evaspixmapsink->eo = NULL;
+  }
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+}
+
+/* X11 stuff */
+static gboolean error_caught = FALSE;
+
+static int
+gst_evaspixmapsink_handle_xerror (Display * display, XErrorEvent * xevent)
+{
+  FUNCTION_ENTER ();
+
+  char error_msg[1024];
+
+  XGetErrorText (display, xevent->error_code, error_msg, 1024);
+  {
+    if (g_display_id == display) {
+      GST_ERROR
+          ("evaspixmapsink triggered an XError. error: %s, display(%p), xevent->request_code: %d",
+          error_msg, display, xevent->request_code);
+      error_caught = TRUE;
+    } else {
+      GST_ERROR
+          ("evaspixmapsink triggered an XError. error: %s, xevent->request_code: %d, but the display(%p) was not created in evaspixmapsink, skip it...",
+          error_msg, xevent->request_code, display);
+    }
+  }
+  return 0;
+}
+
+#ifdef DUMP_IMG
+int
+util_write_rawdata (const char *file, const void *data, unsigned int size)
+{
+  FUNCTION_ENTER ();
+
+  FILE *fp;
+
+  fp = fopen (file, "wb");
+  if (fp == NULL) {
+    GST_WARNING ("fopen fail... size : %d", size);
+    return -1;
+  }
+  fwrite ((char *) data, sizeof (char), size, fp);
+  fclose (fp);
+
+  return 0;
+}
+
+static inline void
+input_dump (MMVideoBuffer * inbuf)
+{
+  char *temp = (char *) inbuf->data[0];
+  int i = 0;
+  char filename[100] = { 0 };
+  FILE *fp = NULL;
+
+  GST_WARNING
+      ("IN_DUMP_%2.2d : width=%d, height=%d, stride_width=%d, stride_height=%d",
+      g_cnt, inbuf->width[0], inbuf->height[0], inbuf->stride_width[0],
+      inbuf->stride_height[0]);
+
+  sprintf (filename, "/opt/usr/media/IN_DUMP_%2.2d.dump", g_cnt++);
+  fp = fopen (filename, "ab");
+
+  if (!fp) {
+    GST_ERROR ("%s open failed", filename);
+    return;
+  }
+
+  for (i = 0; i < inbuf->height[0]; i++) {
+    fwrite (temp, inbuf->width[0], 1, fp);
+    temp += inbuf->stride_width[0];
+  }
+
+  temp =
+      (char *) inbuf->data[0] +
+      inbuf->stride_width[0] * inbuf->stride_height[0];
+
+  for (i = 0; i < (inbuf->height[0] / 2); i++) {
+    fwrite (temp, inbuf->width[0], 1, fp);
+    temp += inbuf->stride_width[0];
+  }
+  fclose (fp);
+}
+
+void *
+gst_evaspixmapsink_get_buffer (Display * dpy, Pixmap pixmap, int width,
+    int height, int i)
+{
+  if (g_bufinfo[i] != NULL) {
+    GST_ERROR ("g_bufinfo!=NULL %p", g_bufinfo[i]);
+    exit (-1);
+  }
+
+  g_bufinfo[i] = calloc (1, sizeof (BufferInfo));
+
+  g_bufinfo[i]->dpy = dpy;
+  g_bufinfo[i]->pixmap = pixmap;
+  g_bufinfo[i]->width = width;
+  g_bufinfo[i]->height = height;
+
+  if (!gst_evaspixmapsink_init_dri2 (g_bufinfo[i])) {
+    free (g_bufinfo[i]);
+    g_bufinfo[i] = NULL;
+    return NULL;
+  }
+
+  if (g_bufinfo[i]->virtual == NULL) {
+    GST_ERROR ("g_bufinfo->virtual == NULL");
+    exit (-1);
+  }
+
+  return g_bufinfo[i]->virtual;
+}
+
+void
+gst_evaspixmapsink_free_buffer (int i)
+{
+  if (g_bufinfo[i] == NULL) {
+    GST_ERROR ("g_bufinfo == NULL");
+    exit (-1);
+  }
+
+  if (g_bufinfo[i] == NULL) {
+    GST_ERROR ("g_bufinfo==NULL");
+    exit (-1);
+  }
+
+  if (g_bufinfo[i]) {
+    if (g_bufinfo[i]->bo)
+      tbm_bo_unref (g_bufinfo[i]->bo);
+    if (g_bufinfo[i]->dri2_buffers)
+      free (g_bufinfo[i]->dri2_buffers);
+    if (g_bufinfo[i]->bufmgr)
+      tbm_bufmgr_deinit (g_bufinfo[i]->bufmgr);
+    if (g_bufinfo[i]->drm_fd >= 0)
+      close (g_bufinfo[i]->drm_fd);
+  }
+
+  XSync (g_bufinfo[i]->dpy, 0);
+  free (g_bufinfo[i]);
+  g_bufinfo[i] = NULL;
+}
+
+static Bool
+gst_evaspixmapsink_init_dri2 (BufferInfo * bufinfo)
+{
+  int screen;
+  int dri2_base = 0;
+  int dri2_err_base = 0;
+  int dri2Major, dri2Minor;
+  char *driverName = NULL, *deviceName = NULL;
+  unsigned int attachments[1];
+  int dri2_count, dri2_out_count;
+  int dri2_width, dri2_height;
+  drm_magic_t magic;
+  tbm_bo_handle bo_handle;
+  screen = DefaultScreen (bufinfo->dpy);
+  if (!DRI2QueryExtension (bufinfo->dpy, &dri2_base, &dri2_err_base)) {
+    GST_ERROR ("no DRI2 extension. !!\n");
+    goto fail_init_dri2;
+  }
+  if (!DRI2QueryVersion (bufinfo->dpy, &dri2Major, &dri2Minor)) {
+    GST_ERROR ("fail : DRI2QueryVersion !!\n");
+    goto fail_init_dri2;
+  }
+  if (!DRI2Connect (bufinfo->dpy, RootWindow (bufinfo->dpy, screen),
+          &driverName, &deviceName)) {
+    GST_ERROR ("fail : DRI2Connect !!\n");
+    goto fail_init_dri2;
+  }                             /* drm_fd */
+  bufinfo->drm_fd = open (deviceName, O_RDWR);
+  if (bufinfo->drm_fd < 0) {
+    GST_ERROR ("fail : open drm device (%s)\n", deviceName);
+    goto fail_init_dri2;
+  }
+  /* get the drm magic */
+  drmGetMagic (bufinfo->drm_fd, &magic);
+  if (!DRI2Authenticate (bufinfo->dpy, RootWindow (bufinfo->dpy, screen),
+          magic)) {
+    GST_ERROR ("fail : DRI2Authenticate (%d)\n", magic);
+    goto fail_init_dri2;
+  }
+  /* bufmgr */
+  bufinfo->bufmgr = tbm_bufmgr_init (bufinfo->drm_fd);
+  if (!bufinfo->bufmgr) {
+    GST_ERROR ("fail : init buffer manager \n");
+    goto fail_init_dri2;
+  }
+  DRI2CreateDrawable (bufinfo->dpy, bufinfo->pixmap);
+  attachments[0] = DRI2BufferFrontLeft;
+  dri2_count = 1;
+  bufinfo->dri2_buffers =
+      DRI2GetBuffers (bufinfo->dpy, bufinfo->pixmap, &dri2_width, &dri2_height,
+      attachments, dri2_count, &dri2_out_count);
+  if (!bufinfo->dri2_buffers) {
+    GST_ERROR ("fail : get buffers\n");
+    goto fail_init_dri2;
+  }
+  if (!bufinfo->dri2_buffers[0].name) {
+    GST_ERROR ("fail : a handle of the dri2 buffer is null \n ");
+    goto fail_init_dri2;
+  }
+  bufinfo->bo = tbm_bo_import (bufinfo->bufmgr, bufinfo->dri2_buffers[0].name);
+  if (!bufinfo->bo) {
+    GST_ERROR ("fail : import bo (key:%d)\n", bufinfo->dri2_buffers[0].name);
+    goto fail_init_dri2;
+  }
+  /* virtual */
+  bo_handle = tbm_bo_map (bufinfo->bo, TBM_DEVICE_CPU, TBM_OPTION_WRITE);
+  if (!bo_handle.ptr) {
+    GST_ERROR ("fail : tbm_bo_map");
+    goto fail_init_dri2;
+  }
+  tbm_bo_unmap (bufinfo->bo);
+
+  bufinfo->virtual = (void *) bo_handle.ptr;
+  if (!bufinfo->virtual) {
+    GST_ERROR ("fail : map \n");
+    goto fail_init_dri2;
+  }
+
+  free (driverName);
+  free (deviceName);
+
+  return True;
+
+fail_init_dri2:
+  if (driverName)
+    free (driverName);
+  if (deviceName)
+    free (deviceName);
+  if (bufinfo->bo)
+    tbm_bo_unref (bufinfo->bo);
+  if (bufinfo->dri2_buffers)
+    free (bufinfo->dri2_buffers);
+  if (bufinfo->bufmgr)
+    tbm_bufmgr_deinit (bufinfo->bufmgr);
+  if (bufinfo->drm_fd >= 0)
+    close (bufinfo->drm_fd);
+  return False;
+}
+#endif
+
+#ifdef HAVE_XSHM
+/* This function checks that it is actually really possible to create an image
+   using XShm */
+static gboolean
+gst_evaspixmapsink_check_xshm_calls (GstXContext * xcontext)
+{
+  FUNCTION_ENTER ();
+
+  XvImage *xvimage;
+  XShmSegmentInfo SHMInfo;
+  gint size;
+  int (*handler) (Display *, XErrorEvent *);
+  gboolean result = FALSE;
+  gboolean did_attach = FALSE;
+
+  g_return_val_if_fail (xcontext != NULL, FALSE);
+
+  /* Sync to ensure any older errors are already processed */
+  XSync (xcontext->disp, FALSE);
+
+  /* Set defaults so we don't free these later unnecessarily */
+  SHMInfo.shmaddr = ((void *) -1);
+  SHMInfo.shmid = -1;
+
+  /* Setting an error handler to catch failure */
+  error_caught = FALSE;
+  handler = XSetErrorHandler (gst_evaspixmapsink_handle_xerror);
+
+  /* Trying to create a 1x1 picture */
+  GST_DEBUG ("XvShmCreateImage of 1x1");
+  xvimage = XvShmCreateImage (xcontext->disp, xcontext->xv_port_id,
+      xcontext->im_format, NULL, 1, 1, &SHMInfo);
+
+  /* Might cause an error, sync to ensure it is noticed */
+  XSync (xcontext->disp, FALSE);
+  if (!xvimage || error_caught) {
+    GST_WARNING ("could not XvShmCreateImage a 1x1 image");
+    goto beach;
+  }
+  size = xvimage->data_size;
+
+  SHMInfo.shmid = shmget (IPC_PRIVATE, size, IPC_CREAT | 0777);
+  if (SHMInfo.shmid == -1) {
+    GST_WARNING ("could not get shared memory of %d bytes", size);
+    goto beach;
+  }
+
+  SHMInfo.shmaddr = shmat (SHMInfo.shmid, NULL, 0);
+  if (SHMInfo.shmaddr == ((void *) -1)) {
+    GST_WARNING ("Failed to shmat: %s", g_strerror (errno));
+    /* Clean up the shared memory segment */
+    shmctl (SHMInfo.shmid, IPC_RMID, NULL);
+    goto beach;
+  }
+
+  xvimage->data = SHMInfo.shmaddr;
+  SHMInfo.readOnly = FALSE;
+
+  if (XShmAttach (xcontext->disp, &SHMInfo) == 0) {
+    GST_WARNING ("Failed to XShmAttach");
+    /* Clean up the shared memory segment */
+    shmctl (SHMInfo.shmid, IPC_RMID, NULL);
+    goto beach;
+  }
+
+  /* Sync to ensure we see any errors we caused */
+  XSync (xcontext->disp, FALSE);
+
+  /* Delete the shared memory segment as soon as everyone is attached.
+   * This way, it will be deleted as soon as we detach later, and not
+   * leaked if we crash. */
+  shmctl (SHMInfo.shmid, IPC_RMID, NULL);
+
+  if (!error_caught) {
+    GST_DEBUG ("XServer ShmAttached to 0x%x, id 0x%lx", SHMInfo.shmid,
+        SHMInfo.shmseg);
+
+    did_attach = TRUE;
+    /* store whether we succeeded in result */
+    result = TRUE;
+  } else {
+    GST_WARNING ("MIT-SHM extension check failed at XShmAttach. "
+        "Not using shared memory.");
+  }
+
+beach:
+  /* Sync to ensure we swallow any errors we caused and reset error_caught */
+  XSync (xcontext->disp, FALSE);
+
+  error_caught = FALSE;
+  XSetErrorHandler (handler);
+
+  if (did_attach) {
+    GST_DEBUG ("XServer ShmDetaching from 0x%x id 0x%lx",
+        SHMInfo.shmid, SHMInfo.shmseg);
+    XShmDetach (xcontext->disp, &SHMInfo);
+    XSync (xcontext->disp, FALSE);
+  }
+  if (SHMInfo.shmaddr != ((void *) -1))
+    shmdt (SHMInfo.shmaddr);
+  if (xvimage)
+    XFree (xvimage);
+  return result;
+}
+#endif /* HAVE_XSHM */
+
+/* This function destroys a GstEvasPixmap handling XShm availability */
+static void
+gst_evaspixmap_buffer_destroy (GstEvasPixmapBuffer * evaspixmapbuf)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+
+  evaspixmapsink = evaspixmapbuf->evaspixmapsink;
+  if (G_UNLIKELY (evaspixmapsink == NULL)) {
+    goto no_sink;
+  }
+  GST_DEBUG_OBJECT (evaspixmapsink, "Destroying buffer");
+
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  GST_OBJECT_LOCK (evaspixmapsink);
+
+  /* We might have some buffers destroyed after changing state to NULL */
+  if (evaspixmapsink->xcontext == NULL) {
+    GST_DEBUG_OBJECT (evaspixmapsink, "Destroying XvImage after Xcontext");
+#ifdef HAVE_XSHM
+    /* Need to free the shared memory segment even if the x context
+     * was already cleaned up */
+    if (evaspixmapbuf->SHMInfo.shmaddr != ((void *) -1)) {
+      shmdt (evaspixmapbuf->SHMInfo.shmaddr);
+    }
+#endif
+    goto beach;
+  }
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+#ifdef HAVE_XSHM
+  if (evaspixmapsink->xcontext->use_xshm) {
+    if (evaspixmapbuf->SHMInfo.shmaddr != ((void *) -1)) {
+      GST_DEBUG_OBJECT (evaspixmapsink,
+          "XServer ShmDetaching from 0x%x id 0x%lx",
+          evaspixmapbuf->SHMInfo.shmid, evaspixmapbuf->SHMInfo.shmseg);
+      XShmDetach (evaspixmapsink->xcontext->disp, &evaspixmapbuf->SHMInfo);
+      XSync (evaspixmapsink->xcontext->disp, FALSE);
+      shmdt (evaspixmapbuf->SHMInfo.shmaddr);
+    }
+    if (evaspixmapbuf->xvimage)
+      XFree (evaspixmapbuf->xvimage);
+  } else
+#endif /* HAVE_XSHM */
+  {
+    if (evaspixmapbuf->xvimage) {
+      if (evaspixmapbuf->xvimage->data) {
+        g_free (evaspixmapbuf->xvimage->data);
+      }
+      XFree (evaspixmapbuf->xvimage);
+    }
+  }
+
+  XSync (evaspixmapsink->xcontext->disp, FALSE);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+beach:
+  GST_OBJECT_UNLOCK (evaspixmapsink);
+  evaspixmapbuf->evaspixmapsink = NULL;
+  gst_object_unref (evaspixmapsink);
+  gst_buffer_unref (evaspixmapbuf->buffer);
+  free (evaspixmapbuf);
+  return;
+
+no_sink:
+  {
+    GST_WARNING_OBJECT (evaspixmapsink, "no sink found");
+    return;
+  }
+}
+
+static void
+gst_evaspixmap_buffer_finalize (GstEvasPixmapBuffer * evaspixmapbuf)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+
+  evaspixmapsink = evaspixmapbuf->evaspixmapsink;
+  if (G_UNLIKELY (evaspixmapsink == NULL)) {
+    GST_WARNING_OBJECT (evaspixmapsink, "no sink found");
+    return;
+  }
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  /* If our geometry changed we can't reuse that image. */
+  GST_LOG_OBJECT (evaspixmapsink, "destroy image as sink is shutting down");
+  gst_evaspixmap_buffer_destroy (evaspixmapbuf);
+}
+
+static void
+gst_evaspixmap_buffer_free (GstEvasPixmapBuffer * evaspixmapbuf)
+{
+  FUNCTION_ENTER ();
+  GST_WARNING ("evaspixmap buffer free");
+  /* make sure it is not recycled */
+  evaspixmapbuf->width = -1;
+  evaspixmapbuf->height = -1;
+  free (evaspixmapbuf);
+}
+
+static void
+gst_evaspixmap_buffer_init (GstEvasPixmapBuffer * evaspixmapbuf,
+    gpointer g_class)
+{
+  FUNCTION_ENTER ();
+
+#ifdef HAVE_XSHM
+  evaspixmapbuf->SHMInfo.shmaddr = ((void *) -1);
+  evaspixmapbuf->SHMInfo.shmid = -1;
+#endif
+}
+
+static void
+gst_evaspixmap_buffer_class_init (gpointer g_class, gpointer class_data)
+{
+  FUNCTION_ENTER ();
+
+}
+
+/* This function handles GstEvasPixmapBuffer creation depending on XShm availability */
+static GstEvasPixmapBuffer *
+gst_evaspixmap_buffer_new (GstEvasPixmapSink * evaspixmapsink, GstCaps * caps)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapBuffer *evaspixmapbuf = NULL;
+  GstStructure *structure = NULL;
+  gboolean succeeded = FALSE;
+  int (*handler) (Display *, XErrorEvent *);
+
+  g_return_val_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink), NULL);
+
+  if (caps == NULL) {
+    GST_WARNING ("caps is NULL");
+    return NULL;
+  }
+
+  evaspixmapbuf = (GstEvasPixmapBuffer *) malloc (sizeof (GstEvasPixmapBuffer));
+  if (!evaspixmapbuf) {
+    GST_WARNING ("fail to allocate evaspixmapbuf");
+    return NULL;
+  }
+  GST_DEBUG_OBJECT (evaspixmapsink, "Creating new EvasPixmapBuffer");
+  evaspixmapbuf->buffer = gst_buffer_new ();
+
+  structure = gst_caps_get_structure (caps, 0);
+
+  if (!gst_structure_get_int (structure, "width", &evaspixmapbuf->width)
+      || !gst_structure_get_int (structure, "height", &evaspixmapbuf->height)) {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "failed getting geometry from caps %" GST_PTR_FORMAT, caps);
+  }
+
+  GST_LOG_OBJECT (evaspixmapsink, "creating %dx%d", evaspixmapbuf->width,
+      evaspixmapbuf->height);
+  GST_LOG_OBJECT (evaspixmapsink, "aligned size %dx%d",
+      evaspixmapsink->aligned_width, evaspixmapsink->aligned_height);
+  if (!evaspixmapsink->is_zero_copy_format) {
+    GST_INFO_OBJECT (evaspixmapsink,
+        "it is not zero copy format. set size of caps.");
+    evaspixmapsink->aligned_width = evaspixmapbuf->width;
+    evaspixmapsink->aligned_height = evaspixmapbuf->height;
+  }
+  if (evaspixmapsink->aligned_width == 0 || evaspixmapsink->aligned_height == 0) {
+    GST_ERROR ("wrong size information");
+    goto beach_unlocked;
+  }
+
+  evaspixmapbuf->im_format =
+      gst_evaspixmapsink_get_format_from_info (evaspixmapsink->xcontext,
+      &evaspixmapsink->info);
+  if (evaspixmapbuf->im_format == -1) {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "failed to get format from caps %" GST_PTR_FORMAT, caps);
+    GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+        ("Failed to create output image buffer of %dx%d pixels",
+            evaspixmapbuf->width, evaspixmapbuf->height),
+        ("Invalid input caps"));
+    goto beach_unlocked;
+  }
+  evaspixmapbuf->evaspixmapsink = gst_object_ref (evaspixmapsink);
+
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+  /* Setting an error handler to catch failure */
+  error_caught = FALSE;
+  handler = XSetErrorHandler (gst_evaspixmapsink_handle_xerror);
+
+#ifdef HAVE_XSHM
+  if (evaspixmapsink->xcontext->use_xshm) {
+    int expected_size;
+    evaspixmapbuf->xvimage =
+        XvShmCreateImage (evaspixmapsink->xcontext->disp,
+        evaspixmapsink->xcontext->xv_port_id, evaspixmapbuf->im_format, NULL,
+        evaspixmapsink->aligned_width, evaspixmapsink->aligned_height,
+        &evaspixmapbuf->SHMInfo);
+    if (!evaspixmapbuf->xvimage) {
+      GST_ERROR_OBJECT (evaspixmapsink, "XvShmCreateImage() failed");
+    }
+    if (!evaspixmapbuf->xvimage || error_caught) {
+      if (error_caught) {
+        GST_ERROR_OBJECT (evaspixmapsink, "error_caught!");
+      }
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      /* Reset error handler */
+      error_caught = FALSE;
+      XSetErrorHandler (handler);
+      /* Push an error */
+      GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+          ("Failed to create output image buffer of %dx%d pixels",
+              evaspixmapbuf->width, evaspixmapbuf->height),
+          ("could not XvShmCreateImage a %dx%d image", evaspixmapbuf->width,
+              evaspixmapbuf->height));
+      goto beach_unlocked;
+    }
+
+    /* we have to use the returned data_size for our shm size */
+    evaspixmapbuf->size = evaspixmapbuf->xvimage->data_size;
+    GST_LOG_OBJECT (evaspixmapsink, "XShm image size is %" G_GSIZE_FORMAT,
+        evaspixmapbuf->size);
+
+    /* calculate the expected size.  This is only for sanity checking the
+     * number we get from X. */
+    switch (evaspixmapbuf->im_format) {
+      case GST_VIDEO_FORMAT_I420:
+      case GST_VIDEO_FORMAT_YV12:
+      {
+        gint pitches[3];
+        gint offsets[3];
+        guint plane;
+
+        offsets[0] = 0;
+        pitches[0] = GST_ROUND_UP_4 (evaspixmapbuf->width);
+        offsets[1] =
+            offsets[0] + pitches[0] * GST_ROUND_UP_2 (evaspixmapbuf->height);
+        pitches[1] = GST_ROUND_UP_8 (evaspixmapbuf->width) / 2;
+        offsets[2] =
+            offsets[1] +
+            pitches[1] * GST_ROUND_UP_2 (evaspixmapbuf->height) / 2;
+        pitches[2] = GST_ROUND_UP_8 (pitches[0]) / 2;
+
+        expected_size =
+            offsets[2] +
+            pitches[2] * GST_ROUND_UP_2 (evaspixmapbuf->height) / 2;
+
+        for (plane = 0; plane < evaspixmapbuf->xvimage->num_planes; plane++) {
+          GST_DEBUG_OBJECT (evaspixmapsink,
+              "Plane %u has a expected pitch of %d bytes, " "offset of %d",
+              plane, pitches[plane], offsets[plane]);
+        }
+        break;
+      }
+      case GST_VIDEO_FORMAT_YUY2:
+      case GST_VIDEO_FORMAT_UYVY:
+        expected_size =
+            evaspixmapbuf->height * GST_ROUND_UP_4 (evaspixmapbuf->width * 2);
+        break;
+      case GST_VIDEO_FORMAT_ST12:
+      case GST_VIDEO_FORMAT_SN12:
+        expected_size = sizeof (MMVideoBuffer);
+        break;
+      default:
+        expected_size = 0;
+        break;
+    }
+    if (expected_size != 0 && evaspixmapbuf->size != expected_size) {
+      GST_WARNING_OBJECT (evaspixmapsink,
+          "unexpected XShm image size (got %" G_GSIZE_FORMAT ", expected %d)",
+          evaspixmapbuf->size, expected_size);
+    }
+
+    /* Be verbose about our XvImage stride */
+    {
+      guint plane;
+      for (plane = 0; plane < evaspixmapbuf->xvimage->num_planes; plane++) {
+        GST_DEBUG_OBJECT (evaspixmapsink,
+            "Plane %u has a pitch of %d bytes, " "offset of %d", plane,
+            evaspixmapbuf->xvimage->pitches[plane],
+            evaspixmapbuf->xvimage->offsets[plane]);
+      }
+    }
+
+    evaspixmapbuf->SHMInfo.shmid =
+        shmget (IPC_PRIVATE, evaspixmapbuf->size, IPC_CREAT | 0777);
+    if (evaspixmapbuf->SHMInfo.shmid == -1) {
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+          ("Failed to create output image buffer of %dx%d pixels",
+              evaspixmapbuf->width, evaspixmapbuf->height),
+          ("could not get shared memory of %" G_GSIZE_FORMAT " bytes",
+              evaspixmapbuf->size));
+      goto beach_unlocked;
+    }
+
+    evaspixmapbuf->SHMInfo.shmaddr =
+        shmat (evaspixmapbuf->SHMInfo.shmid, NULL, 0);
+    if (evaspixmapbuf->SHMInfo.shmaddr == ((void *) -1)) {
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+          ("Failed to create output image buffer of %dx%d pixels",
+              evaspixmapbuf->width, evaspixmapbuf->height),
+          ("Failed to shmat: %s", g_strerror (errno)));
+      /* Clean up the shared memory segment */
+      shmctl (evaspixmapbuf->SHMInfo.shmid, IPC_RMID, NULL);
+      goto beach_unlocked;
+    }
+
+    evaspixmapbuf->xvimage->data = evaspixmapbuf->SHMInfo.shmaddr;
+    evaspixmapbuf->SHMInfo.readOnly = FALSE;
+
+    if (XShmAttach (evaspixmapsink->xcontext->disp,
+            &evaspixmapbuf->SHMInfo) == 0) {
+      /* Clean up the shared memory segment */
+      shmctl (evaspixmapbuf->SHMInfo.shmid, IPC_RMID, NULL);
+
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+          ("Failed to create output image buffer of %dx%d pixels",
+              evaspixmapbuf->width, evaspixmapbuf->height),
+          ("Failed to XShmAttach"));
+      goto beach_unlocked;
+    }
+
+    XSync (evaspixmapsink->xcontext->disp, FALSE);
+
+    /* Delete the shared memory segment as soon as we everyone is attached.
+     * This way, it will be deleted as soon as we detach later, and not
+     * leaked if we crash. */
+    shmctl (evaspixmapbuf->SHMInfo.shmid, IPC_RMID, NULL);
+
+    GST_DEBUG_OBJECT (evaspixmapsink, "XServer ShmAttached to 0x%x, id 0x%lx",
+        evaspixmapbuf->SHMInfo.shmid, evaspixmapbuf->SHMInfo.shmseg);
+  } else
+#endif /* HAVE_XSHM */
+  {
+    evaspixmapbuf->xvimage =
+        XvCreateImage (evaspixmapsink->xcontext->disp,
+        evaspixmapsink->xcontext->xv_port_id, evaspixmapbuf->im_format, NULL,
+        evaspixmapsink->aligned_width, evaspixmapsink->aligned_height);
+    if (!evaspixmapbuf->xvimage || error_caught) {
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      /* Reset error handler */
+      error_caught = FALSE;
+      XSetErrorHandler (handler);
+      /* Push an error */
+      GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+          ("Failed to create outputimage buffer of %dx%d pixels",
+              evaspixmapbuf->width, evaspixmapbuf->height),
+          ("could not XvCreateImage a %dx%d image",
+              evaspixmapbuf->width, evaspixmapbuf->height));
+      goto beach_unlocked;
+    }
+
+    /* we have to use the returned data_size for our image size */
+    evaspixmapbuf->size = evaspixmapbuf->xvimage->data_size;
+    evaspixmapbuf->xvimage->data = g_malloc (evaspixmapbuf->size);
+
+    XSync (evaspixmapsink->xcontext->disp, FALSE);
+  }
+
+  /* Reset error handler */
+  error_caught = FALSE;
+  XSetErrorHandler (handler);
+
+  succeeded = TRUE;
+
+  gst_buffer_replace_all_memory (evaspixmapbuf->buffer,
+      gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
+          (guchar *) evaspixmapbuf->xvimage->data, evaspixmapbuf->size, 0,
+          evaspixmapbuf->size, evaspixmapbuf, g_free));
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+beach_unlocked:
+  if (!succeeded) {
+    gst_evaspixmap_buffer_free (evaspixmapbuf);
+    evaspixmapbuf = NULL;
+  }
+
+  return evaspixmapbuf;
+}
+
+/* This function puts a GstEvasPixmapBuffer on a GstEvasPixmapSink's pixmap. Returns FALSE
+ * if no pixmap was available  */
+static gboolean
+gst_evaspixmap_buffer_put (GstEvasPixmapSink * evaspixmapsink,
+    GstEvasPixmapBuffer * evaspixmapbuf)
+{
+  FUNCTION_ENTER ();
+
+  GstVideoRectangle result;
+
+  GstVideoRectangle src_origin = { 0, 0, 0, 0 };
+  GstVideoRectangle src_input = { 0, 0, 0, 0 };
+  GstVideoRectangle src = { 0, 0, 0, 0 };
+  GstVideoRectangle dst = { 0, 0, 0, 0 };
+  int rotate = 0;
+  int ret = 0;
+  int idx = 0;
+  GstXPixmap *xpixmap = NULL;
+  int i = 0;
+  int (*handler) (Display *, XErrorEvent *) = NULL;
+
+  /* We take the flow_lock. If expose is in there we don't want to run
+     concurrently from the data flow thread */
+
+  if (G_UNLIKELY (evaspixmapsink->xpixmap[idx] == NULL)) {
+    GST_WARNING_OBJECT (evaspixmapsink, "xpixmap is NULL. Skip buffer_put.");
+    return FALSE;
+  }
+  if (evaspixmapsink->visible == FALSE) {
+    GST_WARNING_OBJECT (evaspixmapsink, "visible is FALSE. Skip buffer_put.");
+    return TRUE;
+  }
+  if (!evaspixmapbuf) {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "evaspixmapbuf is NULL. Skip buffer_put.");
+    return TRUE;
+  }
+  g_mutex_lock (&evaspixmapsink->pixmap_ref_lock);
+  if (evaspixmapsink->last_updated_idx == -1) {
+    /* if it has never been updated any frame in Ecore thread, do below */
+    idx = 0;
+    xpixmap = evaspixmapsink->xpixmap[idx];
+    xpixmap->ref = 1;
+    GST_LOG_OBJECT (evaspixmapsink,
+        "last_updated_idx(%d), we use index[%d] of pixmap buffers : pixmap(%ld), ref(%d)",
+        evaspixmapsink->last_updated_idx, idx, xpixmap->pixmap, xpixmap->ref);
+  } else {
+    for (idx = 0; idx < evaspixmapsink->num_of_pixmaps; idx++) {
+      if (idx == evaspixmapsink->last_updated_idx) {
+        continue;
+      } else {
+        xpixmap = evaspixmapsink->xpixmap[idx];
+        if (xpixmap->ref == 0 && xpixmap->damaged_time == 0) {
+          xpixmap->ref++;
+          GST_LOG_OBJECT (evaspixmapsink,
+              "found an available pixmap(%ld) : xpixmap[%d]", xpixmap->pixmap,
+              idx);
+          GST_INFO_OBJECT (evaspixmapsink,
+              "pixmap ref-count INCREASED : pixmap(%ld), refcount(%d)",
+              xpixmap->pixmap, xpixmap->ref);
+          break;
+        }
+      }
+    }
+    if (idx == evaspixmapsink->num_of_pixmaps) {
+      GST_LOG_OBJECT (evaspixmapsink,
+          "Could not find a pixmap with idle state, skip buffer_put.");
+      g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+      return TRUE;
+    }
+  }
+  g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+  gst_evaspixmapsink_xpixmap_update_geometry (evaspixmapsink, idx);
+
+  src.x = src.y = 0;
+  src_origin.x = src_origin.y = src_input.x = src_input.y = 0;
+  src_input.w = src_origin.w = evaspixmapsink->video_width;
+  src_input.h = src_origin.h = evaspixmapsink->video_height;
+  src.w = src_origin.w;
+  src.h = src_origin.h;
+
+  if (evaspixmapsink->use_origin_size ||
+      (evaspixmapsink->rotate_angle == DEGREE_0 ||
+          evaspixmapsink->rotate_angle == DEGREE_180)) {
+    src.w = src_origin.w;
+    src.h = src_origin.h;
+  } else {
+    src.w = src_origin.h;
+    src.h = src_origin.w;
+  }
+
+  dst.w = evaspixmapsink->render_rect.w;        /* pixmap width */
+  dst.h = evaspixmapsink->render_rect.h;        /* pixmap height */
+
+  if (!evaspixmapsink->use_origin_size) {
+    static Atom atom_rotation = None;
+    static Atom atom_hflip = None;
+    static Atom atom_vflip = None;
+    gboolean set_hflip = FALSE;
+    gboolean set_vflip = FALSE;
+
+    /* compensation of size information (between evas image object's and pixmap's) */
+    if (evaspixmapsink->sizediff_width > 1) {
+      if (evaspixmapsink->sizediff_height > 1) {
+        dst.w -= (evaspixmapsink->sizediff_width >> 1) << 1;
+        dst.h -= (evaspixmapsink->sizediff_height >> 1) << 1;
+      } else {
+        dst.w -= (evaspixmapsink->sizediff_width >> 1) << 1;
+      }
+    } else if (evaspixmapsink->sizediff_height > 1) {
+      dst.h -= (evaspixmapsink->sizediff_height >> 1) << 1;
+    }
+
+    switch (evaspixmapsink->display_geometry_method) {
+      case DISP_GEO_METHOD_LETTER_BOX:
+        gst_video_sink_center_rect (src, dst, &result, TRUE);
+        result.x += evaspixmapsink->render_rect.x;
+        result.y += evaspixmapsink->render_rect.y;
+        GST_DEBUG_OBJECT (evaspixmapsink, "GEO_METHOD : letter box");
+        break;
+      case DISP_GEO_METHOD_ORIGIN_SIZE:
+        gst_video_sink_center_rect (src, dst, &result, FALSE);
+        gst_video_sink_center_rect (dst, src, &src_input, FALSE);
+        GST_DEBUG_OBJECT (evaspixmapsink, "GEO_METHOD : origin size");
+        if (evaspixmapsink->rotate_angle == DEGREE_90 ||
+            evaspixmapsink->rotate_angle == DEGREE_270) {
+          src_input.x = src_input.x ^ src_input.y;
+          src_input.y = src_input.x ^ src_input.y;
+          src_input.x = src_input.x ^ src_input.y;
+          src_input.w = src_input.w ^ src_input.h;
+          src_input.h = src_input.w ^ src_input.h;
+          src_input.w = src_input.w ^ src_input.h;
+        }
+        break;
+      case DISP_GEO_METHOD_FULL_SCREEN:
+        result.x = result.y = 0;
+        result.w = evaspixmapsink->xpixmap[idx]->width;
+        result.h = evaspixmapsink->xpixmap[idx]->height;
+        GST_DEBUG_OBJECT (evaspixmapsink, "GEO_METHOD : full screen");
+        break;
+      case DISP_GEO_METHOD_CROPPED_FULL_SCREEN:
+        GST_DEBUG_OBJECT (evaspixmapsink, "GEO_METHOD : cropped full screen");
+        gst_video_sink_center_rect (dst, src, &src_input, TRUE);
+        result.x = result.y = 0;
+        result.w = dst.w;
+        result.h = dst.h;
+        if (evaspixmapsink->rotate_angle == DEGREE_90 ||
+            evaspixmapsink->rotate_angle == DEGREE_270) {
+          src_input.x = src_input.x ^ src_input.y;
+          src_input.y = src_input.x ^ src_input.y;
+          src_input.x = src_input.x ^ src_input.y;
+          src_input.w = src_input.w ^ src_input.h;
+          src_input.h = src_input.w ^ src_input.h;
+          src_input.w = src_input.w ^ src_input.h;
+        }
+        break;
+      case DISP_GEO_METHOD_ORIGIN_SIZE_OR_LETTER_BOX:
+        if (src.w > dst.w || src.h > dst.h) {
+          /* LETTER BOX */
+          gst_video_sink_center_rect (src, dst, &result, TRUE);
+          result.x += evaspixmapsink->render_rect.x;
+          result.y += evaspixmapsink->render_rect.y;
+        } else {
+          /* ORIGIN SIZE */
+          gst_video_sink_center_rect (src, dst, &result, FALSE);
+          gst_video_sink_center_rect (dst, src, &src_input, FALSE);
+          if (evaspixmapsink->rotate_angle == DEGREE_90 ||
+              evaspixmapsink->rotate_angle == DEGREE_270) {
+            src_input.x = src_input.x ^ src_input.y;
+            src_input.y = src_input.x ^ src_input.y;
+            src_input.x = src_input.x ^ src_input.y;
+            src_input.w = src_input.w ^ src_input.h;
+            src_input.h = src_input.w ^ src_input.h;
+            src_input.w = src_input.w ^ src_input.h;
+          }
+        }
+        GST_DEBUG_OBJECT (evaspixmapsink,
+            "GEO_METHOD : origin size or letter box");
+        break;
+      case DISP_GEO_METHOD_CUSTOM_ROI:
+        switch (evaspixmapsink->rotate_angle) {
+          case DEGREE_90:
+            result.w = evaspixmapsink->dst_roi.h;
+            result.h = evaspixmapsink->dst_roi.w;
+            result.x = evaspixmapsink->dst_roi.y;
+            result.y =
+                evaspixmapsink->xpixmap[idx]->height -
+                evaspixmapsink->dst_roi.x - evaspixmapsink->dst_roi.w;
+            break;
+          case DEGREE_180:
+            result.w = evaspixmapsink->dst_roi.w;
+            result.h = evaspixmapsink->dst_roi.h;
+            result.x =
+                evaspixmapsink->xpixmap[idx]->width - result.w -
+                evaspixmapsink->dst_roi.x;
+            result.y =
+                evaspixmapsink->xpixmap[idx]->height - result.h -
+                evaspixmapsink->dst_roi.y;
+            break;
+          case DEGREE_270:
+            result.w = evaspixmapsink->dst_roi.h;
+            result.h = evaspixmapsink->dst_roi.w;
+            result.x =
+                evaspixmapsink->xpixmap[idx]->width -
+                evaspixmapsink->dst_roi.y - evaspixmapsink->dst_roi.h;
+            result.y = evaspixmapsink->dst_roi.x;
+            break;
+          default:
+            result.x = evaspixmapsink->dst_roi.x;
+            result.y = evaspixmapsink->dst_roi.y;
+            result.w = evaspixmapsink->dst_roi.w;
+            result.h = evaspixmapsink->dst_roi.h;
+            break;
+        }
+        GST_LOG_OBJECT (evaspixmapsink,
+            "rotate[%d], ROI input[%d,%d,%dx%d] > result[%d,%d,%dx%d]",
+            evaspixmapsink->rotate_angle, evaspixmapsink->dst_roi.x,
+            evaspixmapsink->dst_roi.y, evaspixmapsink->dst_roi.w,
+            evaspixmapsink->dst_roi.h, result.x, result.y, result.w, result.h);
+      default:
+        break;
+    }
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "GEO_METHOD : src(%dx%d), dst(%dx%d), result(%dx%d), result_x(%d), result_y(%d)",
+        src.w, src.h, dst.w, dst.h, result.w, result.h, result.x, result.y);
+
+    switch (evaspixmapsink->rotate_angle) {
+      case DEGREE_0:
+        break;
+      case DEGREE_90:
+        rotate = 270;
+        break;
+      case DEGREE_180:
+        rotate = 180;
+        break;
+      case DEGREE_270:
+        rotate = 90;
+        break;
+      default:
+        GST_WARNING_OBJECT (evaspixmapsink,
+            "Unsupported rotation [%d]... set DEGREE 0.",
+            evaspixmapsink->rotate_angle);
+        break;
+    }
+
+    g_mutex_lock (&evaspixmapsink->x_lock);
+
+    /* set display rotation */
+    if (atom_rotation == None) {
+      atom_rotation =
+          XInternAtom (evaspixmapsink->xcontext->disp,
+          "_USER_WM_PORT_ATTRIBUTE_ROTATION", False);
+    }
+    ret =
+        XvSetPortAttribute (evaspixmapsink->xcontext->disp,
+        evaspixmapsink->xcontext->xv_port_id, atom_rotation, rotate);
+    if (ret != Success) {
+      GST_ERROR_OBJECT (evaspixmapsink,
+          "XvSetPortAttribute failed[%d]. disp[%p],xv_port_id[%ld],atom[%ld],rotate[%d]",
+          ret, evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xcontext->xv_port_id, atom_rotation, rotate);
+    }
+
+    /* set display flip */
+    if (atom_hflip == None) {
+      atom_hflip =
+          XInternAtom (evaspixmapsink->xcontext->disp,
+          "_USER_WM_PORT_ATTRIBUTE_HFLIP", False);
+    }
+    if (atom_vflip == None) {
+      atom_vflip =
+          XInternAtom (evaspixmapsink->xcontext->disp,
+          "_USER_WM_PORT_ATTRIBUTE_VFLIP", False);
+    }
+
+    switch (evaspixmapsink->flip) {
+      case FLIP_HORIZONTAL:
+        set_hflip = TRUE;
+        set_vflip = FALSE;
+        break;
+      case FLIP_VERTICAL:
+        set_hflip = FALSE;
+        set_vflip = TRUE;
+        break;
+      case FLIP_BOTH:
+        set_hflip = TRUE;
+        set_vflip = TRUE;
+        break;
+      case FLIP_NONE:
+      default:
+        set_hflip = FALSE;
+        set_vflip = FALSE;
+        break;
+    }
+    GST_INFO_OBJECT (evaspixmapsink, "set rotate %d HFLIP %d, VFLIP %d", rotate,
+        set_hflip, set_vflip);
+
+    ret =
+        XvSetPortAttribute (evaspixmapsink->xcontext->disp,
+        evaspixmapsink->xcontext->xv_port_id, atom_hflip, set_hflip);
+    if (ret != Success) {
+      GST_WARNING
+          ("set HFLIP failed[%d]. disp[%p],xv_port_id[%ld],atom[%ld],hflip[%d]",
+          ret, evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xcontext->xv_port_id, atom_hflip, set_hflip);
+    }
+    ret =
+        XvSetPortAttribute (evaspixmapsink->xcontext->disp,
+        evaspixmapsink->xcontext->xv_port_id, atom_vflip, set_vflip);
+    if (ret != Success) {
+      GST_WARNING
+          ("set VFLIP failed[%d]. disp[%p],xv_port_id[%ld],atom[%ld],vflip[%d]",
+          ret, evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xcontext->xv_port_id, atom_vflip, set_vflip);
+    }
+
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+  } else {
+    result.x = result.y = 0;
+    result.w = evaspixmapsink->xpixmap[idx]->width;
+    result.h = evaspixmapsink->xpixmap[idx]->height;
+    GST_DEBUG_OBJECT (evaspixmapsink, "USE ORIGIN SIZE, no geometry method");
+  }
+
+  if ((evaspixmapsink->result_prev.w != 0 && evaspixmapsink->result_prev.h != 0)
+      && (evaspixmapsink->src_prev.w == src_origin.w
+          && evaspixmapsink->src_prev.h == src_origin.h)
+      && (evaspixmapsink->result_prev.w != result.w
+          || evaspixmapsink->result_prev.h != result.h)) {
+    GST_WARNING
+        ("It will execute XFillRectangle..... evaspixmapsink->result_prev.w : %d, evaspixmapsink->result_prev.h: %d, result.w : %d, result.h : %d",
+        evaspixmapsink->result_prev.w, evaspixmapsink->result_prev.h, result.w,
+        result.h);
+    for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+      DRI2CreateDrawable (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xpixmap[i]->pixmap);
+      gst_evaspixmapsink_xpixmap_fillblack (evaspixmapsink->bufmgr_for_black,
+          evaspixmapsink->xcontext->disp, evaspixmapsink->xpixmap[i]->pixmap);
+      DRI2DestroyDrawable (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xpixmap[i]->pixmap);
+      GST_LOG_OBJECT (evaspixmapsink,
+          "fill black to xpixmap[%ld] with size(w:%d,h:%d)",
+          evaspixmapsink->xpixmap[i]->pixmap, evaspixmapsink->xpixmap[i]->width,
+          evaspixmapsink->xpixmap[i]->height);
+    }
+  }
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+  /* We scale to the pixmap's geometry */
+#ifdef HAVE_XSHM
+  if (evaspixmapsink->xcontext->use_xshm) {
+    GST_LOG_OBJECT (evaspixmapsink,
+        "XvShmPutImage with image %dx%d and pixmap %dx%d, from xvimage %"
+        GST_PTR_FORMAT, evaspixmapbuf->width, evaspixmapbuf->height,
+        evaspixmapsink->render_rect.w, evaspixmapsink->render_rect.h,
+        evaspixmapbuf);
+
+    /* Trim as proper size */
+    if (src_input.w % 2 == 1) {
+      src_input.w += 1;
+    }
+    if (src_input.h % 2 == 1) {
+      src_input.h += 1;
+    }
+    error_caught = FALSE;
+    handler = XSetErrorHandler (gst_evaspixmapsink_handle_xerror);
+
+    GST_LOG_OBJECT (evaspixmapsink,
+        "screen[%dx%d],pixmap[%d,%d,%dx%d],idx(%d)[%ld],method[%d],rotate[%d],src[%dx%d],dst[%d,%d,%dx%d],input[%d,%d,%dx%d],result[%d,%d,%dx%d]",
+        evaspixmapsink->scr_w, evaspixmapsink->scr_h,
+        evaspixmapsink->xpixmap[idx]->x, evaspixmapsink->xpixmap[idx]->y,
+        evaspixmapsink->xpixmap[idx]->width,
+        evaspixmapsink->xpixmap[idx]->height,
+        idx, evaspixmapsink->xpixmap[idx]->pixmap,
+        evaspixmapsink->display_geometry_method, rotate, src_origin.w,
+        src_origin.h, dst.x, dst.y, dst.w, dst.h, src_input.x, src_input.y,
+        src_input.w, src_input.h, result.x, result.y, result.w, result.h);
+
+    if (evaspixmapsink->visible) {
+      ret = XvShmPutImage (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xcontext->xv_port_id,
+          evaspixmapsink->xpixmap[idx]->pixmap,
+          evaspixmapsink->xpixmap[idx]->gc, evaspixmapbuf->xvimage,
+          src_input.x, src_input.y, src_input.w, src_input.h,
+          result.x, result.y, result.w, result.h, FALSE);
+      GST_LOG_OBJECT (evaspixmapsink, "XvShmPutImage return value [%d]", ret);
+    } else {
+      GST_WARNING_OBJECT (evaspixmapsink,
+          "visible is FALSE. skip this image...");
+    }
+    XSync (evaspixmapsink->xcontext->disp, FALSE);
+    if (ret != Success || error_caught) {
+      GST_WARNING ("putimage error");
+      if (evaspixmapsink->xpixmap[idx]->ref > 0) {
+        evaspixmapsink->xpixmap[idx]->ref--;
+        evaspixmapsink->xpixmap[idx]->damaged_time = 0;
+        GST_INFO_OBJECT (evaspixmapsink,
+            "pixmap ref-count DECREASED : pixmap(%ld), refcount(%d), damaged_time(%d), idx(%d)",
+            evaspixmapsink->xpixmap[idx]->pixmap,
+            evaspixmapsink->xpixmap[idx]->ref,
+            evaspixmapsink->xpixmap[idx]->damaged_time,
+            evaspixmapsink->last_updated_idx);
+      }
+    }
+    /* Reset error handler */
+    if (handler) {
+      error_caught = FALSE;
+      XSetErrorHandler (handler);
+    }
+  } else
+#endif /* HAVE_XSHM */
+  {
+    if (evaspixmapsink->visible) {
+      XvPutImage (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->xcontext->xv_port_id,
+          evaspixmapsink->xpixmap[idx]->pixmap,
+          evaspixmapsink->xpixmap[idx]->gc, evaspixmapbuf->xvimage,
+          evaspixmapsink->disp_x, evaspixmapsink->disp_y,
+          evaspixmapsink->disp_width, evaspixmapsink->disp_height,
+          result.x, result.y, result.w, result.h);
+    } else {
+      GST_WARNING_OBJECT (evaspixmapsink,
+          "visible is FALSE. skip this image...");
+    }
+  }
+  evaspixmapsink->src_prev.w = src_origin.w;
+  evaspixmapsink->src_prev.h = src_origin.h;
+
+  evaspixmapsink->result_prev.w = result.w;
+  evaspixmapsink->result_prev.h = result.h;
+
+  XSync (evaspixmapsink->xcontext->disp, FALSE);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+
+  return TRUE;
+}
+
+static int
+drm_init (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  Display *dpy;
+  int i = 0;
+  int eventBase = 0;
+  int errorBase = 0;
+  int dri2Major = 0;
+  int dri2Minor = 0;
+  char *driverName = NULL;
+  char *deviceName = NULL;
+  struct drm_auth auth_arg = { 0 };
+
+  evaspixmapsink->drm_fd = -1;
+
+  dpy = XOpenDisplay (0);
+
+  /* DRI2 */
+  if (!DRI2QueryExtension (dpy, &eventBase, &errorBase)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "failed to DRI2QueryExtension()");
+    goto ERROR_CASE;
+  }
+
+  if (!DRI2QueryVersion (dpy, &dri2Major, &dri2Minor)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "failed to DRI2QueryVersion");
+    goto ERROR_CASE;
+  }
+
+  if (!DRI2Connect (dpy, RootWindow (dpy, DefaultScreen (dpy)), &driverName,
+          &deviceName)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "failed to DRI2Connect");
+    goto ERROR_CASE;
+  }
+
+  if (!driverName || !deviceName) {
+    GST_ERROR_OBJECT (evaspixmapsink, "driverName or deviceName is not valid");
+    goto ERROR_CASE;
+  }
+
+  GST_INFO_OBJECT (evaspixmapsink, "Open drm device : %s", deviceName);
+
+  /* get the drm_fd though opening the deviceName */
+  evaspixmapsink->drm_fd = open (deviceName, O_RDWR);
+  if (evaspixmapsink->drm_fd < 0) {
+    GST_ERROR_OBJECT (evaspixmapsink, "cannot open drm device (%s)",
+        deviceName);
+    goto ERROR_CASE;
+  }
+
+  /* get magic from drm to authentication */
+  if (ioctl (evaspixmapsink->drm_fd, DRM_IOCTL_GET_MAGIC, &auth_arg)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "cannot get drm auth magic");
+    close (evaspixmapsink->drm_fd);
+    evaspixmapsink->drm_fd = -1;
+    goto ERROR_CASE;
+  }
+
+  if (!DRI2Authenticate (dpy, RootWindow (dpy, DefaultScreen (dpy)),
+          auth_arg.magic)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "cannot get drm authentication from X");
+    close (evaspixmapsink->drm_fd);
+    evaspixmapsink->drm_fd = -1;
+    goto ERROR_CASE;
+  }
+
+  /* init gem handle */
+  for (i = 0; i < MAX_GEM_BUFFER_NUM; i++) {
+    evaspixmapsink->gem_info[i].dmabuf_fd = 0;
+    evaspixmapsink->gem_info[i].gem_handle = 0;
+    evaspixmapsink->gem_info[i].gem_name = 0;
+    evaspixmapsink->gem_info[i].bo = 0;
+  }
+
+  XCloseDisplay (dpy);
+  free (driverName);
+  free (deviceName);
+
+  return 0;
+
+ERROR_CASE:
+  XCloseDisplay (dpy);
+  if (driverName) {
+    free (driverName);
+  }
+  if (deviceName) {
+    free (deviceName);
+  }
+
+  return -1;
+}
+
+static void
+drm_fini (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  if (evaspixmapsink->drm_fd >= 0) {
+    int i = 0;
+    for (i = 0; i < MAX_GEM_BUFFER_NUM; i++) {
+      if (evaspixmapsink->gem_info[i].dmabuf_fd > 0) {
+        GST_INFO_OBJECT (evaspixmapsink, "close gem_handle(%u)",
+            evaspixmapsink->gem_info[i].gem_handle);
+        drm_close_gem (evaspixmapsink, evaspixmapsink->gem_info[i].gem_handle);
+
+        evaspixmapsink->gem_info[i].dmabuf_fd = 0;
+        evaspixmapsink->gem_info[i].gem_handle = 0;
+        evaspixmapsink->gem_info[i].gem_name = 0;
+      } else if (evaspixmapsink->gem_info[i].bo > 0) {
+        evaspixmapsink->gem_info[i].gem_name = 0;
+        evaspixmapsink->gem_info[i].bo = 0;
+      } else {
+        break;
+      }
+    }
+    GST_INFO_OBJECT (evaspixmapsink, "close drm_fd(%d)",
+        evaspixmapsink->drm_fd);
+    close (evaspixmapsink->drm_fd);
+    evaspixmapsink->drm_fd = -1;
+  }
+}
+
+static unsigned int
+drm_convert_dmabuf_gemname (GstEvasPixmapSink * evaspixmapsink, int dmabuf_fd)
+{
+  FUNCTION_ENTER ();
+
+  struct drm_prime_handle prime_arg = { 0, };
+  struct drm_gem_flink flink_arg = { 0, };
+  int i = 0;
+
+  if (evaspixmapsink->drm_fd < 0) {
+    GST_ERROR_OBJECT (evaspixmapsink, "DRM is not opened");
+    return 0;
+  }
+
+  if (dmabuf_fd <= 0) {
+    GST_DEBUG_OBJECT (evaspixmapsink, "Ignore wrong dmabuf fd(%d)", dmabuf_fd); /* temporarily change log level to DEBUG for reducing WARNING level log */
+    return 0;
+  }
+
+  /* check duplicated dmabuf fd */
+  for (i = 0; i < MAX_GEM_BUFFER_NUM; i++) {
+    if (evaspixmapsink->gem_info[i].dmabuf_fd == dmabuf_fd) {
+      GST_LOG_OBJECT (evaspixmapsink, "already got fd(%u) with name(%u)",
+          dmabuf_fd, evaspixmapsink->gem_info[i].gem_name);
+      return evaspixmapsink->gem_info[i].gem_name;
+    }
+
+    if (evaspixmapsink->gem_info[i].dmabuf_fd == 0) {
+      GST_LOG_OBJECT (evaspixmapsink, "empty gem_info[%d] found", i);
+      break;
+    }
+  }
+
+  if (i == MAX_GEM_BUFFER_NUM) {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "too many buffers[dmabuf_fd(%d). skip it]", dmabuf_fd);
+    return 0;
+  }
+
+  evaspixmapsink->gem_info[i].dmabuf_fd = dmabuf_fd;
+  prime_arg.fd = dmabuf_fd;
+  if (ioctl (evaspixmapsink->drm_fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &prime_arg)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "non dmabuf fd(%d)", dmabuf_fd);
+    return 0;
+  }
+
+  evaspixmapsink->gem_info[i].gem_handle = prime_arg.handle;
+  GST_LOG_OBJECT (evaspixmapsink, "gem_info[%d].gem_handle = %u", i,
+      prime_arg.handle);
+
+  flink_arg.handle = prime_arg.handle;
+  if (ioctl (evaspixmapsink->drm_fd, DRM_IOCTL_GEM_FLINK, &flink_arg)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "cannot convert drm handle to name");
+    return 0;
+  }
+
+  evaspixmapsink->gem_info[i].gem_name = flink_arg.name;
+  GST_LOG_OBJECT (evaspixmapsink, "gem_info[%d].gem_name = %u", i,
+      flink_arg.name);
+
+  return flink_arg.name;
+}
+
+static void
+drm_close_gem (GstEvasPixmapSink * evaspixmapsink, unsigned int gem_handle)
+{
+  FUNCTION_ENTER ();
+
+  struct drm_gem_close close_arg = { 0, };
+
+  if (evaspixmapsink->drm_fd < 0) {
+    GST_ERROR_OBJECT (evaspixmapsink, "DRM is not opened");
+    return;
+  }
+
+  if (gem_handle == 0) {
+    GST_ERROR_OBJECT (evaspixmapsink, "invalid gem_handle(%d)", gem_handle);
+    return;
+  }
+
+  close_arg.handle = gem_handle;
+  if (gem_handle > 0
+      && ioctl (evaspixmapsink->drm_fd, DRM_IOCTL_GEM_CLOSE, &close_arg)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "cannot close drm gem handle(%d)",
+        gem_handle);
+    return;
+  }
+
+  return;
+}
+
+
+G_DEFINE_TYPE_EXTENDED (GstEvasPixmapSink, gst_evaspixmapsink,
+    GST_TYPE_VIDEO_SINK, 0, G_IMPLEMENT_INTERFACE (GST_TYPE_NAVIGATION,
+        gst_evaspixmapsink_navigation_init)
+    G_IMPLEMENT_INTERFACE (GST_TYPE_COLOR_BALANCE,
+        gst_evaspixmapsink_colorbalance_init)
+    G_IMPLEMENT_INTERFACE (GST_TYPE_PROPERTY_PROBE,
+        gst_evaspixmapsink_property_probe_interface_init));
+
+
+/* This function destroys a GstXPixmap */
+static void
+gst_evaspixmapsink_xpixmap_destroy (GstEvasPixmapSink * evaspixmapsink,
+    GstXPixmap * xpixmap)
+{
+  FUNCTION_ENTER ();
+
+  g_return_if_fail (xpixmap != NULL);
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+  if (xpixmap->pixmap) {
+    XFreePixmap (evaspixmapsink->xcontext->disp, xpixmap->pixmap);
+    xpixmap->pixmap = 0;
+    GST_DEBUG_OBJECT (evaspixmapsink, "Free pixmap");
+  }
+
+  if (xpixmap->gc) {
+    XFreeGC (evaspixmapsink->xcontext->disp, xpixmap->gc);
+  }
+
+  XSync (evaspixmapsink->xcontext->disp, FALSE);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+  g_free (xpixmap);
+}
+
+static void
+gst_evaspixmapsink_xpixmap_update_geometry (GstEvasPixmapSink * evaspixmapsink,
+    int idx)
+{
+  FUNCTION_ENTER ();
+
+  Window root_window;
+  XWindowAttributes root_attr;
+
+  int cur_pixmap_x = 0;
+  int cur_pixmap_y = 0;
+  unsigned int cur_pixmap_width = 0;
+  unsigned int cur_pixmap_height = 0;
+  unsigned int cur_pixmap_border_width = 0;
+  unsigned int cur_pixmap_depth = 0;
+
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  /* Update the window geometry */
+  g_mutex_lock (&evaspixmapsink->x_lock);
+  if (G_UNLIKELY (evaspixmapsink->xpixmap[idx] == NULL)) {
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+    return;
+  }
+
+  /* Get root window and size of current pixmap */
+  XGetGeometry (evaspixmapsink->xcontext->disp, evaspixmapsink->xpixmap[idx]->pixmap, &root_window, &cur_pixmap_x, &cur_pixmap_y,       /* relative x, y, for pixmap these are alway 0 */
+      &cur_pixmap_width, &cur_pixmap_height, &cur_pixmap_border_width, &cur_pixmap_depth);      /* cur_pixmap_border_width, cur_pixmap_depth are not used */
+
+  evaspixmapsink->xpixmap[idx]->width = cur_pixmap_width;
+  evaspixmapsink->xpixmap[idx]->height = cur_pixmap_height;
+
+  evaspixmapsink->xpixmap[idx]->x = cur_pixmap_x;
+  evaspixmapsink->xpixmap[idx]->y = cur_pixmap_y;
+
+  /* Get size of root window == size of screen */
+  XGetWindowAttributes (evaspixmapsink->xcontext->disp, root_window,
+      &root_attr);
+
+  evaspixmapsink->scr_w = root_attr.width;
+  evaspixmapsink->scr_h = root_attr.height;
+
+  if (!evaspixmapsink->have_render_rect) {
+    evaspixmapsink->render_rect.x = evaspixmapsink->render_rect.y = 0;
+    evaspixmapsink->render_rect.w = cur_pixmap_width;
+    evaspixmapsink->render_rect.h = cur_pixmap_height;
+  }
+
+  GST_LOG_OBJECT (evaspixmapsink,
+      "screen size %dx%d, current pixmap geometry %d,%d,%dx%d, render_rect %d,%d,%dx%d",
+      evaspixmapsink->scr_w, evaspixmapsink->scr_h,
+      evaspixmapsink->xpixmap[idx]->x, evaspixmapsink->xpixmap[idx]->y,
+      evaspixmapsink->xpixmap[idx]->width, evaspixmapsink->xpixmap[idx]->height,
+      evaspixmapsink->render_rect.x, evaspixmapsink->render_rect.y,
+      evaspixmapsink->render_rect.w, evaspixmapsink->render_rect.h);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+}
+
+static void
+gst_evaspixmapsink_xpixmap_clear (GstEvasPixmapSink * evaspixmapsink,
+    GstXPixmap * xpixmap)
+{
+  FUNCTION_ENTER ();
+
+  g_return_if_fail (xpixmap != NULL);
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  if (!xpixmap->pixmap) {
+    GST_WARNING_OBJECT (evaspixmapsink, "pixmap was not created..");
+    return;
+  }
+
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+  if (!evaspixmapsink->xcontext) {
+    GST_WARNING_OBJECT (evaspixmapsink, "xcontext is null..");
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+    return;
+  }
+
+  if (evaspixmapsink->stop_video) {
+    XvStopVideo (evaspixmapsink->xcontext->disp,
+        evaspixmapsink->xcontext->xv_port_id, xpixmap->pixmap);
+  }
+  /* Preview area is not updated before other UI is updated in the screen. */
+  XSetForeground (evaspixmapsink->xcontext->disp, xpixmap->gc,
+      evaspixmapsink->xcontext->black);
+  DRI2CreateDrawable (evaspixmapsink->xcontext->disp, xpixmap->pixmap);
+  gst_evaspixmapsink_xpixmap_fillblack (evaspixmapsink->bufmgr_for_black,
+      evaspixmapsink->xcontext->disp, xpixmap->pixmap);
+  DRI2DestroyDrawable (evaspixmapsink->xcontext->disp, xpixmap->pixmap);
+
+  XSync (evaspixmapsink->xcontext->disp, FALSE);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+  g_mutex_lock (&evaspixmapsink->pixmap_ref_lock);
+  evaspixmapsink->last_updated_idx = -1;
+  xpixmap->ref = 0;
+  xpixmap->damaged_time = 0;
+  g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+}
+
+/* This function commits our internal colorbalance settings to our grabbed Xv
+   port. If the xcontext is not initialized yet it simply returns */
+static void
+gst_evaspixmapsink_update_colorbalance (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  GList *channels = NULL;
+
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  /* If we haven't initialized the X context we can't update anything */
+  if (evaspixmapsink->xcontext == NULL)
+    return;
+
+  /* Don't set the attributes if they haven't been changed, to avoid
+   * rounding errors changing the values */
+  if (!evaspixmapsink->cb_changed)
+    return;
+
+  /* For each channel of the colorbalance we calculate the correct value
+     doing range conversion and then set the Xv port attribute to match our
+     values. */
+  channels = evaspixmapsink->xcontext->channels_list;
+
+  while (channels) {
+    if (channels->data && GST_IS_COLOR_BALANCE_CHANNEL (channels->data)) {
+      GstColorBalanceChannel *channel = NULL;
+      Atom prop_atom;
+      gint value = 0;
+      gdouble convert_coef;
+
+      channel = GST_COLOR_BALANCE_CHANNEL (channels->data);
+      g_object_ref (channel);
+
+      /* Our range conversion coef */
+      convert_coef = (channel->max_value - channel->min_value) / 2000.0;
+
+      if (g_ascii_strcasecmp (channel->label, "XV_HUE") == 0) {
+        value = evaspixmapsink->hue;
+      } else if (g_ascii_strcasecmp (channel->label, "XV_SATURATION") == 0) {
+        value = evaspixmapsink->saturation;
+      } else if (g_ascii_strcasecmp (channel->label, "XV_CONTRAST") == 0) {
+        value = evaspixmapsink->contrast;
+      } else if (g_ascii_strcasecmp (channel->label, "XV_BRIGHTNESS") == 0) {
+        value = evaspixmapsink->brightness;
+      } else {
+        g_warning ("got an unknown channel %s", channel->label);
+        g_object_unref (channel);
+        return;
+      }
+
+      /* Committing to Xv port */
+      g_mutex_lock (&evaspixmapsink->x_lock);
+      prop_atom =
+          XInternAtom (evaspixmapsink->xcontext->disp, channel->label, True);
+      if (prop_atom != None) {
+        int xv_value;
+        xv_value =
+            floor (0.5 + (value + 1000) * convert_coef + channel->min_value);
+        XvSetPortAttribute (evaspixmapsink->xcontext->disp,
+            evaspixmapsink->xcontext->xv_port_id, prop_atom, xv_value);
+      }
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+
+      g_object_unref (channel);
+    }
+    channels = g_list_next (channels);
+  }
+}
+
+static void
+gst_lookup_xv_port_from_adaptor (GstXContext * xcontext,
+    XvAdaptorInfo * adaptors, int adaptor_no)
+{
+  FUNCTION_ENTER ();
+
+  gint j;
+  gint res;
+
+  /* Do we support XvImageMask ? */
+  if (!(adaptors[adaptor_no].type & XvImageMask)) {
+    GST_DEBUG ("XV Adaptor %s has no support for XvImageMask",
+        adaptors[adaptor_no].name);
+    return;
+  }
+
+  /* We found such an adaptor, looking for an available port */
+  for (j = 0; j < adaptors[adaptor_no].num_ports && !xcontext->xv_port_id; j++) {
+    /* We try to grab the port */
+    res = XvGrabPort (xcontext->disp, adaptors[adaptor_no].base_id + j, 0);
+    if (Success == res) {
+      xcontext->xv_port_id = adaptors[adaptor_no].base_id + j;
+      GST_DEBUG ("XV Adaptor %s with %ld ports", adaptors[adaptor_no].name,
+          adaptors[adaptor_no].num_ports);
+    } else {
+      GST_DEBUG ("GrabPort %d for XV Adaptor %s failed: %d", j,
+          adaptors[adaptor_no].name, res);
+    }
+  }
+}
+
+/* This function generates a caps with all supported format by the first
+   Xv grabable port we find. We store each one of the supported formats in a
+   format list and append the format to a newly created caps that we return
+   If this function does not return NULL because of an error, it also grabs
+   the port via XvGrabPort */
+static GstCaps *
+gst_evaspixmapsink_get_xv_support (GstEvasPixmapSink * evaspixmapsink,
+    GstXContext * xcontext)
+{
+  FUNCTION_ENTER ();
+
+  gint i;
+  XvAdaptorInfo *adaptors;
+  gint nb_formats;
+  XvImageFormatValues *formats = NULL;
+  guint nb_encodings;
+  XvEncodingInfo *encodings = NULL;
+  gulong max_w = G_MAXINT, max_h = G_MAXINT;
+  GstCaps *caps = NULL;
+  GstCaps *rgb_caps = NULL;
+
+  g_return_val_if_fail (xcontext != NULL, NULL);
+
+  /* First let's check that XVideo extension is available */
+  if (!XQueryExtension (xcontext->disp, "XVideo", &i, &i, &i)) {
+    GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, SETTINGS,
+        ("Could not initialise Xv output"),
+        ("XVideo extension is not available"));
+    return NULL;
+  }
+
+  /* Then we get adaptors list */
+  if (Success != XvQueryAdaptors (xcontext->disp, xcontext->root,
+          &xcontext->nb_adaptors, &adaptors)) {
+    GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, SETTINGS,
+        ("Could not initialise Xv output"),
+        ("Failed getting XV adaptors list"));
+    return NULL;
+  }
+
+  xcontext->xv_port_id = 0;
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "Found %u XV adaptor(s)",
+      xcontext->nb_adaptors);
+
+  xcontext->adaptors =
+      (gchar **) g_malloc0 (xcontext->nb_adaptors * sizeof (gchar *));
+
+  /* Now fill up our adaptor name array */
+  for (i = 0; i < xcontext->nb_adaptors; i++) {
+    xcontext->adaptors[i] = g_strdup (adaptors[i].name);
+  }
+
+  if (evaspixmapsink->adaptor_no < xcontext->nb_adaptors) {
+    /* Find xv port from user defined adaptor */
+    gst_lookup_xv_port_from_adaptor (xcontext, adaptors,
+        evaspixmapsink->adaptor_no);
+  }
+
+  if (!xcontext->xv_port_id) {
+    /* Now search for an adaptor that supports XvImageMask */
+    for (i = 0; i < xcontext->nb_adaptors && !xcontext->xv_port_id; i++) {
+      gst_lookup_xv_port_from_adaptor (xcontext, adaptors, i);
+      evaspixmapsink->adaptor_no = i;
+    }
+  }
+
+  XvFreeAdaptorInfo (adaptors);
+
+  if (!xcontext->xv_port_id) {
+    evaspixmapsink->adaptor_no = -1;
+    GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, BUSY,
+        ("Could not initialise Xv output"), ("No port available"));
+    return NULL;
+  }
+
+  /* Set XV_AUTOPAINT_COLORKEY and XV_DOUBLE_BUFFER and XV_COLORKEY */
+  {
+    int count, todo = 3;
+    XvAttribute *const attr = XvQueryPortAttributes (xcontext->disp,
+        xcontext->xv_port_id, &count);
+    static const char autopaint[] = "XV_AUTOPAINT_COLORKEY";
+    static const char dbl_buffer[] = "XV_DOUBLE_BUFFER";
+    static const char colorkey[] = "XV_COLORKEY";
+
+    GST_DEBUG_OBJECT (evaspixmapsink, "Checking %d Xv port attributes", count);
+
+    evaspixmapsink->have_autopaint_colorkey = FALSE;
+    evaspixmapsink->have_double_buffer = FALSE;
+    evaspixmapsink->have_colorkey = FALSE;
+
+    for (i = 0; ((i < count) && todo); i++)
+      if (!strcmp (attr[i].name, autopaint)) {
+        const Atom atom = XInternAtom (xcontext->disp, autopaint, False);
+
+        /* turn on autopaint colorkey */
+        XvSetPortAttribute (xcontext->disp, xcontext->xv_port_id, atom,
+            (evaspixmapsink->autopaint_colorkey ? 1 : 0));
+        todo--;
+        evaspixmapsink->have_autopaint_colorkey = TRUE;
+      } else if (!strcmp (attr[i].name, dbl_buffer)) {
+        const Atom atom = XInternAtom (xcontext->disp, dbl_buffer, False);
+
+        XvSetPortAttribute (xcontext->disp, xcontext->xv_port_id, atom,
+            (evaspixmapsink->double_buffer ? 1 : 0));
+        todo--;
+        evaspixmapsink->have_double_buffer = TRUE;
+      } else if (!strcmp (attr[i].name, colorkey)) {
+        /* Set the colorkey, default is something that is dark but hopefully
+         * won't randomly appear on the screen elsewhere (ie not black or greys)
+         * can be overridden by setting "colorkey" property
+         */
+        const Atom atom = XInternAtom (xcontext->disp, colorkey, False);
+        guint32 ckey = 0;
+        gboolean set_attr = TRUE;
+        guint cr, cg, cb;
+
+        /* set a colorkey in the right format RGB565/RGB888
+         * We only handle these 2 cases, because they're the only types of
+         * devices we've encountered. If we don't recognise it, leave it alone
+         */
+        cr = (evaspixmapsink->colorkey >> 16);
+        cg = (evaspixmapsink->colorkey >> 8) & 0xFF;
+        cb = (evaspixmapsink->colorkey) & 0xFF;
+        switch (xcontext->depth) {
+          case 16:             /* RGB 565 */
+            cr >>= 3;
+            cg >>= 2;
+            cb >>= 3;
+            ckey = (cr << 11) | (cg << 5) | cb;
+            break;
+          case 24:
+          case 32:             /* RGB 888 / ARGB 8888 */
+            ckey = (cr << 16) | (cg << 8) | cb;
+            break;
+          default:
+            GST_DEBUG_OBJECT (evaspixmapsink,
+                "Unknown bit depth %d for Xv Colorkey - not adjusting",
+                xcontext->depth);
+            set_attr = FALSE;
+            break;
+        }
+
+        if (set_attr) {
+          ckey = CLAMP (ckey, (guint32) attr[i].min_value,
+              (guint32) attr[i].max_value);
+          GST_LOG_OBJECT (evaspixmapsink,
+              "Setting color key for display depth %d to 0x%x", xcontext->depth,
+              ckey);
+
+          XvSetPortAttribute (xcontext->disp, xcontext->xv_port_id, atom,
+              (gint) ckey);
+        }
+        todo--;
+        evaspixmapsink->have_colorkey = TRUE;
+      }
+
+    XFree (attr);
+  }
+
+  /* Get the list of encodings supported by the adapter and look for the
+   * XV_IMAGE encoding so we can determine the maximum width and height
+   * supported */
+  XvQueryEncodings (xcontext->disp, xcontext->xv_port_id, &nb_encodings,
+      &encodings);
+
+  for (i = 0; i < nb_encodings; i++) {
+    GST_LOG_OBJECT (evaspixmapsink,
+        "Encoding %d, name %s, max wxh %lux%lu rate %d/%d",
+        i, encodings[i].name, encodings[i].width, encodings[i].height,
+        encodings[i].rate.numerator, encodings[i].rate.denominator);
+    if (strcmp (encodings[i].name, "XV_IMAGE") == 0) {
+      max_w = encodings[i].width;
+      max_h = encodings[i].height;
+      evaspixmapsink->scr_w = max_w;
+      evaspixmapsink->scr_h = max_h;
+    }
+  }
+
+  XvFreeEncodingInfo (encodings);
+
+  /* We get all image formats supported by our port */
+  formats = XvListImageFormats (xcontext->disp,
+      xcontext->xv_port_id, &nb_formats);
+  caps = gst_caps_new_empty ();
+  for (i = 0; i < nb_formats; i++) {
+    GstCaps *format_caps = NULL;
+    gboolean is_rgb_format = FALSE;
+    GstVideoFormat vformat;
+
+    /* We set the image format of the xcontext to an existing one. This
+       is just some valid image format for making our xshm calls check before
+       caps negotiation really happens. */
+    xcontext->im_format = formats[i].id;
+
+    switch (formats[i].type) {
+      case XvRGB:
+      {
+        XvImageFormatValues *fmt = &(formats[i]);
+        gint endianness =
+            (fmt->byte_order == LSBFirst ? G_LITTLE_ENDIAN : G_BIG_ENDIAN);
+
+        vformat = gst_video_format_from_masks (fmt->depth, fmt->bits_per_pixel,
+            endianness, fmt->red_mask, fmt->green_mask, fmt->blue_mask, 0);
+        if (vformat == GST_VIDEO_FORMAT_UNKNOWN)
+          break;
+        format_caps = gst_caps_new_simple ("video/x-raw",
+            "format", G_TYPE_STRING, gst_video_format_to_string (vformat),
+            "endianness", G_TYPE_INT, endianness,
+            "depth", G_TYPE_INT, fmt->depth,
+            "bpp", G_TYPE_INT, fmt->bits_per_pixel,
+            "red_mask", G_TYPE_INT, fmt->red_mask,
+            "green_mask", G_TYPE_INT, fmt->green_mask,
+            "blue_mask", G_TYPE_INT, fmt->blue_mask,
+            "width", GST_TYPE_INT_RANGE, 1, max_w,
+            "height", GST_TYPE_INT_RANGE, 1, max_h,
+            "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
+
+        is_rgb_format = TRUE;
+        break;
+      }
+      case XvYUV:
+        vformat = gst_video_format_from_fourcc (formats[i].id);
+        if (vformat == GST_VIDEO_FORMAT_UNKNOWN)
+          break;
+        format_caps = gst_caps_new_simple ("video/x-raw",
+            "format", G_TYPE_STRING, gst_video_format_to_string (vformat),
+            "width", GST_TYPE_INT_RANGE, 1, max_w,
+            "height", GST_TYPE_INT_RANGE, 1, max_h,
+            "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
+        break;
+      default:
+        vformat = GST_VIDEO_FORMAT_UNKNOWN;
+        g_assert_not_reached ();
+        break;
+    }
+
+    if (format_caps) {
+      GstEvasPixmapFormat *format = NULL;
+
+      format = g_new0 (GstEvasPixmapFormat, 1);
+      if (format) {
+        format->format = formats[i].id;
+        format->vformat = vformat;
+        format->caps = gst_caps_copy (format_caps);
+        xcontext->formats_list = g_list_append (xcontext->formats_list, format);
+      }
+
+      if (is_rgb_format) {
+        if (rgb_caps == NULL)
+          rgb_caps = format_caps;
+        else
+          gst_caps_append (rgb_caps, format_caps);
+      } else
+        gst_caps_append (caps, format_caps);
+    }
+  }
+
+  /* Collected all caps into either the caps or rgb_caps structures.
+   * Append rgb_caps on the end of YUV, so that YUV is always preferred */
+  if (rgb_caps)
+    gst_caps_append (caps, rgb_caps);
+
+  if (formats)
+    XFree (formats);
+
+  GST_DEBUG_OBJECT (evaspixmapsink,
+      "Generated the following caps: %" GST_PTR_FORMAT, caps);
+
+  if (gst_caps_is_empty (caps)) {
+    gst_caps_unref (caps);
+    XvUngrabPort (xcontext->disp, xcontext->xv_port_id, 0);
+    GST_ELEMENT_ERROR (evaspixmapsink, STREAM, WRONG_TYPE, (NULL),
+        ("No supported format found"));
+    return NULL;
+  }
+
+  return caps;
+}
+
+static gpointer
+gst_evaspixmapsink_event_thread (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  g_return_val_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink), NULL);
+  int damage_base = 0;
+  int damage_err_base = 0;
+  int damage_case = 0;
+  XEvent e;
+  int i = 0;
+  Display *disp = NULL;
+#ifdef DUMP_IMG
+  int ret = 0;
+  char file_name[128];
+  char *dump_data;
+#endif
+
+  GST_OBJECT_LOCK (evaspixmapsink);
+
+  if (evaspixmapsink->xcontext && evaspixmapsink->xcontext->disp) {
+    disp = evaspixmapsink->xcontext->disp;
+  } else {
+    GST_ERROR_OBJECT (evaspixmapsink,
+        "evaspixmapsink->xcontext(->disp) is not ready");
+    return NULL;
+  }
+
+  if (!XDamageQueryExtension (evaspixmapsink->xcontext->disp, &damage_base,
+          &damage_err_base)) {
+    GST_ERROR_OBJECT (evaspixmapsink, "XDamageQueryExtension() failed");
+    return NULL;
+  }
+  damage_case = (int) damage_base + XDamageNotify;
+
+  while (evaspixmapsink->running) {
+    GST_OBJECT_UNLOCK (evaspixmapsink);
+
+    g_mutex_lock (&evaspixmapsink->x_lock);
+    while (XPending (disp)) {
+      XNextEvent (disp, &e);
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      if (e.type == damage_case) {
+        XDamageNotifyEvent *damage_ev = (XDamageNotifyEvent *) & e;
+        for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+          GstXPixmap *xpixmap = evaspixmapsink->xpixmap[i];
+          if (xpixmap && damage_ev->drawable == xpixmap->pixmap) {
+            g_mutex_lock (&evaspixmapsink->pixmap_ref_lock);
+            if (xpixmap->ref) {
+              /* set it only if damage event comes from _buffer_put() */
+              xpixmap->damaged_time = (gint) get_millis_time ();
+            }
+            g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+            if (GST_STATE (evaspixmapsink) < GST_STATE_PLAYING
+                || log_warn_count < 20) {
+              GST_WARNING_OBJECT (evaspixmapsink,
+                  "event_handler : got a damage event for pixmap(%ld), refcount(%d), damaged_time(%d)",
+                  xpixmap->pixmap, xpixmap->ref, xpixmap->damaged_time);
+            } else {
+              GST_DEBUG_OBJECT (evaspixmapsink,
+                  "event_handler : got a damage event for pixmap(%ld), refcount(%d), damaged_time(%d)",
+                  xpixmap->pixmap, xpixmap->ref, xpixmap->damaged_time);
+            }
+            if (evaspixmapsink->epipe_request_count > EPIPE_REQUEST_LIMIT) {
+              GST_WARNING_OBJECT (evaspixmapsink,
+                  "event_handler : epipe_request_count(%d), skip ecore_pipe_write()",
+                  evaspixmapsink->epipe_request_count);
+            } else {
+              ecore_pipe_write (evaspixmapsink->epipe, evaspixmapsink,
+                  sizeof (GstEvasPixmapSink));
+              evaspixmapsink->epipe_request_count++;
+              if (GST_STATE (evaspixmapsink) < GST_STATE_PLAYING
+                  || log_warn_count < 20) {
+                GST_WARNING_OBJECT (evaspixmapsink,
+                    "event_handler : after call ecore_pipe_write() for pixmap(%ld)",
+                    xpixmap->pixmap);
+                log_warn_count++;
+              } else {
+                GST_DEBUG_OBJECT (evaspixmapsink,
+                    "event_handler : after call ecore_pipe_write() for pixmap(%ld)",
+                    xpixmap->pixmap);
+              }
+            }
+            g_mutex_lock (&evaspixmapsink->x_lock);
+            XDamageSubtract (evaspixmapsink->xcontext->disp,
+                evaspixmapsink->damage[i], None, None);
+            g_mutex_unlock (&evaspixmapsink->x_lock);
+#ifdef DUMP_IMG                 //after ecore_pipe_write
+            int dump_w = evaspixmapsink->w;     // + (32 - (evaspixmapsink->w % 32));   // for multiples of 32
+            if (g_cnt < 20) {
+              evaspixmapsink->pixmap_addr[i] =
+                  gst_evaspixmapsink_get_buffer (evaspixmapsink->xcontext->disp,
+                  evaspixmapsink->xpixmap[i]->pixmap, dump_w, evaspixmapsink->h,
+                  i);
+              GST_WARNING
+                  ("OUT_DUMP_%2.2d : pixmap[%d] addr %p (w : %d, h : %d)",
+                  g_cnt, i, evaspixmapsink->pixmap_addr[i], dump_w,
+                  evaspixmapsink->h);
+              sprintf (file_name, "/opt/usr/media/OUT_DUMP_%2.2d.dump", g_cnt);
+
+              dump_data = g_malloc (dump_w * evaspixmapsink->h * 4);
+              memcpy (dump_data, evaspixmapsink->pixmap_addr[i],
+                  dump_w * evaspixmapsink->h * 4);
+
+              ret =
+                  util_write_rawdata (file_name, dump_data,
+                  dump_w * evaspixmapsink->h * 4);
+              if (ret) {
+                GST_ERROR_OBJECT (evaspixmapsink,
+                    "util_write_rawdata() failed");
+              }
+              g_free (dump_data);
+
+              if (g_bufinfo[i]) {
+                gst_evaspixmapsink_free_buffer (i);
+                g_bufinfo[i] = NULL;
+              }
+              evaspixmapsink->pixmap_addr[i] = NULL;
+            }
+#endif
+            break;
+          }
+        }
+        if (i == evaspixmapsink->num_of_pixmaps) {
+          GST_WARNING_OBJECT (evaspixmapsink,
+              "event_handler : could not find corresponding pixmap with this damage event(%ld)",
+              damage_ev->drawable);
+        }
+      } else {
+        GST_LOG_OBJECT (evaspixmapsink,
+            "event_handler : unidentified event(%d)", e.type);
+        g_mutex_lock (&evaspixmapsink->x_lock);
+        continue;
+      }
+      g_mutex_lock (&evaspixmapsink->x_lock);
+    }
+    //XSync (disp, FALSE);
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+
+    g_usleep (G_USEC_PER_SEC / 40);
+    GST_OBJECT_LOCK (evaspixmapsink);
+  }
+  GST_OBJECT_UNLOCK (evaspixmapsink);
+  return NULL;
+}
+
+static void
+gst_evaspixmapsink_manage_event_thread (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  /* don't start the thread too early */
+  if (evaspixmapsink->xcontext == NULL) {
+    GST_ERROR_OBJECT (evaspixmapsink, "xcontext is NULL..");
+    return;
+  }
+
+  GST_OBJECT_LOCK (evaspixmapsink);
+
+  if (!evaspixmapsink->event_thread) {
+    /* Setup our event listening thread */
+    GST_DEBUG_OBJECT (evaspixmapsink, "run xevent thread");
+    evaspixmapsink->running = TRUE;
+    evaspixmapsink->event_thread =
+        g_thread_try_new ("evaspixmapsink-events",
+        (GThreadFunc) gst_evaspixmapsink_event_thread, evaspixmapsink, NULL);
+    if (!evaspixmapsink->event_thread) {
+      GST_ERROR ("creating event_thread failed");
+    }
+  } else {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "there already existed the event_thread.. keep going");
+    /* Do not finalize the thread in here, Only finalize the thread by calling gst_evaspixmapsink_reset() */
+  }
+
+  GST_OBJECT_UNLOCK (evaspixmapsink);
+}
+
+
+/* This function calculates the pixel aspect ratio based on the properties
+ * in the xcontext structure and stores it there. */
+static void
+gst_evaspixmapsink_calculate_pixel_aspect_ratio (GstXContext * xcontext)
+{
+  FUNCTION_ENTER ();
+
+  static const gint par[][2] = {
+    {1, 1},                     /* regular screen */
+    {16, 15},                   /* PAL TV */
+    {11, 10},                   /* 525 line Rec.601 video */
+    {54, 59},                   /* 625 line Rec.601 video */
+    {64, 45},                   /* 1280x1024 on 16:9 display */
+    {5, 3},                     /* 1280x1024 on 4:3 display */
+    {4, 3}                      /*  800x600 on 16:9 display */
+  };
+  gint i;
+  gint index;
+  gdouble ratio;
+  gdouble delta;
+
+#define DELTA(idx) (ABS (ratio - ((gdouble) par[idx][0] / par[idx][1])))
+
+  /* first calculate the "real" ratio based on the X values;
+   * which is the "physical" w/h divided by the w/h in pixels of the display */
+  ratio = (gdouble) (xcontext->widthmm * xcontext->height)
+      / (xcontext->heightmm * xcontext->width);
+
+  /* DirectFB's X in 720x576 reports the physical dimensions wrong, so
+   * override here */
+  if (xcontext->width == 720 && xcontext->height == 576) {
+    ratio = 4.0 * 576 / (3.0 * 720);
+  }
+  GST_DEBUG ("calculated pixel aspect ratio: %f", ratio);
+  /* now find the one from par[][2] with the lowest delta to the real one */
+  delta = DELTA (0);
+  index = 0;
+
+  for (i = 1; i < sizeof (par) / (sizeof (gint) * 2); ++i) {
+    gdouble this_delta = DELTA (i);
+
+    if (this_delta < delta) {
+      index = i;
+      delta = this_delta;
+    }
+  }
+
+  GST_DEBUG ("Decided on index %d (%d/%d)", index,
+      par[index][0], par[index][1]);
+
+  g_free (xcontext->par);
+  xcontext->par = g_new0 (GValue, 1);
+  g_value_init (xcontext->par, GST_TYPE_FRACTION);
+  gst_value_set_fraction (xcontext->par, par[index][0], par[index][1]);
+  GST_DEBUG ("set xcontext PAR to %d/%d",
+      gst_value_get_fraction_numerator (xcontext->par),
+      gst_value_get_fraction_denominator (xcontext->par));
+}
+
+/* This function gets the X Display and global info about it. Everything is
+   stored in our object and will be cleaned when the object is disposed. Note
+   here that caps for supported format are generated without any window or
+   image creation */
+static GstXContext *
+gst_evaspixmapsink_xcontext_get (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  GstXContext *xcontext = NULL;
+  XPixmapFormatValues *px_formats = NULL;
+  gint nb_formats = 0, i, j, N_attr;
+  XvAttribute *xv_attr;
+  Atom prop_atom;
+  const char *channels[4] =
+      { "XV_HUE", "XV_SATURATION", "XV_BRIGHTNESS", "XV_CONTRAST" };
+
+  g_return_val_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink), NULL);
+
+  xcontext = g_new0 (GstXContext, 1);
+  xcontext->im_format = 0;
+
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+  xcontext->disp = XOpenDisplay (evaspixmapsink->display_name);
+
+  if (!xcontext->disp) {
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+    g_free (xcontext);
+    GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, WRITE,
+        ("Could not initialise Xv output"), ("Could not open display"));
+    return NULL;
+  }
+  GST_WARNING_OBJECT (evaspixmapsink, "x display(%p)", xcontext->disp);
+  g_display_id = xcontext->disp;
+
+  xcontext->screen = DefaultScreenOfDisplay (xcontext->disp);
+  xcontext->screen_num = DefaultScreen (xcontext->disp);
+  xcontext->visual = DefaultVisual (xcontext->disp, xcontext->screen_num);
+  xcontext->root = DefaultRootWindow (xcontext->disp);
+  xcontext->white = XWhitePixel (xcontext->disp, xcontext->screen_num);
+  xcontext->black = XBlackPixel (xcontext->disp, xcontext->screen_num);
+  xcontext->depth = DefaultDepthOfScreen (xcontext->screen);
+
+  xcontext->width = DisplayWidth (xcontext->disp, xcontext->screen_num);
+  xcontext->height = DisplayHeight (xcontext->disp, xcontext->screen_num);
+  xcontext->widthmm = DisplayWidthMM (xcontext->disp, xcontext->screen_num);
+  xcontext->heightmm = DisplayHeightMM (xcontext->disp, xcontext->screen_num);
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "X reports %dx%d pixels and %d mm x %d mm",
+      xcontext->width, xcontext->height, xcontext->widthmm, xcontext->heightmm);
+
+  gst_evaspixmapsink_calculate_pixel_aspect_ratio (xcontext);
+  /* We get supported pixmap formats at supported depth */
+  px_formats = XListPixmapFormats (xcontext->disp, &nb_formats);
+
+  if (!px_formats) {
+    XCloseDisplay (xcontext->disp);
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+    g_free (xcontext->par);
+    g_free (xcontext);
+    GST_ELEMENT_ERROR (evaspixmapsink, RESOURCE, SETTINGS,
+        ("Could not initialise Xv output"), ("Could not get pixel formats"));
+    return NULL;
+  }
+
+  /* We get bpp value corresponding to our running depth */
+  for (i = 0; i < nb_formats; i++) {
+    if (px_formats[i].depth == xcontext->depth)
+      xcontext->bpp = px_formats[i].bits_per_pixel;
+  }
+
+  XFree (px_formats);
+
+  xcontext->endianness =
+      (ImageByteOrder (xcontext->disp) ==
+      LSBFirst) ? G_LITTLE_ENDIAN : G_BIG_ENDIAN;
+
+  /* our caps system handles 24/32bpp RGB as big-endian. */
+  if ((xcontext->bpp == 24 || xcontext->bpp == 32)
+      && xcontext->endianness == G_LITTLE_ENDIAN) {
+    xcontext->endianness = G_BIG_ENDIAN;
+    xcontext->visual->red_mask = GUINT32_TO_BE (xcontext->visual->red_mask);
+    xcontext->visual->green_mask = GUINT32_TO_BE (xcontext->visual->green_mask);
+    xcontext->visual->blue_mask = GUINT32_TO_BE (xcontext->visual->blue_mask);
+    if (xcontext->bpp == 24) {
+      xcontext->visual->red_mask >>= 8;
+      xcontext->visual->green_mask >>= 8;
+      xcontext->visual->blue_mask >>= 8;
+    }
+  }
+
+  xcontext->caps = gst_evaspixmapsink_get_xv_support (evaspixmapsink, xcontext);
+
+  if (!xcontext->caps) {
+    XCloseDisplay (xcontext->disp);
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+    g_free (xcontext->par);
+    g_free (xcontext);
+    /* GST_ELEMENT_ERROR is thrown by gst_evaspixmapsink_get_xv_support */
+    return NULL;
+  }
+#ifdef HAVE_XSHM
+  /* Search for XShm extension support */
+  if (XShmQueryExtension (xcontext->disp)
+      && gst_evaspixmapsink_check_xshm_calls (xcontext)) {
+    xcontext->use_xshm = TRUE;
+    GST_DEBUG_OBJECT (evaspixmapsink, "evaspixmapsink is using XShm extension");
+  } else
+#endif /* HAVE_XSHM */
+  {
+    xcontext->use_xshm = FALSE;
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "evaspixmapsink is not using XShm extension");
+  }
+
+  xv_attr =
+      XvQueryPortAttributes (xcontext->disp, xcontext->xv_port_id, &N_attr);
+
+  /* Generate the channels list */
+  for (i = 0; i < (sizeof (channels) / sizeof (char *)); i++) {
+    XvAttribute *matching_attr = NULL;
+
+    /* Retrieve the property atom if it exists. If it doesn't exist,
+     * the attribute itself must not either, so we can skip */
+    prop_atom = XInternAtom (xcontext->disp, channels[i], True);
+    if (prop_atom == None) {
+      continue;
+    }
+
+    if (xv_attr != NULL) {
+      for (j = 0; j < N_attr && matching_attr == NULL; ++j) {
+        if (!g_ascii_strcasecmp (channels[i], xv_attr[j].name)) {
+          matching_attr = xv_attr + j;
+        }
+      }
+    }
+
+    if (matching_attr) {
+      GstColorBalanceChannel *channel;
+      channel = g_object_new (GST_TYPE_COLOR_BALANCE_CHANNEL, NULL);
+      channel->label = g_strdup (channels[i]);
+      channel->min_value = matching_attr->min_value;
+      channel->max_value = matching_attr->max_value;
+
+      xcontext->channels_list =
+          g_list_append (xcontext->channels_list, channel);
+
+      /* If the colorbalance settings have not been touched we get Xv values
+         as defaults and update our internal variables */
+      if (!evaspixmapsink->cb_changed) {
+        gint val;
+        XvGetPortAttribute (xcontext->disp, xcontext->xv_port_id, prop_atom,
+            &val);
+        /* Normalize val to [-1000, 1000] */
+        val =
+            floor (0.5 + -1000 + 2000 * (val -
+                channel->min_value) / (double) (channel->max_value -
+                channel->min_value));
+
+        if (!g_ascii_strcasecmp (channels[i], "XV_HUE")) {
+          evaspixmapsink->hue = val;
+        } else if (!g_ascii_strcasecmp (channels[i], "XV_SATURATION")) {
+          evaspixmapsink->saturation = val;
+        } else if (!g_ascii_strcasecmp (channels[i], "XV_BRIGHTNESS")) {
+          evaspixmapsink->brightness = val;
+        } else if (!g_ascii_strcasecmp (channels[i], "XV_CONTRAST")) {
+          evaspixmapsink->contrast = val;
+        }
+      }
+    }
+  }
+
+  if (xv_attr) {
+    XFree (xv_attr);
+  }
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+  return xcontext;
+}
+
+/* This function cleans the X context. Closing the Display, releasing the XV
+   port and unrefing the caps for supported formats. */
+static void
+gst_evaspixmapsink_xcontext_clear (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  GList *formats_list, *channels_list;
+  GstXContext *xcontext;
+  gint i = 0;
+
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+
+  GST_OBJECT_LOCK (evaspixmapsink);
+  if (evaspixmapsink->xcontext == NULL) {
+    GST_OBJECT_UNLOCK (evaspixmapsink);
+    return;
+  }
+
+  /* Take the XContext from the sink and clean it up */
+  xcontext = evaspixmapsink->xcontext;
+  evaspixmapsink->xcontext = NULL;
+
+  GST_OBJECT_UNLOCK (evaspixmapsink);
+
+  formats_list = xcontext->formats_list;
+
+  while (formats_list) {
+    GstEvasPixmapFormat *format = formats_list->data;
+
+    gst_caps_unref (format->caps);
+    g_free (format);
+    formats_list = g_list_next (formats_list);
+  }
+
+  if (xcontext->formats_list)
+    g_list_free (xcontext->formats_list);
+
+  channels_list = xcontext->channels_list;
+
+  while (channels_list) {
+    GstColorBalanceChannel *channel = channels_list->data;
+
+    g_object_unref (channel);
+    channels_list = g_list_next (channels_list);
+  }
+
+  if (xcontext->channels_list)
+    g_list_free (xcontext->channels_list);
+
+  gst_caps_unref (xcontext->caps);
+
+  for (i = 0; i < xcontext->nb_adaptors; i++) {
+    g_free (xcontext->adaptors[i]);
+  }
+
+  g_free (xcontext->adaptors);
+
+  g_free (xcontext->par);
+
+  g_mutex_lock (&evaspixmapsink->x_lock);
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "Closing display and freeing X Context");
+
+  g_display_id = NULL;
+
+  XvUngrabPort (xcontext->disp, xcontext->xv_port_id, 0);
+
+  XCloseDisplay (xcontext->disp);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+
+  g_free (xcontext);
+}
+
+/* Element stuff */
+
+/* This function tries to get a format matching with a given caps in the
+   supported list of formats we generated in gst_evaspixmapsink_get_xv_support */
+static gint
+gst_evaspixmapsink_get_format_from_info (GstXContext * context,
+    GstVideoInfo * info)
+{
+  GList *list = NULL;
+
+  list = context->formats_list;
+
+  while (list) {
+    GstEvasPixmapFormat *format = list->data;
+
+    if (format && format->vformat == GST_VIDEO_INFO_FORMAT (info))
+      return format->format;
+
+    list = g_list_next (list);
+  }
+  return -1;
+}
+
+static GstCaps *
+gst_evaspixmapsink_getcaps (GstBaseSink * bsink, GstCaps * filter)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+  GstCaps *pad_caps;
+
+  evaspixmapsink = GST_EVASPIXMAPSINK (bsink);
+
+  if (filter)
+    GST_LOG_OBJECT (evaspixmapsink, "filter caps %" GST_PTR_FORMAT, filter);
+  if (evaspixmapsink->xcontext)
+    GST_LOG_OBJECT (evaspixmapsink, "context caps %" GST_PTR_FORMAT,
+        evaspixmapsink->xcontext->caps);
+
+  if (evaspixmapsink->xcontext)
+    return filter ? gst_caps_intersect (filter, evaspixmapsink->xcontext->caps)
+        : gst_caps_ref (evaspixmapsink->xcontext->caps);
+
+  pad_caps =
+      gst_pad_get_pad_template_caps (GST_VIDEO_SINK_PAD (evaspixmapsink));
+  return filter ? gst_caps_intersect (filter,
+      pad_caps) : gst_caps_copy (pad_caps);
+}
+
+static gboolean
+gst_evaspixmapsink_setcaps (GstBaseSink * bsink, GstCaps * caps)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+  GstStructure *structure;
+  guint32 im_format = 0;
+  gint video_width, video_height;
+  gint disp_x, disp_y;
+  gint disp_width, disp_height;
+  gint video_par_n, video_par_d;        /* video's PAR */
+  gint display_par_n, display_par_d;    /* display's PAR */
+  const GValue *caps_par;
+  const GValue *caps_disp_reg;
+  guint num, den;
+  gboolean enable_last_buffer;
+  GstVideoInfo info;
+
+
+  evaspixmapsink = GST_EVASPIXMAPSINK (bsink);
+
+  GST_DEBUG_OBJECT (evaspixmapsink,
+      "In setcaps. Possible caps %" GST_PTR_FORMAT ", setting caps %"
+      GST_PTR_FORMAT, evaspixmapsink->xcontext->caps, caps);
+
+  if (!gst_caps_can_intersect (evaspixmapsink->xcontext->caps, caps)) {
+    goto incompatible_caps;
+  }
+  if (!gst_video_info_from_caps (&info, caps))
+    goto incomplete_caps;
+
+  evaspixmapsink->negotiated_caps = gst_caps_copy (caps);
+  structure = gst_caps_get_structure (caps, 0);
+
+  video_width = info.width;
+  video_height = info.height;
+  evaspixmapsink->fps_n = info.fps_n;
+  evaspixmapsink->fps_d = info.fps_d;
+
+
+  evaspixmapsink->aligned_width = video_width;
+  evaspixmapsink->aligned_height = video_height;
+
+  /* get enable-last-buffer */
+  g_object_get (G_OBJECT (evaspixmapsink), "enable-last-sample",
+      &enable_last_buffer, NULL);
+  GST_INFO_OBJECT (evaspixmapsink, "current enable-last-sample : %d",
+      enable_last_buffer);
+  /* flush if enable-last-buffer is TRUE */
+  if (enable_last_buffer) {
+    GST_INFO_OBJECT (evaspixmapsink, "flush last-buffer");
+    g_object_set (G_OBJECT (evaspixmapsink), "enable-last-sample", FALSE, NULL);
+    g_object_set (G_OBJECT (evaspixmapsink), "enable-last-sample", TRUE, NULL);
+  }
+
+  if (evaspixmapsink->video_width != video_width
+      || evaspixmapsink->video_height != video_height) {
+    evaspixmapsink->src_prev.w = evaspixmapsink->video_width = video_width;
+    evaspixmapsink->src_prev.h = evaspixmapsink->video_height = video_height;
+    evaspixmapsink->need_to_fill_black = TRUE;
+  }
+
+  evaspixmapsink->info = info;
+
+  im_format =
+      gst_evaspixmapsink_get_format_from_info (evaspixmapsink->xcontext, &info);
+  if (im_format == -1) {
+    goto invalid_format;
+  }
+
+  /* get aspect ratio from caps if it's present, and
+   * convert video width and height to a display width and height
+   * using wd / hd = wv / hv * PARv / PARd */
+
+  /* get video's PAR */
+  caps_par = gst_structure_get_value (structure, "pixel-aspect-ratio");
+  if (caps_par) {
+    video_par_n = gst_value_get_fraction_numerator (caps_par);
+    video_par_d = gst_value_get_fraction_denominator (caps_par);
+  } else {
+    video_par_n = 1;
+    video_par_d = 1;
+  }
+  /* get display's PAR */
+  if (evaspixmapsink->par) {
+    display_par_n = gst_value_get_fraction_numerator (evaspixmapsink->par);
+    display_par_d = gst_value_get_fraction_denominator (evaspixmapsink->par);
+  } else {
+    display_par_n = 1;
+    display_par_d = 1;
+  }
+
+  /* get the display region */
+  caps_disp_reg = gst_structure_get_value (structure, "display-region");
+  if (caps_disp_reg) {
+    disp_x = g_value_get_int (gst_value_array_get_value (caps_disp_reg, 0));
+    disp_y = g_value_get_int (gst_value_array_get_value (caps_disp_reg, 1));
+    disp_width = g_value_get_int (gst_value_array_get_value (caps_disp_reg, 2));
+    disp_height =
+        g_value_get_int (gst_value_array_get_value (caps_disp_reg, 3));
+  } else {
+    disp_x = disp_y = 0;
+    disp_width = video_width;
+    disp_height = video_height;
+  }
+
+  if (!gst_video_calculate_display_ratio (&num, &den, video_width, video_height,
+          video_par_n, video_par_d, display_par_n, display_par_d)) {
+    goto no_disp_ratio;
+  }
+
+  evaspixmapsink->disp_x = disp_x;
+  evaspixmapsink->disp_y = disp_y;
+  evaspixmapsink->disp_width = disp_width;
+  evaspixmapsink->disp_height = disp_height;
+
+  GST_DEBUG_OBJECT (evaspixmapsink,
+      "video width/height: %dx%d, calculated display ratio: %d/%d", video_width,
+      video_height, num, den);
+
+  /* now find a width x height that respects this display ratio.
+   * prefer those that have one of w/h the same as the incoming video
+   * using wd / hd = num / den */
+
+  /* start with same height, because of interlaced video */
+  /* check hd / den is an integer scale factor, and scale wd with the PAR */
+  if (video_height % den == 0) {
+    GST_DEBUG_OBJECT (evaspixmapsink, "keeping video height");
+    GST_VIDEO_SINK_WIDTH (evaspixmapsink) =
+        (guint) gst_util_uint64_scale_int (video_height, num, den);
+    GST_VIDEO_SINK_HEIGHT (evaspixmapsink) = video_height;
+  } else if (video_width % num == 0) {
+    GST_DEBUG_OBJECT (evaspixmapsink, "keeping video width");
+    GST_VIDEO_SINK_WIDTH (evaspixmapsink) = video_width;
+    GST_VIDEO_SINK_HEIGHT (evaspixmapsink) =
+        (guint) gst_util_uint64_scale_int (video_width, den, num);
+  } else {
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "approximating while keeping video height");
+    GST_VIDEO_SINK_WIDTH (evaspixmapsink) =
+        (guint) gst_util_uint64_scale_int (video_height, num, den);
+    GST_VIDEO_SINK_HEIGHT (evaspixmapsink) = video_height;
+  }
+  GST_DEBUG_OBJECT (evaspixmapsink, "scaling to %dx%d",
+      GST_VIDEO_SINK_WIDTH (evaspixmapsink),
+      GST_VIDEO_SINK_HEIGHT (evaspixmapsink));
+
+  /* Creating our window and our image with the display size in pixels */
+  if (GST_VIDEO_SINK_WIDTH (evaspixmapsink) <= 0
+      || GST_VIDEO_SINK_HEIGHT (evaspixmapsink) <= 0) {
+    goto no_display_size;
+  }
+
+  g_mutex_lock (&evaspixmapsink->flow_lock);
+
+  /* We renew our evaspixmap buffer only if size or format changed;
+   * the evaspixmap buffer is the same size as the video pixel size */
+  if ((evaspixmapsink->evas_pixmap_buf)
+      && ((im_format != evaspixmapsink->evas_pixmap_buf->im_format)
+          || (video_width != evaspixmapsink->evas_pixmap_buf->width)
+          || (video_height != evaspixmapsink->evas_pixmap_buf->height))) {
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "old format %" GST_FOURCC_FORMAT ", new format %" GST_FOURCC_FORMAT,
+        GST_FOURCC_ARGS (evaspixmapsink->evas_pixmap_buf->im_format),
+        GST_FOURCC_ARGS (im_format));
+    GST_DEBUG_OBJECT (evaspixmapsink, "renewing evaspixmap buffer");
+//  gst_evaspixmap_buffer_finalize(evaspixmapsink->evas_pixmap_buf);
+    evaspixmapsink->evas_pixmap_buf = NULL;
+  }
+
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+
+  if (evaspixmapsink->eo) {
+    if (!gst_evaspixmapsink_xpixmap_link (evaspixmapsink)) {
+      GST_ERROR_OBJECT (evaspixmapsink,
+          "link evas image object with pixmap failed...");
+      return FALSE;
+    } else {
+      gst_evaspixmapsink_manage_event_thread (evaspixmapsink);
+    }
+  } else {
+    GST_ERROR_OBJECT (evaspixmapsink,
+        "setcaps success, but there is no evas image object..");
+    return FALSE;
+  }
+
+  return TRUE;
+
+  /* ERRORS */
+incompatible_caps:
+  {
+    GST_ERROR_OBJECT (evaspixmapsink, "caps incompatible");
+    return FALSE;
+  }
+incomplete_caps:
+  {
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "Failed to retrieve either width, "
+        "height or framerate from intersected caps");
+    return FALSE;
+  }
+invalid_format:
+  {
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "Could not locate image format from caps %" GST_PTR_FORMAT, caps);
+    return FALSE;
+  }
+no_disp_ratio:
+  {
+    GST_ELEMENT_ERROR (evaspixmapsink, CORE, NEGOTIATION, (NULL),
+        ("Error calculating the output display ratio of the video."));
+    return FALSE;
+  }
+no_display_size:
+  {
+    GST_ELEMENT_ERROR (evaspixmapsink, CORE, NEGOTIATION, (NULL),
+        ("Error calculating the output display ratio of the video."));
+    return FALSE;
+  }
+}
+
+static GstStateChangeReturn
+gst_evaspixmapsink_change_state (GstElement * element,
+    GstStateChange transition)
+{
+  FUNCTION_ENTER ();
+
+  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
+  GstEvasPixmapSink *evaspixmapsink;
+
+  evaspixmapsink = GST_EVASPIXMAPSINK (element);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_NULL_TO_READY:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_STATE_CHANGE_NULL_TO_READY");
+      g_mutex_lock (&evaspixmapsink->flow_lock);
+
+      /* open drm to use gem */
+      if (drm_init (evaspixmapsink)) {
+        GST_ERROR_OBJECT (evaspixmapsink, "drm_init() failure");
+        g_mutex_unlock (&evaspixmapsink->flow_lock);
+        return GST_STATE_CHANGE_FAILURE;
+      }
+
+      /* check if there exist evas image object, need to write code related to making internal evas image object */
+      if (!is_evas_image_object (evaspixmapsink->eo)) {
+        GST_ERROR_OBJECT (evaspixmapsink, "There is no evas image object..");
+        g_mutex_unlock (&evaspixmapsink->flow_lock);
+        return GST_STATE_CHANGE_FAILURE;
+      }
+
+      /* Set xcontext and display */
+      if (!evaspixmapsink->xcontext) {
+        evaspixmapsink->xcontext =
+            gst_evaspixmapsink_xcontext_get (evaspixmapsink);
+        if (!evaspixmapsink->xcontext) {
+          GST_ERROR_OBJECT (evaspixmapsink, "could not get xcontext..");
+          g_mutex_unlock (&evaspixmapsink->flow_lock);
+          return GST_STATE_CHANGE_FAILURE;
+        }
+      }
+
+      /* update object's par with calculated one if not set yet */
+      if (!evaspixmapsink->par) {
+        evaspixmapsink->par = g_new0 (GValue, 1);
+        gst_value_init_and_copy (evaspixmapsink->par,
+            evaspixmapsink->xcontext->par);
+        GST_DEBUG_OBJECT (evaspixmapsink, "set calculated PAR on object's PAR");
+      }
+
+      /* call XSynchronize with the current value of synchronous */
+      GST_DEBUG_OBJECT (evaspixmapsink, "XSynchronize called with %s",
+          evaspixmapsink->synchronous ? "TRUE" : "FALSE");
+      g_mutex_lock (&evaspixmapsink->x_lock);
+      XSynchronize (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->synchronous);
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+      g_mutex_unlock (&evaspixmapsink->flow_lock);
+      break;
+
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_STATE_CHANGE_READY_TO_PAUSED");
+      break;
+
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
+      break;
+
+    default:
+      break;
+  }
+
+  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_STATE_CHANGE_PLAYING_TO_PAUSED");
+      log_warn_count = 0;
+      break;
+
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_STATE_CHANGE_PAUSED_TO_READY");
+      evaspixmapsink->fps_n = 0;
+      evaspixmapsink->fps_d = 1;
+      GST_VIDEO_SINK_WIDTH (evaspixmapsink) = 0;
+      GST_VIDEO_SINK_HEIGHT (evaspixmapsink) = 0;
+      break;
+
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_STATE_CHANGE_READY_TO_NULL");
+      g_mutex_lock (&evaspixmapsink->flow_lock);
+      gst_evaspixmapsink_reset (evaspixmapsink);
+      g_mutex_unlock (&evaspixmapsink->flow_lock);
+      /* close drm */
+      drm_fini (evaspixmapsink);
+      break;
+
+    default:
+      break;
+  }
+  return ret;
+}
+
+static void
+gst_evaspixmapsink_get_times (GstBaseSink * bsink, GstBuffer * buf,
+    GstClockTime * start, GstClockTime * end)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+
+  evaspixmapsink = GST_EVASPIXMAPSINK (bsink);
+
+  if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
+    *start = GST_BUFFER_TIMESTAMP (buf);
+    if (GST_BUFFER_DURATION_IS_VALID (buf)) {
+      *end = *start + GST_BUFFER_DURATION (buf);
+    } else {
+      if (evaspixmapsink->fps_n > 0) {
+        *end = *start +
+            gst_util_uint64_scale_int (GST_SECOND, evaspixmapsink->fps_d,
+            evaspixmapsink->fps_n);
+      }
+    }
+  }
+}
+
+static GstFlowReturn
+gst_evaspixmapsink_show_frame (GstVideoSink * vsink, GstBuffer * buf)
+{
+  FUNCTION_ENTER ();
+
+  GstMapInfo buf_info = GST_MAP_INFO_INIT;
+  GstEvasPixmapSink *evaspixmapsink;
+  XV_PUTIMAGE_DATA_PTR img_data = NULL;
+  MMVideoBuffer *mm_video_buf = NULL;
+  GstMemory *mem;
+
+  evaspixmapsink = GST_EVASPIXMAPSINK (vsink);
+
+  if (GST_STATE (evaspixmapsink) < GST_STATE_PLAYING || log_warn_count < 20) {
+    GST_WARNING_OBJECT (evaspixmapsink, "enter >>>");
+  }
+
+  if (evaspixmapsink->stop_video) {
+    GST_INFO_OBJECT (evaspixmapsink,
+        "Stop video is TRUE. so skip show frame...");
+    return GST_FLOW_OK;
+  }
+
+  if (!evaspixmapsink->evas_pixmap_buf) {
+    GST_DEBUG_OBJECT (evaspixmapsink, "creating our evaspixmap buffer");
+
+    switch (GST_VIDEO_INFO_FORMAT (&evaspixmapsink->info)) {
+      case GST_VIDEO_FORMAT_ST12:
+      case GST_VIDEO_FORMAT_SN12:
+        mem = gst_buffer_peek_memory (buf, 1);
+        gst_memory_map (mem, &buf_info, GST_MAP_READ);
+        mm_video_buf = (MMVideoBuffer *) buf_info.data;
+        gst_memory_unmap (mem, &buf_info);
+        if (mm_video_buf == NULL) {
+          GST_DEBUG_OBJECT (evaspixmapsink,
+              "mm_video_buf is NULL. Skip buffer put...");
+          return GST_FLOW_OK;
+        }
+        /* skip buffer if aligned size is smaller than size of caps */
+        if (mm_video_buf->stride_width[0] < evaspixmapsink->video_width
+            || mm_video_buf->stride_height[0] < evaspixmapsink->video_height) {
+          GST_WARNING_OBJECT (evaspixmapsink,
+              "invalid size[caps:%dx%d,aligned:%dx%d]. Skip this buffer...",
+              evaspixmapsink->video_width, evaspixmapsink->video_height,
+              mm_video_buf->stride_width[0], mm_video_buf->stride_height[0]);
+          return GST_FLOW_OK;
+        }
+        evaspixmapsink->aligned_width = mm_video_buf->stride_width[0];
+        evaspixmapsink->aligned_height = mm_video_buf->stride_height[0];
+        GST_DEBUG_OBJECT (evaspixmapsink, "video width,height[%dx%d]",
+            evaspixmapsink->video_width, evaspixmapsink->video_height);
+        GST_INFO_OBJECT (evaspixmapsink, "Use aligned width,height[%dx%d]",
+            evaspixmapsink->aligned_width, evaspixmapsink->aligned_height);
+        evaspixmapsink->is_zero_copy_format = TRUE;
+        break;
+      default:
+        GST_INFO_OBJECT (evaspixmapsink, "Use original width,height of caps");
+        evaspixmapsink->is_zero_copy_format = FALSE;
+        break;
+    }
+    evaspixmapsink->evas_pixmap_buf =
+        gst_evaspixmap_buffer_new (evaspixmapsink,
+        evaspixmapsink->negotiated_caps);
+
+    if (!evaspixmapsink->evas_pixmap_buf) {
+      /* The create method should have posted an informative error */
+      goto no_image;
+    }
+  }
+
+  switch (evaspixmapsink->evas_pixmap_buf->im_format) {
+      /* Cases for specified formats of Samsung extension */
+    case GST_MAKE_FOURCC ('S', 'T', '1', '2'):
+    case GST_MAKE_FOURCC ('S', 'N', '1', '2'):
+    {
+      GST_DEBUG_OBJECT (evaspixmapsink,
+          "Samsung extension display format activated. fourcc:%c%c%c%c",
+          evaspixmapsink->evas_pixmap_buf->im_format,
+          evaspixmapsink->evas_pixmap_buf->im_format >> 8,
+          evaspixmapsink->evas_pixmap_buf->im_format >> 16,
+          evaspixmapsink->evas_pixmap_buf->im_format >> 24);
+      GstMapInfo buf_info = GST_MAP_INFO_INIT;
+
+      if (evaspixmapsink->evas_pixmap_buf->xvimage->data) {
+        img_data =
+            (XV_PUTIMAGE_DATA_PTR) evaspixmapsink->evas_pixmap_buf->xvimage->
+            data;
+        XV_PUTIMAGE_INIT_DATA (img_data);
+
+        mem = gst_buffer_peek_memory (buf, 1);
+        gst_memory_map (mem, &buf_info, GST_MAP_READ);
+        mm_video_buf = (MMVideoBuffer *) buf_info.data;
+        gst_memory_unmap (mem, &buf_info);
+
+        if (mm_video_buf == NULL) {
+          GST_DEBUG_OBJECT (evaspixmapsink,
+              "mm_video_buf is NULL. Skip buffer put...");
+          return GST_FLOW_OK;
+        }
+
+        if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS) {
+          img_data->YBuf = (unsigned int) mm_video_buf->handle.paddr[0];
+          img_data->CbBuf = (unsigned int) mm_video_buf->handle.paddr[1];
+          img_data->CrBuf = (unsigned int) mm_video_buf->handle.paddr[2];
+          img_data->BufType = XV_BUF_TYPE_LEGACY;
+          if (!img_data->YBuf) {
+            GST_WARNING_OBJECT (evaspixmapsink,
+                "img_data->YBuf is NULL. skip buffer put...");
+            return GST_FLOW_OK;
+          }
+        } else if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+          /* convert dma-buf fd into drm gem name */
+          img_data->YBuf =
+              drm_convert_dmabuf_gemname (evaspixmapsink,
+              (int) mm_video_buf->handle.dmabuf_fd[0]);
+          img_data->CbBuf =
+              drm_convert_dmabuf_gemname (evaspixmapsink,
+              (int) mm_video_buf->handle.dmabuf_fd[1]);
+          img_data->CrBuf =
+              drm_convert_dmabuf_gemname (evaspixmapsink,
+              (int) mm_video_buf->handle.dmabuf_fd[2]);
+          img_data->BufType = XV_BUF_TYPE_DMABUF;
+          if (!img_data->YBuf) {
+            GST_WARNING_OBJECT (evaspixmapsink,
+                "img_data->YBuf is NULL. skip buffer put...");
+            return GST_FLOW_OK;
+          }
+        } else if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_TBM_BO) {
+          img_data->bo[0] = mm_video_buf->handle.bo[0];
+          img_data->bo[1] = mm_video_buf->handle.bo[1];
+          img_data->bo[2] = mm_video_buf->handle.bo[2];
+          GST_DEBUG ("TBM bo %p %p %p", img_data->bo[0], img_data->bo[1],
+              img_data->bo[2]);
+          /* export bo */
+          if (img_data->bo[0]) {
+            img_data->YBuf = tbm_bo_export ((tbm_bo) img_data->bo[0]);
+          }
+          if (img_data->bo[1]) {
+            img_data->CbBuf = tbm_bo_export ((tbm_bo) img_data->bo[1]);
+          }
+          if (img_data->bo[2]) {
+            img_data->CrBuf = tbm_bo_export ((tbm_bo) img_data->bo[2]);
+          }
+          if (mm_video_buf->type != MM_VIDEO_BUFFER_TYPE_TBM_BO) {
+            mm_video_buf->type = MM_VIDEO_BUFFER_TYPE_TBM_BO;
+            GST_WARNING_OBJECT (evaspixmapsink,
+                "BUF SHARED TYPE : TIZEN BUFFER");
+          }
+        } else {
+          GST_WARNING_OBJECT (evaspixmapsink,
+              "Not supported, mm_video_buf->type(%d)", mm_video_buf->type);
+          return GST_FLOW_OK;
+        }
+        GST_LOG_OBJECT (evaspixmapsink, "YBuf[%d], CbBuf[%d], CrBuf[%d]",
+            img_data->YBuf, img_data->CbBuf, img_data->CrBuf);
+      } else {
+        GST_WARNING_OBJECT (evaspixmapsink,
+            "xvimage->data is NULL. skip buffer put...");
+        return GST_FLOW_OK;
+      }
+      break;
+    }
+    default:
+    {
+      GST_DEBUG_OBJECT (evaspixmapsink,
+          "Normal format activated. fourcc:%c%c%c%c",
+          evaspixmapsink->evas_pixmap_buf->im_format,
+          evaspixmapsink->evas_pixmap_buf->im_format >> 8,
+          evaspixmapsink->evas_pixmap_buf->im_format >> 16,
+          evaspixmapsink->evas_pixmap_buf->im_format >> 24);
+      gst_buffer_map (buf, &buf_info, GST_MAP_READ);
+      memcpy (evaspixmapsink->evas_pixmap_buf->xvimage->data, buf_info.data,
+          MIN (buf_info.size, evaspixmapsink->evas_pixmap_buf->size));
+      gst_buffer_unmap (buf, &buf_info);
+      break;
+    }
+  }
+#ifdef DUMP_IMG
+  if (mm_video_buf && g_cnt < 20)
+    input_dump (mm_video_buf);
+#endif
+  g_mutex_lock (&evaspixmapsink->flow_lock);
+  if (!gst_evaspixmap_buffer_put (evaspixmapsink,
+          evaspixmapsink->evas_pixmap_buf)) {
+    g_mutex_unlock (&evaspixmapsink->flow_lock);
+    goto no_pixmap;
+  }
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+
+  return GST_FLOW_OK;
+
+  /* ERRORS */
+no_image:
+  {
+    /* No image available. That's very bad ! */
+    GST_WARNING_OBJECT (evaspixmapsink, "could not create image");
+    return GST_FLOW_ERROR;
+  }
+no_pixmap:
+  {
+    /* No Pixmap available to put our image into */
+    GST_WARNING_OBJECT (evaspixmapsink, "could not output image - no pixmap");
+    return GST_FLOW_ERROR;
+  }
+}
+
+static gboolean
+gst_evaspixmapsink_event (GstBaseSink * sink, GstEvent * event)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (sink);
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_FLUSH_START:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_EVENT_FLUSH_START");
+      break;
+    case GST_EVENT_FLUSH_STOP:
+      GST_DEBUG_OBJECT (evaspixmapsink, "GST_EVENT_FLUSH_STOP");
+      break;
+    default:
+      break;
+  }
+  if (GST_BASE_SINK_CLASS (parent_class)->event) {
+    return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
+  } else {
+    return TRUE;
+  }
+}
+
+/* Interfaces stuff */
+
+static void
+gst_evaspixmapsink_navigation_send_event (GstNavigation * navigation,
+    GstStructure * structure)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (navigation);
+  GstPad *peer;
+  int i = 0;
+
+  if ((peer = gst_pad_get_peer (GST_VIDEO_SINK_PAD (evaspixmapsink)))) {
+    GstEvent *event;
+    GstVideoRectangle src = { 0, };
+    GstVideoRectangle dst = { 0, };
+    GstVideoRectangle result = { 0, };
+
+    gdouble x, y, xscale = 1.0, yscale = 1.0;
+
+    event = gst_event_new_navigation (structure);
+
+    /* We take the flow_lock while we look at the window */
+    g_mutex_lock (&evaspixmapsink->flow_lock);
+
+    for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+      if (!evaspixmapsink->xpixmap[i]) {
+        g_mutex_unlock (&evaspixmapsink->flow_lock);
+        return;
+      }
+    }
+
+    if (evaspixmapsink->keep_aspect) {
+      /* We get the frame position using the calculated geometry from _setcaps
+         that respect pixel aspect ratios */
+      src.w = GST_VIDEO_SINK_WIDTH (evaspixmapsink);
+      src.h = GST_VIDEO_SINK_HEIGHT (evaspixmapsink);
+      dst.w = evaspixmapsink->render_rect.w;
+      dst.h = evaspixmapsink->render_rect.h;
+
+      gst_video_sink_center_rect (src, dst, &result, TRUE);
+      result.x += evaspixmapsink->render_rect.x;
+      result.y += evaspixmapsink->render_rect.y;
+    } else {
+      memcpy (&result, &evaspixmapsink->render_rect,
+          sizeof (GstVideoRectangle));
+    }
+
+    g_mutex_unlock (&evaspixmapsink->flow_lock);
+
+    /* We calculate scaling using the original video frames geometry to include
+       pixel aspect ratio scaling. */
+    if (result.w != 0)
+      xscale = (gdouble) evaspixmapsink->video_width / result.w;
+    if (result.h != 0)
+      yscale = (gdouble) evaspixmapsink->video_height / result.h;
+
+    /* Converting pointer coordinates to the non scaled geometry */
+    if (gst_structure_get_double (structure, "pointer_x", &x)) {
+      x = MIN (x, result.x + result.w);
+      x = MAX (x - result.x, 0);
+      gst_structure_set (structure, "pointer_x", G_TYPE_DOUBLE,
+          (gdouble) x * xscale, NULL);
+    }
+    if (gst_structure_get_double (structure, "pointer_y", &y)) {
+      y = MIN (y, result.y + result.h);
+      y = MAX (y - result.y, 0);
+      gst_structure_set (structure, "pointer_y", G_TYPE_DOUBLE,
+          (gdouble) y * yscale, NULL);
+    }
+
+    gst_pad_send_event (peer, event);
+    gst_object_unref (peer);
+  }
+}
+
+static void
+gst_evaspixmapsink_navigation_init (GstNavigationInterface * iface)
+{
+  FUNCTION_ENTER ();
+
+  iface->send_event = gst_evaspixmapsink_navigation_send_event;
+}
+
+static const GList *
+gst_evaspixmapsink_colorbalance_list_channels (GstColorBalance * balance)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (balance);
+
+  g_return_val_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink), NULL);
+
+  if (evaspixmapsink->xcontext)
+    return evaspixmapsink->xcontext->channels_list;
+  else
+    return NULL;
+}
+
+static void
+gst_evaspixmapsink_colorbalance_set_value (GstColorBalance * balance,
+    GstColorBalanceChannel * channel, gint value)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (balance);
+
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink));
+  g_return_if_fail (channel->label != NULL);
+
+  evaspixmapsink->cb_changed = TRUE;
+
+  /* Normalize val to [-1000, 1000] */
+  value = floor (0.5 + -1000 + 2000 * (value - channel->min_value) /
+      (double) (channel->max_value - channel->min_value));
+
+  if (g_ascii_strcasecmp (channel->label, "XV_HUE") == 0) {
+    evaspixmapsink->hue = value;
+  } else if (g_ascii_strcasecmp (channel->label, "XV_SATURATION") == 0) {
+    evaspixmapsink->saturation = value;
+  } else if (g_ascii_strcasecmp (channel->label, "XV_CONTRAST") == 0) {
+    evaspixmapsink->contrast = value;
+  } else if (g_ascii_strcasecmp (channel->label, "XV_BRIGHTNESS") == 0) {
+    evaspixmapsink->brightness = value;
+  } else {
+    g_warning ("got an unknown channel %s", channel->label);
+    return;
+  }
+
+  gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+}
+
+static gint
+gst_evaspixmapsink_colorbalance_get_value (GstColorBalance * balance,
+    GstColorBalanceChannel * channel)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (balance);
+  gint value = 0;
+
+  g_return_val_if_fail (GST_IS_EVASPIXMAPSINK (evaspixmapsink), 0);
+  g_return_val_if_fail (channel->label != NULL, 0);
+
+  if (g_ascii_strcasecmp (channel->label, "XV_HUE") == 0) {
+    value = evaspixmapsink->hue;
+  } else if (g_ascii_strcasecmp (channel->label, "XV_SATURATION") == 0) {
+    value = evaspixmapsink->saturation;
+  } else if (g_ascii_strcasecmp (channel->label, "XV_CONTRAST") == 0) {
+    value = evaspixmapsink->contrast;
+  } else if (g_ascii_strcasecmp (channel->label, "XV_BRIGHTNESS") == 0) {
+    value = evaspixmapsink->brightness;
+  } else {
+    g_warning ("got an unknown channel %s", channel->label);
+  }
+
+  /* Normalize val to [channel->min_value, channel->max_value] */
+  value =
+      channel->min_value + (channel->max_value - channel->min_value) * (value +
+      1000) / 2000;
+
+  return value;
+}
+
+static void
+gst_evaspixmapsink_colorbalance_init (GstColorBalanceInterface * iface)
+{
+  FUNCTION_ENTER ();
+
+  iface->list_channels = gst_evaspixmapsink_colorbalance_list_channels;
+  iface->set_value = gst_evaspixmapsink_colorbalance_set_value;
+  iface->get_value = gst_evaspixmapsink_colorbalance_get_value;
+}
+
+static const GList *
+gst_evaspixmapsink_probe_get_properties (GstPropertyProbe * probe)
+{
+  FUNCTION_ENTER ();
+
+  GObjectClass *klass = G_OBJECT_GET_CLASS (probe);
+  static GList *list = NULL;
+
+  if (!list) {
+    list = g_list_append (NULL, g_object_class_find_property (klass, "device"));
+    list =
+        g_list_append (list, g_object_class_find_property (klass,
+            "autopaint-colorkey"));
+    list =
+        g_list_append (list, g_object_class_find_property (klass,
+            "double-buffer"));
+    list =
+        g_list_append (list, g_object_class_find_property (klass, "colorkey"));
+  }
+
+  return list;
+}
+
+static void
+gst_evaspixmapsink_probe_probe_property (GstPropertyProbe * probe,
+    guint prop_id, const GParamSpec * pspec)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (probe);
+
+  switch (prop_id) {
+    case PROP_DEVICE:
+    case PROP_AUTOPAINT_COLORKEY:
+    case PROP_DOUBLE_BUFFER:
+    case PROP_COLORKEY:
+      GST_DEBUG_OBJECT (evaspixmapsink,
+          "probing device list and get capabilities");
+      if (!evaspixmapsink->xcontext) {
+        GST_DEBUG_OBJECT (evaspixmapsink, "generating xcontext");
+        evaspixmapsink->xcontext =
+            gst_evaspixmapsink_xcontext_get (evaspixmapsink);
+        if (!evaspixmapsink->xcontext) {
+          GST_ERROR_OBJECT (evaspixmapsink, "could not get xcontext..");
+        }
+      }
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
+      break;
+  }
+}
+
+static gboolean
+gst_evaspixmapsink_probe_needs_probe (GstPropertyProbe * probe, guint prop_id,
+    const GParamSpec * pspec)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (probe);
+  gboolean ret = FALSE;
+
+  switch (prop_id) {
+    case PROP_DEVICE:
+    case PROP_AUTOPAINT_COLORKEY:
+    case PROP_DOUBLE_BUFFER:
+    case PROP_COLORKEY:
+      if (evaspixmapsink->xcontext != NULL) {
+        ret = FALSE;
+      } else {
+        ret = TRUE;
+      }
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
+      break;
+  }
+
+  return ret;
+}
+
+static GValueArray *
+gst_evaspixmapsink_probe_get_values (GstPropertyProbe * probe, guint prop_id,
+    const GParamSpec * pspec)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink = GST_EVASPIXMAPSINK (probe);
+  GValueArray *array = NULL;
+
+  if (G_UNLIKELY (!evaspixmapsink->xcontext)) {
+    GST_WARNING_OBJECT (evaspixmapsink, "we don't have any xcontext, can't "
+        "get values");
+    goto beach;
+  }
+
+  switch (prop_id) {
+    case PROP_DEVICE:
+    {
+      guint i;
+      GValue value = { 0 };
+
+      array = g_value_array_new (evaspixmapsink->xcontext->nb_adaptors);
+      g_value_init (&value, G_TYPE_STRING);
+
+      for (i = 0; i < evaspixmapsink->xcontext->nb_adaptors; i++) {
+        gchar *adaptor_id_s = g_strdup_printf ("%u", i);
+
+        g_value_set_string (&value, adaptor_id_s);
+        g_value_array_append (array, &value);
+        g_free (adaptor_id_s);
+      }
+      g_value_unset (&value);
+      break;
+    }
+    case PROP_AUTOPAINT_COLORKEY:
+      if (evaspixmapsink->have_autopaint_colorkey) {
+        GValue value = { 0 };
+
+        array = g_value_array_new (2);
+        g_value_init (&value, G_TYPE_BOOLEAN);
+        g_value_set_boolean (&value, FALSE);
+        g_value_array_append (array, &value);
+        g_value_set_boolean (&value, TRUE);
+        g_value_array_append (array, &value);
+        g_value_unset (&value);
+      }
+      break;
+    case PROP_DOUBLE_BUFFER:
+      if (evaspixmapsink->have_double_buffer) {
+        GValue value = { 0 };
+
+        array = g_value_array_new (2);
+        g_value_init (&value, G_TYPE_BOOLEAN);
+        g_value_set_boolean (&value, FALSE);
+        g_value_array_append (array, &value);
+        g_value_set_boolean (&value, TRUE);
+        g_value_array_append (array, &value);
+        g_value_unset (&value);
+      }
+      break;
+    case PROP_COLORKEY:
+      if (evaspixmapsink->have_colorkey) {
+        GValue value = { 0 };
+
+        array = g_value_array_new (1);
+        g_value_init (&value, GST_TYPE_INT_RANGE);
+        gst_value_set_int_range (&value, 0, 0xffffff);
+        g_value_array_append (array, &value);
+        g_value_unset (&value);
+      }
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec);
+      break;
+  }
+
+beach:
+  return array;
+}
+
+static void
+gst_evaspixmapsink_property_probe_interface_init (GstPropertyProbeInterface *
+    iface)
+{
+  FUNCTION_ENTER ();
+
+  iface->get_properties = gst_evaspixmapsink_probe_get_properties;
+  iface->probe_property = gst_evaspixmapsink_probe_probe_property;
+  iface->needs_probe = gst_evaspixmapsink_probe_needs_probe;
+  iface->get_values = gst_evaspixmapsink_probe_get_values;
+}
+
+static gboolean
+gst_evaspixmapsink_xpixmap_link (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  Display *dpy;
+  Pixmap pixmap_id[NUM_OF_PIXMAP] = { 0 };
+  int evas_object_width = 0;
+  int evas_object_height = 0;
+  int pixmap_width = 0;
+  int pixmap_height = 0;
+  guint xw = 0;
+  guint xh = 0;
+  int i = 0;
+  int j = 0;
+  int empty = -1;
+  gboolean full = TRUE;
+  XGCValues gc_values_black;
+  gc_values_black.foreground = 0xff000000;
+
+  if (!evaspixmapsink) {
+    GST_ERROR_OBJECT (evaspixmapsink, "could not get evaspixmapsink..");
+    return FALSE;
+  }
+  g_mutex_lock (&evaspixmapsink->flow_lock);
+
+  /* Set xcontext and display */
+  if (!evaspixmapsink->xcontext) {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "there's no xcontext, try to get one..");
+    evaspixmapsink->xcontext = gst_evaspixmapsink_xcontext_get (evaspixmapsink);
+    if (!evaspixmapsink->xcontext) {
+      GST_ERROR_OBJECT (evaspixmapsink, "could not get xcontext..");
+      return FALSE;
+    }
+  }
+  evas_object_geometry_get (evaspixmapsink->eo, NULL, NULL, &evas_object_width,
+      &evas_object_height);
+
+  /* check if it is redundant request */
+  for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+    if (evaspixmapsink->xpixmap[i]) {
+      if (!evaspixmapsink->use_origin_size && evaspixmapsink->xpixmap[i]->width
+          && evaspixmapsink->xpixmap[i]->height) {
+        if (evaspixmapsink->xpixmap[i]->width == evas_object_width
+            && evaspixmapsink->xpixmap[i]->height == evas_object_height) {
+          if (GST_STATE (evaspixmapsink) < GST_STATE_PLAYING) {
+            GST_WARNING_OBJECT (evaspixmapsink,
+                "pixmap was already created(w:%d, h:%d), skip it..",
+                evaspixmapsink->xpixmap[i]->width,
+                evaspixmapsink->xpixmap[i]->height);
+            if (evaspixmapsink->need_to_fill_black) {
+              for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+                g_mutex_lock (&evaspixmapsink->x_lock);
+                DRI2CreateDrawable (evaspixmapsink->xcontext->disp,
+                    evaspixmapsink->xpixmap[i]->pixmap);
+                gst_evaspixmapsink_xpixmap_fillblack
+                    (evaspixmapsink->bufmgr_for_black,
+                    evaspixmapsink->xcontext->disp,
+                    evaspixmapsink->xpixmap[i]->pixmap);
+                DRI2DestroyDrawable (evaspixmapsink->xcontext->disp,
+                    evaspixmapsink->xpixmap[i]->pixmap);
+                GST_LOG_OBJECT (evaspixmapsink,
+                    "fill black to xpixmap[%ld] with size(w:%d,h:%d)",
+                    evaspixmapsink->xpixmap[i]->pixmap,
+                    evaspixmapsink->xpixmap[i]->width,
+                    evaspixmapsink->xpixmap[i]->height);
+                g_mutex_unlock (&evaspixmapsink->x_lock);
+              }
+              evaspixmapsink->need_to_fill_black = FALSE;
+            }
+            goto SKIP_LINK;
+          } else {
+            GST_LOG ("we are in the state of playing. keep pixmap");
+            goto KEEP_PIXMAP;
+          }
+        }
+      }
+    }
+  }
+  dpy = evaspixmapsink->xcontext->disp;
+
+
+  /* Set evas image object size */
+  if (evaspixmapsink->use_origin_size || !evas_object_width
+      || !evas_object_height) {
+    pixmap_width = evaspixmapsink->video_width;
+    pixmap_height = evaspixmapsink->video_height;
+    GST_INFO_OBJECT (evaspixmapsink, "set size to media src size(%dx%d)",
+        pixmap_width, pixmap_height);
+  }
+
+  g_mutex_lock (&evaspixmapsink->x_lock);
+  evaspixmapsink->sizediff_width = 0;
+  evaspixmapsink->sizediff_height = 0;
+  if (evaspixmapsink->use_origin_size || !evas_object_width
+      || !evas_object_height) {
+    XvQueryBestSize (dpy, evaspixmapsink->xcontext->xv_port_id, 0, 0, 0,
+        pixmap_width, pixmap_height, &xw, &xh);
+    if (!evas_object_width || !evas_object_height) {
+      evaspixmapsink->w = xw;
+      evaspixmapsink->h = xh;
+    } else {
+      evaspixmapsink->w = evas_object_width;
+      evaspixmapsink->h = evas_object_height;
+    }
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "XvQueryBestSize : xv_port_id(%ld), w(%d),h(%d) => xw(%d),xh(%d)",
+        evaspixmapsink->xcontext->xv_port_id, pixmap_width, pixmap_height, xw,
+        xh);
+  } else {
+    XvQueryBestSize (dpy, evaspixmapsink->xcontext->xv_port_id, 0, 0, 0,
+        evas_object_width, evas_object_height, &xw, &xh);
+    GST_DEBUG_OBJECT (evaspixmapsink,
+        "XvQueryBestSize : xv_port_id(%ld), w(%d),h(%d) => xw(%d),xh(%d)",
+        evaspixmapsink->xcontext->xv_port_id, evas_object_width,
+        evas_object_height, xw, xh);
+    evaspixmapsink->w = xw;
+    evaspixmapsink->h = xh;
+    /* update difference of size information (between evas image object's and pixmap's) */
+    evaspixmapsink->sizediff_width = xw - evas_object_width;
+    evaspixmapsink->sizediff_height = xh - evas_object_height;
+  }
+
+  /* create xpixmap structure */
+  for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+    if (!evaspixmapsink->xpixmap[i]) {
+      /* xpixmap can be created in this function only */
+      evaspixmapsink->xpixmap[i] = g_new0 (GstXPixmap, 1);
+      if (!evaspixmapsink->xpixmap[i]) {
+        GST_ERROR_OBJECT (evaspixmapsink, "xpixmap is not valid..");
+        int j = 0;
+        for (j = 0; j < i; j++) {
+          g_free (evaspixmapsink->xpixmap[j]);
+        }
+        goto GO_OUT_OF_FUNC;
+      }
+    }
+  }
+
+  /* create pixmap */
+  if (!xw || !xh) {
+    GST_WARNING_OBJECT (evaspixmapsink, "skip creating pixmap..xw(%d),xh(%d)",
+        xw, xh);
+    goto GO_OUT_OF_FUNC;
+  } else {
+    /* multiple pixmaps creation */
+    for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+      pixmap_id[i] =
+          XCreatePixmap (dpy, DefaultRootWindow (dpy), xw, xh,
+          DefaultDepth (dpy, DefaultScreen (dpy)));
+      if ((int) pixmap_id[i] == BadAlloc || (int) pixmap_id[i] == BadDrawable
+          || (int) pixmap_id[i] == BadValue) {
+        GST_ERROR_OBJECT (evaspixmapsink, "pixmap[%d] allocation error..", i);
+        int j = 0;
+        for (j = 0; j < i; j++) {
+          XFreePixmap (dpy, pixmap_id[j]);
+        }
+        goto GO_OUT_OF_FUNC;
+      }
+      GST_INFO_OBJECT (evaspixmapsink, "creation pixmap_id[%d]:%ld success", i,
+          pixmap_id[i]);
+      GST_DEBUG_OBJECT (evaspixmapsink,
+          "evas_object_width(%d),evas_object_height(%d),pixmap:%ld,depth:%d",
+          evas_object_width, evas_object_height, pixmap_id[i],
+          DefaultDepth (dpy, DefaultScreen (dpy)));
+      DRI2CreateDrawable (evaspixmapsink->xcontext->disp, pixmap_id[i]);
+      gst_evaspixmapsink_xpixmap_fillblack
+          (evaspixmapsink->bufmgr_for_black,
+          evaspixmapsink->xcontext->disp, pixmap_id[i]);
+      DRI2DestroyDrawable (evaspixmapsink->xcontext->disp, pixmap_id[i]);
+    }
+    evaspixmapsink->need_to_fill_black = FALSE;
+  }
+
+  /* keep previous pixmap id */
+  for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+    if (evaspixmapsink->xpixmap[i]->pixmap
+        && pixmap_id[i] != evaspixmapsink->xpixmap[i]->pixmap) {
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      g_mutex_lock (&evaspixmapsink->pixmap_ref_lock);
+      /* find empty spaces */
+      for (j = 0; j < NUM_OF_PREV_PIXMAP; j++) {
+        if (!evaspixmapsink->prev[j]->pixmap) {
+          empty = j;
+          full = FALSE;
+          break;
+        }
+      }
+      if (full || empty == -1)
+        GST_ERROR ("previous pixmap pool is full");
+      else {
+        evaspixmapsink->prev[empty]->pixmap =
+            evaspixmapsink->xpixmap[i]->pixmap;
+        evaspixmapsink->prev[empty]->gc = evaspixmapsink->xpixmap[i]->gc;
+        evaspixmapsink->prev[empty]->damage = evaspixmapsink->damage[i];
+        GST_LOG ("saved %ld %p %ld",
+            evaspixmapsink->prev[empty]->pixmap,
+            evaspixmapsink->prev[empty]->gc,
+            evaspixmapsink->prev[empty]->damage);
+      }
+      evaspixmapsink->xpixmap[i]->pixmap = 0;
+      evaspixmapsink->xpixmap[i]->ref = 0;
+      evaspixmapsink->xpixmap[i]->damaged_time = 0;
+
+      g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+      g_mutex_lock (&evaspixmapsink->x_lock);
+    }
+  }
+
+  for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+    /* Set pixmap id and create GC */
+    evaspixmapsink->xpixmap[i]->pixmap = pixmap_id[i];
+    evaspixmapsink->xpixmap[i]->gc =
+        XCreateGC (dpy, evaspixmapsink->xpixmap[i]->pixmap, GCForeground,
+        &gc_values_black);
+    evaspixmapsink->xpixmap[i]->width = xw;
+    evaspixmapsink->xpixmap[i]->height = xh;
+
+    /* Create XDamage */
+    evaspixmapsink->damage[i] =
+        XDamageCreate (dpy, evaspixmapsink->xpixmap[i]->pixmap,
+        XDamageReportRawRectangles);
+
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "xpixmap[%d]->(pixmap:%ld,gc:%p), damage[%d]:%ld", i,
+        evaspixmapsink->xpixmap[i]->pixmap, evaspixmapsink->xpixmap[i]->gc, i,
+        evaspixmapsink->damage[i]);
+  }
+
+  XSync (dpy, FALSE);
+
+  /* Set flag for mapping evas object with xpixmap */
+  evaspixmapsink->do_link = TRUE;
+  evaspixmapsink->last_updated_idx = -1;
+  if (evaspixmapsink->epipe_request_count > EPIPE_REQUEST_LIMIT) {
+    GST_WARNING_OBJECT (evaspixmapsink,
+        "epipe_request_count(%d), skip ecore_pipe_write()",
+        evaspixmapsink->epipe_request_count);
+  } else {
+    GST_WARNING_OBJECT (evaspixmapsink, ">>>>>ecore_pipe_write()");
+    ecore_pipe_write (evaspixmapsink->epipe, evaspixmapsink,
+        sizeof (GstEvasPixmapSink));
+    evaspixmapsink->epipe_request_count++;
+  }
+  gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+
+  return TRUE;
+
+SKIP_LINK:
+  g_mutex_lock (&evaspixmapsink->pixmap_ref_lock);
+  evaspixmapsink->last_updated_idx = -1;
+  g_mutex_unlock (&evaspixmapsink->pixmap_ref_lock);
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+  return TRUE;
+
+KEEP_PIXMAP:
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+  return TRUE;
+
+GO_OUT_OF_FUNC:
+  if (evaspixmapsink->xcontext) {
+    XSync (evaspixmapsink->xcontext->disp, TRUE);
+  }
+  g_mutex_unlock (&evaspixmapsink->x_lock);
+  g_mutex_unlock (&evaspixmapsink->flow_lock);
+  return FALSE;
+}
+
+static void
+gst_evaspixmapsink_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (object));
+  evaspixmapsink = GST_EVASPIXMAPSINK (object);
+
+  Evas_Object *eo;
+  int i = 0;
+
+  switch (prop_id) {
+    case PROP_HUE:
+      evaspixmapsink->hue = g_value_get_int (value);
+      evaspixmapsink->cb_changed = TRUE;
+      gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+      break;
+    case PROP_CONTRAST:
+      evaspixmapsink->contrast = g_value_get_int (value);
+      evaspixmapsink->cb_changed = TRUE;
+      gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+      break;
+    case PROP_BRIGHTNESS:
+      evaspixmapsink->brightness = g_value_get_int (value);
+      evaspixmapsink->cb_changed = TRUE;
+      gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+      break;
+    case PROP_SATURATION:
+      evaspixmapsink->saturation = g_value_get_int (value);
+      evaspixmapsink->cb_changed = TRUE;
+      gst_evaspixmapsink_update_colorbalance (evaspixmapsink);
+      break;
+    case PROP_DISPLAY:
+      evaspixmapsink->display_name = g_strdup (g_value_get_string (value));
+      break;
+    case PROP_SYNCHRONOUS:
+      evaspixmapsink->synchronous = g_value_get_boolean (value);
+      if (evaspixmapsink->xcontext) {
+        XSynchronize (evaspixmapsink->xcontext->disp,
+            evaspixmapsink->synchronous);
+        GST_DEBUG_OBJECT (evaspixmapsink, "XSynchronize called with %s",
+            evaspixmapsink->synchronous ? "TRUE" : "FALSE");
+      }
+      break;
+    case PROP_PIXEL_ASPECT_RATIO:
+      g_free (evaspixmapsink->par);
+      evaspixmapsink->par = g_new0 (GValue, 1);
+      g_value_init (evaspixmapsink->par, GST_TYPE_FRACTION);
+      if (!g_value_transform (value, evaspixmapsink->par)) {
+        g_warning ("Could not transform string to aspect ratio");
+        gst_value_set_fraction (evaspixmapsink->par, 1, 1);
+      }
+      GST_DEBUG_OBJECT (evaspixmapsink, "set PAR to %d/%d",
+          gst_value_get_fraction_numerator (evaspixmapsink->par),
+          gst_value_get_fraction_denominator (evaspixmapsink->par));
+      break;
+    case PROP_FORCE_ASPECT_RATIO:
+      evaspixmapsink->keep_aspect = g_value_get_boolean (value);
+      break;
+    case PROP_DEVICE:
+      evaspixmapsink->adaptor_no = atoi (g_value_get_string (value));
+      break;
+    case PROP_DOUBLE_BUFFER:
+      evaspixmapsink->double_buffer = g_value_get_boolean (value);
+      break;
+    case PROP_AUTOPAINT_COLORKEY:
+      evaspixmapsink->autopaint_colorkey = g_value_get_boolean (value);
+      break;
+    case PROP_COLORKEY:
+      evaspixmapsink->colorkey = g_value_get_int (value);
+      break;
+    case PROP_PIXMAP_WIDTH:
+      for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+        if (evaspixmapsink->xpixmap[i]) {
+          evaspixmapsink->xpixmap[i]->width = g_value_get_uint64 (value);
+          /* To do : code related to pixmap re-link */
+        }
+      }
+      break;
+    case PROP_PIXMAP_HEIGHT:
+      for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+        if (evaspixmapsink->xpixmap[i]) {
+          evaspixmapsink->xpixmap[i]->height = g_value_get_uint64 (value);
+          /* To do : code related to pixmap re-link */
+        }
+      }
+      break;
+    case PROP_DISPLAY_GEOMETRY_METHOD:
+    {
+      guint new_val = g_value_get_enum (value);
+      if (evaspixmapsink->display_geometry_method != new_val) {
+        evaspixmapsink->display_geometry_method = new_val;
+        GST_INFO_OBJECT (evaspixmapsink,
+            "Overlay geometry method update, display_geometry_method(%d)",
+            evaspixmapsink->display_geometry_method);
+        if (evaspixmapsink->display_geometry_method !=
+            DISP_GEO_METHOD_FULL_SCREEN
+            && evaspixmapsink->display_geometry_method !=
+            DISP_GEO_METHOD_CROPPED_FULL_SCREEN) {
+          if (evaspixmapsink->xcontext) {
+            g_mutex_lock (&evaspixmapsink->flow_lock);
+            int i = 0;
+            for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+              if (evaspixmapsink->xpixmap[i]) {
+                gst_evaspixmapsink_xpixmap_clear (evaspixmapsink,
+                    evaspixmapsink->xpixmap[i]);
+              }
+            }
+            g_mutex_unlock (&evaspixmapsink->flow_lock);
+          }
+        }
+        if (evaspixmapsink->xcontext) {
+          g_mutex_lock (&evaspixmapsink->flow_lock);
+          gst_evaspixmap_buffer_put (evaspixmapsink,
+              evaspixmapsink->evas_pixmap_buf);
+          g_mutex_unlock (&evaspixmapsink->flow_lock);
+        }
+      }
+      break;
+    }
+    case PROP_DST_ROI_X:
+      evaspixmapsink->dst_roi.x = g_value_get_int (value);
+      GST_INFO_OBJECT (evaspixmapsink, "ROI_X(%d)", evaspixmapsink->dst_roi.x);
+      break;
+    case PROP_DST_ROI_Y:
+      evaspixmapsink->dst_roi.y = g_value_get_int (value);
+      GST_INFO_OBJECT (evaspixmapsink, "ROI_Y(%d)", evaspixmapsink->dst_roi.y);
+      break;
+    case PROP_DST_ROI_W:
+      evaspixmapsink->dst_roi.w = g_value_get_int (value);
+      GST_INFO_OBJECT (evaspixmapsink, "ROI_W(%d)", evaspixmapsink->dst_roi.w);
+      break;
+    case PROP_DST_ROI_H:
+      evaspixmapsink->dst_roi.h = g_value_get_int (value);
+      GST_INFO_OBJECT (evaspixmapsink, "ROI_H(%d)", evaspixmapsink->dst_roi.h);
+      break;
+    case PROP_STOP_VIDEO:
+      evaspixmapsink->stop_video = g_value_get_int (value);
+      g_mutex_lock (&evaspixmapsink->flow_lock);
+      if (evaspixmapsink->stop_video) {
+        GST_INFO_OBJECT (evaspixmapsink,
+            "XPixmap CLEAR when set video-stop property");
+        int i = 0;
+        for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+          if (evaspixmapsink->xpixmap[i]) {
+            gst_evaspixmapsink_xpixmap_clear (evaspixmapsink,
+                evaspixmapsink->xpixmap[i]);
+          }
+        }
+      }
+      g_mutex_unlock (&evaspixmapsink->flow_lock);
+      break;
+    case PROP_FLIP:
+      evaspixmapsink->flip = g_value_get_enum (value);
+      GST_WARNING ("[set property] flip : %d", evaspixmapsink->rotate_angle);
+      break;
+    case PROP_ROTATE_ANGLE:
+      evaspixmapsink->rotate_angle = g_value_get_enum (value);
+      GST_WARNING ("[set property] rotate : %d", evaspixmapsink->rotate_angle);
+      break;
+    case PROP_EVAS_OBJECT:
+      eo = g_value_get_pointer (value);
+      if (is_evas_image_object (eo)) {
+        if (!evaspixmapsink->epipe) {
+          evaspixmapsink->epipe =
+              ecore_pipe_add (ecore_pipe_callback_handler, evaspixmapsink);
+          if (!evaspixmapsink->epipe) {
+            GST_ERROR_OBJECT (evaspixmapsink,
+                "Cannot set evas-object property: ecore_pipe_add() failed");
+            break;
+          }
+        }
+        if (evaspixmapsink->eo == NULL) {
+          evaspixmapsink->eo = eo;
+          /* add evas object callbacks on a new evas image object */
+          evas_object_event_callback_add (evaspixmapsink->eo, EVAS_CALLBACK_DEL,
+              evas_callback_del_event, evaspixmapsink);
+          evas_object_event_callback_add (evaspixmapsink->eo,
+              EVAS_CALLBACK_RESIZE, evas_callback_resize_event, evaspixmapsink);
+          if (GST_STATE (evaspixmapsink) < GST_STATE_PAUSED) {
+            GST_INFO_OBJECT (evaspixmapsink,
+                "It's the first time the new evas image object(%p) is set, skip gst_evaspixmapsink_xpixmap_link()..",
+                eo);
+            break;
+          } else {
+            if (!gst_evaspixmapsink_xpixmap_link (evaspixmapsink)) {
+              GST_WARNING_OBJECT (evaspixmapsink,
+                  "link evas image object with pixmap failed...");
+              evaspixmapsink->eo = NULL;
+              break;
+            }
+          }
+        }
+        if (eo == evaspixmapsink->eo) {
+          GST_LOG_OBJECT (evaspixmapsink,
+              "new evas image object(%p) is same as the previous one(%p)", eo,
+              evaspixmapsink->eo);
+        } else {
+          GST_INFO_OBJECT (evaspixmapsink,
+              "new evas image object(%p), previous one(%p)", eo,
+              evaspixmapsink->eo);
+          /* delete evas object callbacks registrated on a former evas image object */
+          evas_object_event_callback_del (evaspixmapsink->eo, EVAS_CALLBACK_DEL,
+              evas_callback_del_event);
+          evas_object_event_callback_del (evaspixmapsink->eo,
+              EVAS_CALLBACK_RESIZE, evas_callback_resize_event);
+          evaspixmapsink->eo = eo;
+          if (!gst_evaspixmapsink_xpixmap_link (evaspixmapsink)) {
+            GST_WARNING_OBJECT (evaspixmapsink,
+                "link evas image object with pixmap failed...");
+            evaspixmapsink->eo = NULL;
+            break;
+          }
+          /* add evas object callbacks on a new evas image object */
+          evas_object_event_callback_add (evaspixmapsink->eo, EVAS_CALLBACK_DEL,
+              evas_callback_del_event, evaspixmapsink);
+          evas_object_event_callback_add (evaspixmapsink->eo,
+              EVAS_CALLBACK_RESIZE, evas_callback_resize_event, evaspixmapsink);
+          GST_INFO_OBJECT (evaspixmapsink, "Evas Image Object(%p) is set",
+              evaspixmapsink->eo);
+        }
+      } else {
+        GST_ERROR_OBJECT (evaspixmapsink,
+            "Cannot set evas-object property: value is not an evas image object");
+      }
+      break;
+    case PROP_VISIBLE:
+    {
+      Eina_Bool r = EINA_FALSE;
+      gboolean visible = g_value_get_boolean (value);
+      GST_INFO_OBJECT (evaspixmapsink,
+          "evaspixmapsink->visible(%d), new value of visible(%d)",
+          evaspixmapsink->visible, visible);
+      if (evaspixmapsink->visible != visible) {
+        evaspixmapsink->visible = visible;
+        if (evaspixmapsink->eo) {
+          evaspixmapsink->update_visibility = UPDATE_TRUE;
+          if (evaspixmapsink->epipe_request_count > EPIPE_REQUEST_LIMIT) {
+            GST_WARNING_OBJECT (evaspixmapsink,
+                "skip ecore_pipe_write() reqest_count(%d)",
+                evaspixmapsink->epipe_request_count);
+            if (visible) {
+              evas_object_show (evaspixmapsink->eo);
+              GST_WARNING_OBJECT (evaspixmapsink, "object show (forcely)");
+            }
+          } else {
+            r = ecore_pipe_write (evaspixmapsink->epipe,
+                &evaspixmapsink->update_visibility, SIZE_FOR_UPDATE_VISIBILITY);
+            if (r == EINA_FALSE) {
+              GST_WARNING
+                  ("Failed to ecore_pipe_write() for updating visibility)\n");
+            }
+            evaspixmapsink->epipe_request_count++;
+          }
+
+          if (!visible) {
+            int i = 0;
+            g_mutex_lock (&evaspixmapsink->flow_lock);
+            for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+              if (evaspixmapsink->xpixmap[i]) {
+                gst_evaspixmapsink_xpixmap_clear (evaspixmapsink,
+                    evaspixmapsink->xpixmap[i]);
+              }
+            }
+            evas_object_hide (evaspixmapsink->eo);
+            GST_INFO_OBJECT (evaspixmapsink, "object hide (forcely)");
+            g_mutex_unlock (&evaspixmapsink->flow_lock);
+          } else {
+            g_mutex_lock (&evaspixmapsink->flow_lock);
+            gst_evaspixmap_buffer_put (evaspixmapsink,
+                evaspixmapsink->evas_pixmap_buf);
+            g_mutex_unlock (&evaspixmapsink->flow_lock);
+          }
+        } else {
+          GST_WARNING_OBJECT (evaspixmapsink, "evas image object was not set");
+        }
+      }
+      break;
+    }
+    case PROP_ORIGIN_SIZE:
+      evaspixmapsink->use_origin_size = g_value_get_boolean (value);
+      GST_INFO_OBJECT (evaspixmapsink, "set origin-size (%d)",
+          evaspixmapsink->use_origin_size);
+      if (evaspixmapsink->former_origin_size != evaspixmapsink->use_origin_size) {
+        if (!gst_evaspixmapsink_xpixmap_link (evaspixmapsink)) {
+          GST_WARNING_OBJECT (evaspixmapsink,
+              "link evas image object with pixmap failed...");
+        }
+        evaspixmapsink->former_origin_size = evaspixmapsink->use_origin_size;
+      }
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_evaspixmapsink_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+  int i = 0;
+
+  g_return_if_fail (GST_IS_EVASPIXMAPSINK (object));
+
+  evaspixmapsink = GST_EVASPIXMAPSINK (object);
+
+  switch (prop_id) {
+    case PROP_HUE:
+      g_value_set_int (value, evaspixmapsink->hue);
+      break;
+    case PROP_CONTRAST:
+      g_value_set_int (value, evaspixmapsink->contrast);
+      break;
+    case PROP_BRIGHTNESS:
+      g_value_set_int (value, evaspixmapsink->brightness);
+      break;
+    case PROP_SATURATION:
+      g_value_set_int (value, evaspixmapsink->saturation);
+      break;
+    case PROP_DISPLAY:
+      g_value_set_string (value, evaspixmapsink->display_name);
+      break;
+    case PROP_SYNCHRONOUS:
+      g_value_set_boolean (value, evaspixmapsink->synchronous);
+      break;
+    case PROP_PIXEL_ASPECT_RATIO:
+      if (evaspixmapsink->par) {
+        if (!g_value_transform (evaspixmapsink->par, value)) {
+          g_warning ("g_value_transform() failure");
+        }
+      }
+      break;
+    case PROP_FORCE_ASPECT_RATIO:
+      g_value_set_boolean (value, evaspixmapsink->keep_aspect);
+      break;
+    case PROP_DEVICE:
+    {
+      char *adaptor_no_s = g_strdup_printf ("%u", evaspixmapsink->adaptor_no);
+      g_value_set_string (value, adaptor_no_s);
+      g_free (adaptor_no_s);
+      break;
+    }
+    case PROP_DEVICE_NAME:
+      if (evaspixmapsink->xcontext && evaspixmapsink->xcontext->adaptors) {
+        g_value_set_string (value,
+            evaspixmapsink->xcontext->adaptors[evaspixmapsink->adaptor_no]);
+      } else {
+        g_value_set_string (value, NULL);
+      }
+      break;
+    case PROP_DOUBLE_BUFFER:
+      g_value_set_boolean (value, evaspixmapsink->double_buffer);
+      break;
+    case PROP_AUTOPAINT_COLORKEY:
+      g_value_set_boolean (value, evaspixmapsink->autopaint_colorkey);
+      break;
+    case PROP_COLORKEY:
+      g_value_set_int (value, evaspixmapsink->colorkey);
+      break;
+    case PROP_PIXMAP_WIDTH:
+      for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+        if (evaspixmapsink->xpixmap[i]) {
+          g_value_set_uint64 (value, evaspixmapsink->xpixmap[i]->width);
+        } else {
+          g_value_set_uint64 (value, 0);
+        }
+      }
+      break;
+    case PROP_PIXMAP_HEIGHT:
+      for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+        if (evaspixmapsink->xpixmap[i]) {
+          g_value_set_uint64 (value, evaspixmapsink->xpixmap[i]->height);
+        } else {
+          g_value_set_uint64 (value, 0);
+        }
+      }
+      break;
+    case PROP_DISPLAY_GEOMETRY_METHOD:
+      g_value_set_enum (value, evaspixmapsink->display_geometry_method);
+      break;
+    case PROP_DST_ROI_X:
+      g_value_set_int (value, evaspixmapsink->dst_roi.x);
+      break;
+    case PROP_DST_ROI_Y:
+      g_value_set_int (value, evaspixmapsink->dst_roi.y);
+      break;
+    case PROP_DST_ROI_W:
+      g_value_set_int (value, evaspixmapsink->dst_roi.w);
+      break;
+    case PROP_DST_ROI_H:
+      g_value_set_int (value, evaspixmapsink->dst_roi.h);
+      break;
+    case PROP_STOP_VIDEO:
+      g_value_set_int (value, evaspixmapsink->stop_video);
+      break;
+    case PROP_FLIP:
+      g_value_set_enum (value, evaspixmapsink->flip);
+      break;
+    case PROP_ROTATE_ANGLE:
+      g_value_set_enum (value, evaspixmapsink->rotate_angle);
+      break;
+    case PROP_EVAS_OBJECT:
+      g_value_set_pointer (value, evaspixmapsink->eo);
+      break;
+    case PROP_VISIBLE:
+      g_value_set_boolean (value, evaspixmapsink->visible);
+      break;
+    case PROP_ORIGIN_SIZE:
+      g_value_set_boolean (value, evaspixmapsink->use_origin_size);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_evaspixmapsink_xpixmap_fillblack (tbm_bufmgr bufmgr, Display * disp,
+    Pixmap pixmap)
+{
+  unsigned int attachments[1] = { DRI2BufferFrontLeft };
+  int dri2_out_temp, dri2_out_width, dri2_out_height;
+  DRI2Buffer *pDRI2Buffer =
+      DRI2GetBuffers (disp, pixmap, &dri2_out_width, &dri2_out_height,
+      attachments, 1, &dri2_out_temp);
+  if (!pDRI2Buffer)
+    GST_ERROR ("failed to get DRI2 buffers for fillblack.");
+  else {
+    GST_DEBUG ("width=%d height=%d name=%d flags=0x%x", dri2_out_width,
+        dri2_out_height, pDRI2Buffer[0].name, pDRI2Buffer[0].flags);
+    tbm_bo bo = tbm_bo_import (bufmgr, pDRI2Buffer[0].name);
+    memset (tbm_bo_map (bo, TBM_DEVICE_CPU, TBM_OPTION_WRITE).ptr, 0,
+        tbm_bo_size (bo));
+    tbm_bo_unmap (bo);
+    tbm_bo_unref (bo);
+    XFree (pDRI2Buffer);
+  }
+}
+
+static GstFlowReturn
+gst_evaspixmapsink_epipe_reset (GstEvasPixmapSink * evaspixmapsink)
+{
+  if (evaspixmapsink == NULL) {
+    GST_ERROR ("handle is NULL");
+    return GST_FLOW_ERROR;
+  }
+
+  if (evaspixmapsink->epipe) {
+    GST_DEBUG ("ecore-pipe will be deleted");
+    ecore_pipe_del (evaspixmapsink->epipe);
+    evaspixmapsink->epipe = NULL;
+  }
+
+  if (!evaspixmapsink->epipe) {
+    evaspixmapsink->epipe =
+        ecore_pipe_add ((Ecore_Pipe_Cb) ecore_pipe_callback_handler,
+        evaspixmapsink);
+    if (!evaspixmapsink->epipe) {
+      GST_ERROR ("ecore-pipe create failed");
+      return GST_FLOW_ERROR;
+    }
+    GST_DEBUG ("ecore-pipe create success");
+  }
+  evaspixmapsink->epipe_request_count = 0;
+
+  return GST_FLOW_OK;
+}
+
+static void
+gst_evaspixmapsink_reset (GstEvasPixmapSink * evaspixmapsink)
+{
+  FUNCTION_ENTER ();
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[START]");
+
+  GThread *thread;
+  GST_OBJECT_LOCK (evaspixmapsink);
+  evaspixmapsink->running = FALSE;
+  int i = 0;
+
+  /* grab thread and mark it as NULL */
+  thread = evaspixmapsink->event_thread;
+  evaspixmapsink->event_thread = NULL;
+  GST_OBJECT_UNLOCK (evaspixmapsink);
+
+  /* Wait for our event thread to finish before we clean up our stuff. */
+  if (thread) {
+    g_thread_join (thread);
+  }
+
+  for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+    if (evaspixmapsink->damage[i]) {
+      g_mutex_lock (&evaspixmapsink->x_lock);
+      XDamageDestroy (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->damage[i]);
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      evaspixmapsink->damage[i] = 0;
+    }
+  }
+  for (i = 0; i < NUM_OF_PREV_PIXMAP; i++) {
+    if (evaspixmapsink->prev[i]->damage) {
+      g_mutex_lock (&evaspixmapsink->x_lock);
+      GST_DEBUG_OBJECT (evaspixmapsink, "Free damage");
+      XDamageDestroy (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->prev[i]->damage);
+      g_mutex_unlock (&evaspixmapsink->x_lock);
+      evaspixmapsink->prev[i]->damage = 0;
+    }
+  }
+
+  if (evaspixmapsink->handler) {
+    ecore_event_handler_del (evaspixmapsink->handler);
+    evaspixmapsink->handler = NULL;
+  }
+
+  evas_object_event_callback_del (evaspixmapsink->eo, EVAS_CALLBACK_RESIZE,
+      evas_callback_resize_event);
+  evas_object_event_callback_del (evaspixmapsink->eo, EVAS_CALLBACK_DEL,
+      evas_callback_del_event);
+
+  if (evaspixmapsink->evas_pixmap_buf) {
+//  gst_evaspixmap_buffer_finalize(evaspixmapsink->evas_pixmap_buf);
+    evaspixmapsink->evas_pixmap_buf = NULL;
+  }
+  for (i = 0; i < evaspixmapsink->num_of_pixmaps; i++) {
+    gst_evaspixmapsink_xpixmap_clear (evaspixmapsink,
+        evaspixmapsink->xpixmap[i]);
+    gst_evaspixmapsink_xpixmap_destroy (evaspixmapsink,
+        evaspixmapsink->xpixmap[i]);
+    evaspixmapsink->xpixmap[i] = NULL;
+  }
+  for (i = 0; i < NUM_OF_PREV_PIXMAP; i++) {
+    g_mutex_lock (&evaspixmapsink->x_lock);
+    if (evaspixmapsink->prev[i]->pixmap) {
+      GST_DEBUG_OBJECT (evaspixmapsink, "Free pixmap");
+      XFreePixmap (evaspixmapsink->xcontext->disp,
+          evaspixmapsink->prev[i]->pixmap);
+      evaspixmapsink->prev[i]->pixmap = 0;
+    }
+    if (evaspixmapsink->prev[i]->gc) {
+      GST_DEBUG_OBJECT (evaspixmapsink, "Free gc");
+      XFreeGC (evaspixmapsink->xcontext->disp, evaspixmapsink->prev[i]->gc);
+      evaspixmapsink->prev[i]->gc = NULL;
+    }
+    XSync (evaspixmapsink->xcontext->disp, FALSE);
+    g_mutex_unlock (&evaspixmapsink->x_lock);
+  }
+  if (evaspixmapsink->eo) {
+    evas_object_image_native_surface_set (evaspixmapsink->eo, NULL);
+    evas_object_image_data_set (evaspixmapsink->eo, NULL);
+    evaspixmapsink->eo = NULL;
+  }
+  if (evaspixmapsink->epipe) {
+    ecore_pipe_del (evaspixmapsink->epipe);
+    evaspixmapsink->epipe = NULL;
+  }
+#ifdef DUMP_IMG
+  g_cnt = 0;
+#endif
+  evaspixmapsink->render_rect.x = evaspixmapsink->render_rect.y =
+      evaspixmapsink->render_rect.w = evaspixmapsink->render_rect.h = 0;
+  evaspixmapsink->have_render_rect = FALSE;
+
+  if (evaspixmapsink->xcontext) {
+    XSync (evaspixmapsink->xcontext->disp, TRUE);
+  }
+  evaspixmapsink->epipe_request_count = 0;
+  gst_evaspixmapsink_xcontext_clear (evaspixmapsink);
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+}
+
+/* Finalize is called only once, dispose can be called multiple times.
+ * We use mutexes and don't reset stuff to NULL here so let's register
+ * as a finalize. */
+static void
+gst_evaspixmapsink_finalize (GObject * object)
+{
+  FUNCTION_ENTER ();
+
+  GstEvasPixmapSink *evaspixmapsink;
+  int i = 0;
+  evaspixmapsink = GST_EVASPIXMAPSINK (object);
+  GST_DEBUG_OBJECT (evaspixmapsink, "[START]");
+
+  if (evaspixmapsink->display_name) {
+    g_free (evaspixmapsink->display_name);
+    evaspixmapsink->display_name = NULL;
+  }
+  if (evaspixmapsink->par) {
+    g_free (evaspixmapsink->par);
+    evaspixmapsink->par = NULL;
+  }
+  for (i = 0; i < NUM_OF_PREV_PIXMAP; i++) {
+    g_free (evaspixmapsink->prev[i]);
+  }
+
+  g_mutex_clear (&evaspixmapsink->x_lock);
+  g_mutex_clear (&evaspixmapsink->flow_lock);
+  g_mutex_clear (&evaspixmapsink->pixmap_ref_lock);
+  if (evaspixmapsink->bufmgr_for_black)
+    tbm_bufmgr_deinit (evaspixmapsink->bufmgr_for_black);
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+
+  G_OBJECT_CLASS (parent_class)->finalize (object);
+
+}
+
+static void
+gst_evaspixmapsink_init (GstEvasPixmapSink * evaspixmapsink)
+{
+  GST_DEBUG_OBJECT (evaspixmapsink, "[START]");
+
+  int i = 0;
+  evaspixmapsink->display_name = NULL;
+  evaspixmapsink->adaptor_no = 0;
+  evaspixmapsink->xcontext = NULL;
+  for (i = 0; i < NUM_OF_PIXMAP; i++) {
+    evaspixmapsink->xpixmap[i] = NULL;
+    evaspixmapsink->damage[i] = 0;
+  }
+  for (i = 0; i < NUM_OF_PREV_PIXMAP; i++) {
+    evaspixmapsink->prev[i] = NULL;
+  }
+
+  /* create prev structure */
+  for (i = 0; i < NUM_OF_PREV_PIXMAP; i++) {
+    /* prev can be created in this function only */
+    evaspixmapsink->prev[i] = g_new0 (GstPrevPixmap, 1);
+    if (!evaspixmapsink->prev[i]) {
+      GST_ERROR_OBJECT (evaspixmapsink, "prev structure is not valid..");
+      int j = 0;
+      for (j = 0; j < i; j++) {
+        g_free (evaspixmapsink->prev[j]);
+      }
+    }
+  }
+  evaspixmapsink->num_of_pixmaps = NUM_OF_PIXMAP;
+  evaspixmapsink->evas_pixmap_buf = NULL;
+
+  evaspixmapsink->hue = evaspixmapsink->saturation = 0;
+  evaspixmapsink->contrast = evaspixmapsink->brightness = 0;
+  evaspixmapsink->cb_changed = FALSE;
+
+  evaspixmapsink->fps_n = 0;
+  evaspixmapsink->fps_d = 0;
+  evaspixmapsink->video_width = 0;
+  evaspixmapsink->video_height = 0;
+  evaspixmapsink->need_to_fill_black = FALSE;
+
+  g_mutex_init (&evaspixmapsink->x_lock);
+  g_mutex_init (&evaspixmapsink->flow_lock);
+  g_mutex_init (&evaspixmapsink->pixmap_ref_lock);
+
+  evaspixmapsink->synchronous = FALSE;
+  evaspixmapsink->double_buffer = TRUE;
+  evaspixmapsink->keep_aspect = FALSE;
+  evaspixmapsink->par = NULL;
+  evaspixmapsink->autopaint_colorkey = TRUE;
+  evaspixmapsink->running = FALSE;
+
+  /* on 16bit displays this becomes r,g,b = 1,2,3
+   * on 24bit displays this becomes r,g,b = 8,8,16
+   * as a port atom value
+   */
+  evaspixmapsink->colorkey = (8 << 16) | (8 << 8) | 16;
+  evaspixmapsink->display_geometry_method = DEF_DISPLAY_GEOMETRY_METHOD;
+  evaspixmapsink->dst_roi.x = 0;
+  evaspixmapsink->dst_roi.y = 0;
+  evaspixmapsink->dst_roi.w = 0;
+  evaspixmapsink->dst_roi.h = 0;
+  evaspixmapsink->scr_w = 0;
+  evaspixmapsink->scr_h = 0;
+  evaspixmapsink->aligned_width = 0;
+  evaspixmapsink->aligned_height = 0;
+  evaspixmapsink->eo = NULL;
+  evaspixmapsink->epipe = NULL;
+  evaspixmapsink->epipe_request_count = 0;
+  evaspixmapsink->flip = DEF_DISPLAY_FLIP;
+  evaspixmapsink->rotate_angle = DEGREE_0;
+  evaspixmapsink->visible = TRUE;
+  evaspixmapsink->use_origin_size = FALSE;
+  evaspixmapsink->stop_video = FALSE;
+  evaspixmapsink->eo = NULL;
+  evaspixmapsink->epipe = NULL;
+  evaspixmapsink->do_link = FALSE;
+  evaspixmapsink->visible = TRUE;
+  evaspixmapsink->update_visibility = UPDATE_FALSE;
+  evaspixmapsink->use_origin_size = FALSE;
+  evaspixmapsink->former_origin_size = FALSE;
+  evaspixmapsink->last_updated_idx = -1;
+  evaspixmapsink->bufmgr_for_black = tbm_bufmgr_init (-1);
+  if (!evaspixmapsink->bufmgr_for_black)
+    GST_WARNING ("tbm_bufmgr_init is failed");
+
+  memset (&evaspixmapsink->src_prev, 0, sizeof (GstVideoRectangle));
+  memset (&evaspixmapsink->result_prev, 0, sizeof (GstVideoRectangle));
+
+  /*X can't gurarantee thread  safe: sometimes, X can't render Video.
+     Add XInitThread() before XOpenDisplay() */
+  if (!XInitThreads ())
+    GST_WARNING ("FAIL to call XInitThreads()");
+
+  GST_DEBUG_OBJECT (evaspixmapsink, "[END]");
+}
+
+static void
+gst_evaspixmapsink_base_init (gpointer g_class)
+{
+  FUNCTION_ENTER ();
+
+}
+
+static void
+gst_evaspixmapsink_class_init (GstEvasPixmapSinkClass * klass)
+{
+  FUNCTION_ENTER ();
+
+  GObjectClass *gobject_class;
+  GstElementClass *gstelement_class;
+  GstBaseSinkClass *gstbasesink_class;
+  GstVideoSinkClass *videosink_class;
+
+  gobject_class = (GObjectClass *) klass;
+  gstelement_class = (GstElementClass *) klass;
+  gstbasesink_class = (GstBaseSinkClass *) klass;
+  videosink_class = (GstVideoSinkClass *) klass;
+
+  parent_class = g_type_class_peek_parent (klass);
+
+  gobject_class->set_property = gst_evaspixmapsink_set_property;
+  gobject_class->get_property = gst_evaspixmapsink_get_property;
+
+  g_object_class_install_property (gobject_class, PROP_CONTRAST,
+      g_param_spec_int ("contrast", "Contrast", "The contrast of the video",
+          -1000, 1000, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_BRIGHTNESS,
+      g_param_spec_int ("brightness", "Brightness",
+          "The brightness of the video", -1000, 1000, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_HUE,
+      g_param_spec_int ("hue", "Hue", "The hue of the video", -1000, 1000, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_SATURATION,
+      g_param_spec_int ("saturation", "Saturation",
+          "The saturation of the video", -1000, 1000, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_DISPLAY,
+      g_param_spec_string ("display", "Display", "X Display name", NULL,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_SYNCHRONOUS,
+      g_param_spec_boolean ("synchronous", "Synchronous",
+          "When enabled, runs "
+          "the X display in synchronous mode. (used only for debugging)", FALSE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_PIXEL_ASPECT_RATIO,
+      g_param_spec_string ("pixel-aspect-ratio", "Pixel Aspect Ratio",
+          "The pixel aspect ratio of the device", "1/1",
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_FORCE_ASPECT_RATIO,
+      g_param_spec_boolean ("force-aspect-ratio", "Force aspect ratio",
+          "When enabled, scaling will respect original aspect ratio", FALSE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_DEVICE,
+      g_param_spec_string ("device", "Adaptor number",
+          "The number of the video adaptor", "0",
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
+      g_param_spec_string ("device-name", "Adaptor name",
+          "The name of the video adaptor", NULL,
+          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:double-buffer
+   *
+   * Whether to double-buffer the output.
+   *
+   * Since: 0.10.14
+   */
+  g_object_class_install_property (gobject_class, PROP_DOUBLE_BUFFER,
+      g_param_spec_boolean ("double-buffer", "Double-buffer",
+          "Whether to double-buffer the output", TRUE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstEvasPixmapSink:autopaint-colorkey
+   *
+   * Whether to autofill overlay with colorkey
+   *
+   * Since: 0.10.21
+   */
+  g_object_class_install_property (gobject_class, PROP_AUTOPAINT_COLORKEY,
+      g_param_spec_boolean ("autopaint-colorkey", "Autofill with colorkey",
+          "Whether to autofill overlay with colorkey", TRUE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstEvasPixmapSink:colorkey
+   *
+   * Color to use for the overlay mask.
+   *
+   * Since: 0.10.21
+   */
+  g_object_class_install_property (gobject_class, PROP_COLORKEY,
+      g_param_spec_int ("colorkey", "Colorkey",
+          "Color to use for the overlay mask", G_MININT, G_MAXINT, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:pixmap-width
+   *
+   * Actual width of the pixmap.
+   */
+  g_object_class_install_property (gobject_class, PROP_PIXMAP_WIDTH,
+      g_param_spec_uint64 ("pixmap-width", "pixmap-width",
+          "Width of the pixmap", 0, G_MAXUINT64, 0,
+          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:pixmap-height
+   *
+   * Actual height of the pixmap.
+   */
+  g_object_class_install_property (gobject_class, PROP_PIXMAP_HEIGHT,
+      g_param_spec_uint64 ("pixmap-height", "pixmap-height",
+          "Height of the pixmap", 0, G_MAXUINT64, 0,
+          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:display-geometry-method
+   *
+   * Display geometrical method setting
+   */
+  g_object_class_install_property (gobject_class, PROP_DISPLAY_GEOMETRY_METHOD,
+      g_param_spec_enum ("display-geometry-method", "Display geometry method",
+          "Geometrical method for display",
+          GST_TYPE_EVASPIXMAPSINK_DISPLAY_GEOMETRY_METHOD,
+          DEF_DISPLAY_GEOMETRY_METHOD,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:dst-roi-x
+   *
+   * X value of Destination ROI
+   */
+  g_object_class_install_property (gobject_class, PROP_DST_ROI_X,
+      g_param_spec_int ("dst-roi-x", "Dst-ROI-X",
+          "X value of Destination ROI(only effective \"CUSTOM_ROI\")", 0,
+          XV_SCREEN_SIZE_WIDTH, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:dst-roi-y
+   *
+   * Y value of Destination ROI
+   */
+  g_object_class_install_property (gobject_class, PROP_DST_ROI_Y,
+      g_param_spec_int ("dst-roi-y", "Dst-ROI-Y",
+          "Y value of Destination ROI(only effective \"CUSTOM_ROI\")", 0,
+          XV_SCREEN_SIZE_HEIGHT, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:dst-roi-w
+   *
+   * W value of Destination ROI
+   */
+  g_object_class_install_property (gobject_class, PROP_DST_ROI_W,
+      g_param_spec_int ("dst-roi-w", "Dst-ROI-W",
+          "W value of Destination ROI(only effective \"CUSTOM_ROI\")", 0,
+          XV_SCREEN_SIZE_WIDTH, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:dst-roi-h
+   *
+   * H value of Destination ROI
+   */
+  g_object_class_install_property (gobject_class, PROP_DST_ROI_H,
+      g_param_spec_int ("dst-roi-h", "Dst-ROI-H",
+          "H value of Destination ROI(only effective \"CUSTOM_ROI\")", 0,
+          XV_SCREEN_SIZE_HEIGHT, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:stop-video
+   *
+   * Stop video for releasing video source buffer
+   */
+  g_object_class_install_property (gobject_class, PROP_STOP_VIDEO,
+      g_param_spec_int ("stop-video", "Stop-Video",
+          "Stop video for releasing video source buffer", 0, 1, 0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:display-flip
+   *
+   * Display flip setting
+   */
+  g_object_class_install_property (gobject_class, PROP_FLIP,
+      g_param_spec_enum ("flip", "Display flip",
+          "Flip for display",
+          GST_TYPE_EVASPIXMAPSINK_FLIP, DEF_DISPLAY_FLIP,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:rotate
+   *
+   * draw rotation angle setting
+   */
+  g_object_class_install_property (gobject_class, PROP_ROTATE_ANGLE,
+      g_param_spec_enum ("rotate", "Rotate angle",
+          "Rotate angle of display output",
+          GST_TYPE_EVASPIXMAPSINK_ROTATE_ANGLE, DEGREE_0,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:evas-object
+   *
+   * Evas image object for rendering
+   */
+  g_object_class_install_property (gobject_class, PROP_EVAS_OBJECT,
+      g_param_spec_pointer ("evas-object", "Destination Evas Object",
+          "Destination evas image object",
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstEvasPixmapSink:visible
+   *
+   * visible setting for a evas image object
+   */
+  g_object_class_install_property (gobject_class, PROP_VISIBLE,
+      g_param_spec_boolean ("visible", "Visible",
+          "When setting it false, evas image object does not show", TRUE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+   /**
+   * GstEvasPixmapSink:origin-size
+   *
+   * Set pixmap size with media source's width and height
+   */
+  g_object_class_install_property (gobject_class, PROP_ORIGIN_SIZE,
+      g_param_spec_boolean ("origin-size", "Origin-Size",
+          "When setting it true, pixmap will be created with media source's width and height",
+          FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  gobject_class->finalize = gst_evaspixmapsink_finalize;
+
+  gstelement_class->change_state =
+      GST_DEBUG_FUNCPTR (gst_evaspixmapsink_change_state);
+  gst_element_class_set_details_simple (gstelement_class, "EvasPixmapSink",
+      "Sink/Video", "evas image object videosink based on Xv extension",
+      "Sangchul Lee <sc11.lee@samsung.com>");
+
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&gst_evaspixmapsink_sink_template_factory));
+  gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_evaspixmapsink_getcaps);
+  gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_evaspixmapsink_setcaps);
+  gstbasesink_class->get_times =
+      GST_DEBUG_FUNCPTR (gst_evaspixmapsink_get_times);
+  gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_evaspixmapsink_event);
+  videosink_class->show_frame =
+      GST_DEBUG_FUNCPTR (gst_evaspixmapsink_show_frame);
+}
+
+/* Object typing & Creation */
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+  FUNCTION_ENTER ();
+
+  if (!gst_element_register (plugin, "evaspixmapsink", GST_RANK_NONE,
+          GST_TYPE_EVASPIXMAPSINK)) {
+    return FALSE;
+  }
+  GST_DEBUG_CATEGORY_INIT (gst_debug_evaspixmapsink, "evaspixmapsink", 0,
+      "evaspixmapsink element");
+  GST_DEBUG_CATEGORY_GET (GST_CAT_PERFORMANCE, "GST_PERFORMANCE");
+
+  return TRUE;
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR, GST_VERSION_MINOR,
+    evaspixmapsink, "Evas image object render plugin using Xv extension",
+    plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)
diff --git a/evaspixmapsink/evaspixmapsink.h b/evaspixmapsink/evaspixmapsink.h
new file mode 100755 (executable)
index 0000000..3c68c6f
--- /dev/null
@@ -0,0 +1,424 @@
+/*
+ * EvasPixmapSink
+ *
+ * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Sangchul Lee <sc11.lee@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifndef __GST_EVASPIXMAPSINK_H__
+#define __GST_EVASPIXMAPSINK_H__
+
+#include <gst/video/gstvideosink.h>
+
+#ifdef HAVE_XSHM
+#include <sys/types.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#endif /* HAVE_XSHM */
+
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+#ifdef HAVE_XSHM
+#include <X11/extensions/XShm.h>
+#endif /* HAVE_XSHM */
+
+#include <X11/extensions/Xv.h>
+#include <X11/extensions/Xvlib.h>
+#include <X11/extensions/Xdamage.h>
+#include <X11/extensions/damagewire.h>
+#include <X11/Xatom.h>
+#include <stdio.h>
+
+#include <Evas.h>
+#include <Ecore.h>
+#include <Ecore_X.h>
+
+#include <tbm_bufmgr.h>
+
+#include <string.h>
+#include <math.h>
+#include <stdlib.h>
+
+#include <gst/video/video-info.h>
+#include <gst/video/video-format.h>
+
+//#define DUMP_IMG
+#define MAX_PLANE_NUM          3
+#define MAX_BUFFER_NUM         20
+#define MAX_GEM_BUFFER_NUM     (MAX_PLANE_NUM * MAX_BUFFER_NUM)
+typedef struct _gem_info_t
+{
+  int dmabuf_fd;
+  unsigned int gem_handle;
+  unsigned int gem_name;
+  tbm_bo bo;
+} gem_info_t;
+
+
+G_BEGIN_DECLS
+#define GST_TYPE_EVASPIXMAPSINK \
+  (gst_evaspixmapsink_get_type())
+#define GST_EVASPIXMAPSINK(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_EVASPIXMAPSINK, GstEvasPixmapSink))
+#define GST_EVASPIXMAPSINK_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_EVASPIXMAPSINK, GstEvasPixmapSinkClass))
+#define GST_IS_EVASPIXMAPSINK(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_EVASPIXMAPSINK))
+#define GST_IS_EVASPIXMAPSINK_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass), GST_TYPE_EVASPIXMAPSINK))
+#define XV_SCREEN_SIZE_WIDTH 4096
+#define XV_SCREEN_SIZE_HEIGHT 4096
+#define MARGIN_OF_ERROR 0.005
+#define NUM_OF_PIXMAP         3
+#define NUM_OF_PREV_PIXMAP    15
+typedef struct _GstXContext GstXContext;
+typedef struct _GstXPixmap GstXPixmap;
+typedef struct _GstPrevPixmap GstPrevPixmap;
+typedef struct _GstEvasPixmapFormat GstEvasPixmapFormat;
+typedef struct _GstEvasPixmapBuffer GstEvasPixmapBuffer;
+typedef struct _GstEvasPixmapBufferClass GstEvasPixmapBufferClass;
+typedef struct _GstEvasPixmapSink GstEvasPixmapSink;
+typedef struct _GstEvasPixmapSinkClass GstEvasPixmapSinkClass;
+
+/*
+ * GstXContext:
+ * @disp: the X11 Display of this context
+ * @screen: the default Screen of Display @disp
+ * @screen_num: the Screen number of @screen
+ * @visual: the default Visual of Screen @screen
+ * @root: the root Window of Display @disp
+ * @white: the value of a white pixel on Screen @screen
+ * @black: the value of a black pixel on Screen @screen
+ * @depth: the color depth of Display @disp
+ * @bpp: the number of bits per pixel on Display @disp
+ * @endianness: the endianness of image bytes on Display @disp
+ * @width: the width in pixels of Display @disp
+ * @height: the height in pixels of Display @disp
+ * @widthmm: the width in millimeters of Display @disp
+ * @heightmm: the height in millimeters of Display @disp
+ * @par: the pixel aspect ratio calculated from @width, @widthmm and @height,
+ * @heightmm ratio
+ * @use_xshm: used to known wether of not XShm extension is usable or not even
+ * if the Extension is present
+ * @xv_port_id: the XVideo port ID
+ * @im_format: used to store at least a valid format for XShm calls checks
+ * @formats_list: list of supported image formats on @xv_port_id
+ * @channels_list: list of #GstColorBalanceChannels
+ * @caps: the #GstCaps that Display @disp can accept
+ *
+ * Structure used to store various informations collected/calculated for a
+ * Display.
+ */
+struct _GstXContext
+{
+  Display *disp;
+
+  Screen *screen;
+  gint screen_num;
+
+  Visual *visual;
+
+  Window root;
+
+  gulong white, black;
+
+  gint depth;
+  gint bpp;
+  gint endianness;
+
+  gint width, height;
+  gint widthmm, heightmm;
+  GValue *par;                  /* calculated pixel aspect ratio */
+
+  gboolean use_xshm;
+
+  XvPortID xv_port_id;
+  guint nb_adaptors;
+  gchar **adaptors;
+  guint32 im_format;
+
+  GList *formats_list;
+  GList *channels_list;
+
+  GstCaps *caps;
+};
+
+/*
+ * GstXPixmap:
+ * @pixmap: the pixmap ID of this X11 pixmap
+ * @width: the width in pixels of Pixmap @pixmap
+ * @height: the height in pixels of Pixmap @pixmap
+ * @gc: the Graphical Context of Pixmap @pixmap
+ *
+ * Structure used to store informations about a Pixmap.
+ */
+struct _GstXPixmap
+{
+  Pixmap pixmap;
+  gint x, y;
+  gint width, height;
+  GC gc;
+  gint ref;
+  gint damaged_time;
+};
+
+struct _GstPrevPixmap
+{
+  Pixmap pixmap;
+  GC gc;
+  Damage damage;
+};
+
+/**
+ * GstEvasPixmapFormat:
+ * @format: the image format
+ * @caps: generated #GstCaps for this image format
+ *
+ * Structure storing image format to #GstCaps association.
+ */
+struct _GstEvasPixmapFormat
+{
+  guint32 format;
+  GstVideoFormat vformat;
+  GstCaps *caps;
+};
+
+/**
+ * GstEvasPixmapBuffer:
+ * @evaspixmapsink: a reference to our #GstEvasPixmapSink
+ * @xvimage: the XvImage of this buffer
+ * @width: the width in pixels of XvImage @xvimage
+ * @height: the height in pixels of XvImage @xvimage
+ * @im_format: the image format of XvImage @xvimage
+ * @size: the size in bytes of XvImage @xvimage
+ *
+ * Subclass of #GstBuffer containing additional information about an XvImage.
+ */
+struct _GstEvasPixmapBuffer
+{
+  GstBuffer *buffer;
+
+  /* Reference to the evaspixmapsink we belong to */
+  GstEvasPixmapSink *evaspixmapsink;
+  XvImage *xvimage;
+
+#ifdef HAVE_XSHM
+  XShmSegmentInfo SHMInfo;
+#endif                          /* HAVE_XSHM */
+
+  gint width, height;
+  guint32 im_format;
+  size_t size;
+};
+
+/**
+ * GstEvasPixmapSink:
+ * @display_name: the name of the Display we want to render to
+ * @xcontext: our instance's #GstXContext
+ * @xpixmap: the #GstXPixmap we are rendering to
+ * @fps_n: the framerate fraction numerator
+ * @fps_d: the framerate fraction denominator
+ * @x_lock: used to protect X calls as we are not using the XLib in threaded
+ * mode
+ * @flow_lock: used to protect data flow routines from external calls such as
+ * methods from the #GstXOverlay interface
+ * @par: used to override calculated pixel aspect ratio from @xcontext
+ * @synchronous: used to store if XSynchronous should be used or not (for
+ * debugging purpose only)
+ * @keep_aspect: used to remember if reverse negotiation scaling should respect
+ * aspect ratio
+ * @brightness: used to store the user settings for color balance brightness
+ * @contrast: used to store the user settings for color balance contrast
+ * @hue: used to store the user settings for color balance hue
+ * @saturation: used to store the user settings for color balance saturation
+ * @cb_changed: used to store if the color balance settings where changed
+ * @video_width: the width of incoming video frames in pixels
+ * @video_height: the height of incoming video frames in pixels
+ *
+ * The #GstEvasPixmapSink data structure.
+ */
+struct _GstEvasPixmapSink
+{
+  /* Our element stuff */
+  GstVideoSink videosink;
+
+  char *display_name;
+  guint adaptor_no;
+
+  GstXContext *xcontext;
+  GstXPixmap *xpixmap[NUM_OF_PIXMAP];
+  GstPrevPixmap *prev[NUM_OF_PREV_PIXMAP];
+  GstEvasPixmapBuffer *evas_pixmap_buf;
+
+  GThread *event_thread;
+  gboolean running;
+
+  GstVideoInfo info;
+
+  gint fps_n;
+  gint fps_d;
+
+  GMutex x_lock;
+  GMutex flow_lock;
+  GMutex pixmap_ref_lock;
+
+  /* object-set pixel aspect ratio */
+  GValue *par;
+
+  gboolean synchronous;
+  gboolean double_buffer;
+  gboolean keep_aspect;
+
+  gint brightness;
+  gint contrast;
+  gint hue;
+  gint saturation;
+  gboolean cb_changed;
+
+  /* size of incoming video, used as the size for XvImage */
+  guint video_width, video_height;
+  gboolean need_to_fill_black;
+
+  /* display sizes, used for clipping the image */
+  gint disp_x, disp_y;
+  gint disp_width, disp_height;
+
+  /* port attributes */
+  gboolean autopaint_colorkey;
+  gint colorkey;
+
+  /* port features */
+  gboolean have_autopaint_colorkey;
+  gboolean have_colorkey;
+  gboolean have_double_buffer;
+
+  /* target video rectagle */
+  GstVideoRectangle render_rect;
+  gboolean have_render_rect;
+
+  /* display */
+  guint flip;
+  guint rotate_angle;
+  guint display_geometry_method;
+  GstVideoRectangle dst_roi;
+  guint scr_w, scr_h;
+  /* needed if fourcc is one if S series */
+  guint aligned_width;
+  guint aligned_height;
+  GstCaps *negotiated_caps;
+  gboolean stop_video;
+
+  /* evas object */
+  Evas_Object *eo;
+  Evas_Coord w;
+  Evas_Coord h;
+  gboolean visible;
+  gint last_updated_idx;
+  gchar update_visibility;
+  gint epipe_request_count;
+
+  /* pixmap */
+  gboolean do_link;
+  gboolean use_origin_size;
+  gboolean former_origin_size;
+  gint sizediff_width;
+  gint sizediff_height;
+  guint num_of_pixmaps;
+
+  /* damage event */
+  Damage damage[NUM_OF_PIXMAP];
+  int damage_case;
+  Ecore_Event_Handler *handler;
+  Ecore_Pipe *epipe;
+
+  gint drm_fd;
+  gem_info_t gem_info[MAX_GEM_BUFFER_NUM];
+  tbm_bufmgr bufmgr_for_black;
+
+  GstVideoRectangle src_prev;
+  GstVideoRectangle result_prev;
+
+  /* zero copy format */
+  gboolean is_zero_copy_format;
+#ifdef DUMP_IMG
+  void *pixmap_addr[NUM_OF_PIXMAP];
+#endif
+};
+
+/* max plane count *********************************************************/
+#define MPLANE_IMGB_MAX_COUNT         (4)
+
+/* image buffer definition ***************************************************
+
+    +------------------------------------------+ ---
+    |                                          |  ^
+    |     uaddr[], index[]                     |  |
+    |     +---------------------------+ ---    |  |
+    |     |                           |  ^     |  |
+    |     |<-------- width[] -------->|  |     |  |
+    |     |                           |  |     |  |
+    |     |                           |        |
+    |     |                           |height[]|elevation[]
+    |     |                           |        |
+    |     |                           |  |     |  |
+    |     |                           |  |     |  |
+    |     |                           |  v     |  |
+    |     +---------------------------+ ---    |  |
+    |                                          |  v
+    +------------------------------------------+ ---
+
+    |<----------------- stride[] ------------------>|
+*/
+typedef struct _GstMultiPlaneImageBuffer GstMultiPlaneImageBuffer;
+struct _GstMultiPlaneImageBuffer
+{
+  GstBuffer buffer;
+
+  /* width of each image plane */
+  gint width[MPLANE_IMGB_MAX_COUNT];
+  /* height of each image plane */
+  gint height[MPLANE_IMGB_MAX_COUNT];
+  /* stride of each image plane */
+  gint stride[MPLANE_IMGB_MAX_COUNT];
+  /* elevation of each image plane */
+  gint elevation[MPLANE_IMGB_MAX_COUNT];
+  /* user space address of each image plane */
+  gpointer uaddr[MPLANE_IMGB_MAX_COUNT];
+  /* Index of real address of each image plane, if needs */
+  gpointer index[MPLANE_IMGB_MAX_COUNT];
+  /* left postion, if needs */
+  gint x;
+  /* top position, if needs */
+  gint y;
+  /* to align memory */
+  gint __dummy2;
+  /* arbitrary data */
+  gint data[16];
+};
+
+struct _GstEvasPixmapSinkClass
+{
+  GstVideoSinkClass parent_class;
+};
+
+GType gst_evaspixmapsink_get_type (void);
+
+G_END_DECLS
+#endif /* __GST_EVASPIXMAPSINK_H__ */
diff --git a/evaspixmapsink/xv_types.h b/evaspixmapsink/xv_types.h
new file mode 100644 (file)
index 0000000..174e910
--- /dev/null
@@ -0,0 +1,48 @@
+/*                                                              */
+/* File name : xv_types.h                                       */
+/* Author : YoungHoon Jung (yhoon.jung@samsung.com)             */
+/* Protocol Version : 1.0.1 (Dec 16th 2009)                       */
+/* This file is for describing Xv APIs' buffer encoding method. */
+/*                                                              */
+
+#define XV_PUTIMAGE_HEADER     0xDEADCD01
+#define XV_PUTIMAGE_VERSION    0x00010001
+
+/* Return Values */
+#define XV_OK 0
+#define XV_HEADER_ERROR -1
+#define XV_VERSION_MISMATCH -2
+
+/* Video Mode */
+#define VIDEO_MODE_TV_LCD      1
+#define VIDEO_MODE_TVONLY      2
+#define VIDEO_MODE_LCDONLY     3
+#define VIDEO_MODE_TVCAPTION   4
+
+/* Buffer Type */
+#define XV_BUF_TYPE_DMABUF  0
+#define XV_BUF_TYPE_LEGACY  1
+#define XV_BUF_PLANE_NUM    3
+
+/* Data structure for XvPutImage / XvShmPutImage */
+typedef struct
+{
+  unsigned int _header;         /* for internal use only */
+  unsigned int _version;        /* for internal use only */
+
+  unsigned int YBuf;
+  unsigned int CbBuf;
+  unsigned int CrBuf;
+  unsigned int BufType;
+
+  unsigned int dmabuf_fd[XV_BUF_PLANE_NUM];
+  unsigned int gem_handle[XV_BUF_PLANE_NUM];
+  void *bo[XV_BUF_PLANE_NUM];
+} XV_PUTIMAGE_DATA, *XV_PUTIMAGE_DATA_PTR;
+
+static void
+XV_PUTIMAGE_INIT_DATA (XV_PUTIMAGE_DATA_PTR data)
+{
+  data->_header = XV_PUTIMAGE_HEADER;
+  data->_version = XV_PUTIMAGE_VERSION;
+}
diff --git a/fimcconvert/Makefile.am b/fimcconvert/Makefile.am
new file mode 100755 (executable)
index 0000000..5e1c07c
--- /dev/null
@@ -0,0 +1,15 @@
+# Copyright (c) 2006 Software Laboratory, SAMSUNG Electronics, Inc.\r
+# All rights reserved.\r
+#\r
+# This software is the confidential and proprietary information of\r
+# SAMSUNG Electronics, Inc. ("Confidential Information").\r
+# You shall not disclose such Confidential Information and shall use it\r
+# only in accordance with the terms of the license agreement you entered into\r
+# with SAMSUNG Electronics.\r
+#\r
+# Orignal by Jin-mook Lim <jinmook.lim@samsung.com>\r
+#            Bum-seok Lee <bumseok.lee@samsung.com>\r
+# Created by Jaekyun Lee <jkyun.lee@samsung.com>\r
+# Midefied by Jeechul jeon <heechul.jeon@samsung.com>\r
+\r
+SUBDIRS = src\r
diff --git a/fimcconvert/src/Makefile.am b/fimcconvert/src/Makefile.am
new file mode 100755 (executable)
index 0000000..6cbe2ce
--- /dev/null
@@ -0,0 +1,27 @@
+# plugindir is set in configure\r
+\r
+##############################################################################\r
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #\r
+##############################################################################\r
+plugin_LTLIBRARIES = libgstfimcconvert.la\r
+\r
+##############################################################################\r
+# for the next set of variables, rename the prefix if you renamed the .la,   #\r
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #\r
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #\r
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #\r
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #\r
+##############################################################################\r
+\r
+# sources used to compile this plug-in\r
+libgstfimcconvert_la_SOURCES = gstfimcconvert.c fimc_drm_api.c\r
+\r
+# flags used to compile this plugin\r
+# add other _CFLAGS and _LIBS as needed\r
+libgstfimcconvert_la_CFLAGS = $(GST_CFLAGS) $(GST_VIDEO_CFLAGS) $(DRM_CFLAGS) $(XFIXES_CFLAGS) $(DRI2PROTO_CFLAGS) $(DRI2_CFLAGS) $(TBM_CFLAGS) $(MMCOMMON_CFLAGS)\r
+libgstfimcconvert_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS) $(GST_BASE_LIBS) $(GST_VIDEO_LIBS) $(DRM_LIBS) $(XFIXES_LIBS) $(DRI2PROTO_LIBS) $(DRI2_LIBS) $(TBM_LIBS)\r
+libgstfimcconvert_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)\r
+\r
+# headers we need but don't want installed\r
+noinst_HEADERS = gstfimcconvert.h fimc_drm_api.h\r
+\r
diff --git a/fimcconvert/src/fimc_drm_api.c b/fimcconvert/src/fimc_drm_api.c
new file mode 100755 (executable)
index 0000000..d4e00c6
--- /dev/null
@@ -0,0 +1,425 @@
+ /*
+ * FimcConvert
+ *
+ * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Sangchul Lee <sc11.lee@samsung.com>, Eunchul Kim <chulspro.kim@sasmsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#include "fimc_drm_api.h"
+
+int
+exynos_drm_ipp_set_property(int fd,
+        struct drm_exynos_ipp_property *property,
+        struct drm_exynos_sz *src_sz, struct drm_exynos_sz *dst_sz,
+        uint32_t src_format, uint32_t dst_format,
+        enum drm_exynos_ipp_cmd cmd,
+        enum drm_exynos_degree dst_degree, enum drm_exynos_flip dst_flip)
+{
+  struct drm_exynos_pos src_crop_pos = {0, 0, src_sz->hsize, src_sz->vsize};
+  struct drm_exynos_pos dst_crop_pos = {0, 0, dst_sz->hsize, dst_sz->vsize};
+  int ret = 0;
+
+  if(!property) {
+    GST_ERROR("invalid argument, property is null..");
+    return -1;
+  }
+
+  memset(property, 0x00, sizeof(struct drm_exynos_ipp_property));
+  property->cmd = cmd;
+
+  switch(cmd) {
+  case IPP_CMD_M2M:
+    property->config[EXYNOS_DRM_OPS_SRC].ops_id = EXYNOS_DRM_OPS_SRC;
+    property->config[EXYNOS_DRM_OPS_SRC].flip = EXYNOS_DRM_FLIP_NONE;
+    property->config[EXYNOS_DRM_OPS_SRC].degree = EXYNOS_DRM_DEGREE_0;
+    property->config[EXYNOS_DRM_OPS_SRC].fmt = src_format;
+    property->config[EXYNOS_DRM_OPS_SRC].pos = src_crop_pos;
+    property->config[EXYNOS_DRM_OPS_SRC].sz = *src_sz;
+
+    property->config[EXYNOS_DRM_OPS_DST].ops_id = EXYNOS_DRM_OPS_DST;
+    property->config[EXYNOS_DRM_OPS_DST].flip = dst_flip;
+    property->config[EXYNOS_DRM_OPS_DST].degree = dst_degree;
+    property->config[EXYNOS_DRM_OPS_DST].fmt = dst_format;
+
+    /* Bit alignment for IPP : DST */
+    switch (dst_format) {
+    case DRM_FORMAT_NV12MT:
+      dst_sz->hsize = ALIGN_TO_16B(dst_sz->hsize);
+      dst_sz->vsize = ALIGN_TO_8B(dst_sz->vsize);
+      break;
+    case DRM_FORMAT_NV12:
+      /* NOTE: for H/W encoder issue, use ALIGN */
+      dst_sz->hsize = ALIGN_TO_16B(dst_sz->hsize);
+      dst_sz->vsize = ALIGN_TO_16B(dst_sz->vsize);
+      dst_crop_pos.w = ALIGN_TO_2B(dst_sz->hsize);
+      break;
+    case DRM_FORMAT_ARGB8888:
+    case DRM_FORMAT_XRGB8888:
+    case DRM_FORMAT_BGRX8888:
+    case DRM_FORMAT_BGRA8888:
+      dst_sz->vsize = ALIGN_TO_4B(dst_sz->vsize);
+      break;
+    default:
+      dst_sz->hsize = ALIGN_TO_16B(dst_sz->hsize);
+      dst_sz->vsize = ALIGN_TO_2B(dst_sz->vsize);
+      break;
+    }
+    GST_INFO ("***************************************");
+    GST_INFO (" ipp only use aligned outbuffer size   ");
+    GST_INFO (" Aligned width: %d, height: %d", dst_sz->vsize, dst_sz->hsize);
+    GST_INFO (" Aligned buffer size: %d",dst_sz->vsize * dst_sz->hsize);
+    GST_INFO ("***************************************");
+    property->config[EXYNOS_DRM_OPS_DST].pos = dst_crop_pos;
+    property->config[EXYNOS_DRM_OPS_DST].sz = *dst_sz;
+    break;
+
+  case IPP_CMD_WB:
+  case IPP_CMD_OUTPUT:
+  default:
+    ret = -EINVAL;
+    return ret;
+  }
+
+  ret = ioctl(fd, DRM_IOCTL_EXYNOS_IPP_SET_PROPERTY, property);
+  if (ret) {
+    GST_ERROR("failed to DRM_IOCTL_EXYNOS_IPP_SET_PROPERTY : %s", strerror(errno));
+  }
+
+  GST_DEBUG("DRM_IOCTL_EXYNOS_IPP_SET_PROPERTY : prop_id[%d]", property->prop_id);
+
+  return ret;
+}
+
+int
+exynos_drm_ipp_queue_buf(int fd,
+          enum drm_exynos_ops_id ops_id,
+          enum drm_exynos_ipp_buf_type buf_type,
+          int prop_id,
+          int buf_id,
+          uint32_t gem_handle_y, uint32_t gem_handle_cb, uint32_t gem_handle_cr)
+{
+  int ret = 0;
+  struct drm_exynos_ipp_queue_buf qbuf;
+
+  memset(&qbuf, 0x00, sizeof(struct drm_exynos_ipp_queue_buf));
+
+  if (!gem_handle_y) {
+    GST_ERROR("invalid argument, gem_handle_y is null..");
+    return -1;
+  }
+
+  qbuf.ops_id = ops_id;
+  qbuf.buf_type = buf_type;
+  qbuf.user_data = 0;
+  qbuf.prop_id = prop_id;
+  qbuf.buf_id = buf_id;
+  qbuf.handle[EXYNOS_DRM_PLANAR_Y] = gem_handle_y;
+  qbuf.handle[EXYNOS_DRM_PLANAR_CB] = gem_handle_cb;
+  qbuf.handle[EXYNOS_DRM_PLANAR_CR] = gem_handle_cr;
+
+  ret = ioctl(fd, DRM_IOCTL_EXYNOS_IPP_QUEUE_BUF, &qbuf);
+  if (ret) {
+    GST_ERROR("failed to DRM_IOCTL_EXYNOS_IPP_QUEUE_BUF[id:%d][buf_type:%d] : %s",
+                ops_id, buf_type, strerror(errno));
+  }
+
+  return ret;
+}
+
+int
+exynos_drm_ipp_cmd_ctrl(int fd, int prop_id, enum drm_exynos_ipp_ctrl ctrl)
+{
+  int ret = 0;
+  struct drm_exynos_ipp_cmd_ctrl cmd_ctrl;
+
+  memset(&cmd_ctrl, 0x00, sizeof(struct drm_exynos_ipp_cmd_ctrl));
+
+  cmd_ctrl.prop_id = prop_id;
+  cmd_ctrl.ctrl = ctrl;
+
+  GST_DEBUG("prop_id(%d), ipp ctrl cmd(%d)", prop_id, ctrl);
+  ret = ioctl(fd, DRM_IOCTL_EXYNOS_IPP_CMD_CTRL, &cmd_ctrl);
+  if (ret) {
+    GST_ERROR("failed to DRM_IOCTL_EXYNOS_IPP_CMD_CTRL[prop_id:%d][ctrl:%d] : %s",
+                prop_id, ctrl, strerror(errno));
+  }
+
+  return ret;
+}
+
+int
+fimcconvert_drm_create_gem(int drm_fimc_fd, struct drm_exynos_gem_create *gem)
+{
+  int ret = 0;
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+  if (!gem) {
+    GST_ERROR("gem is null..");
+    return -1;
+  }
+  /* NOTE : structure gem should have its size */
+#ifdef USE_BO_TILED
+  if (!gem->gsize.size && gem->gsize.tiled.width && gem->gsize.tiled.height ) {
+    GST_ERROR("gem size is null..");
+    return -1;
+  }
+#else
+  if (!gem->size) {
+    GST_ERROR("gem size is null..");
+    return -1;
+  }
+#endif
+
+#ifdef USE_CACHABLE_GEM
+  gem->flags = EXYNOS_BO_CACHABLE | EXYNOS_BO_CONTIG;
+#else
+  gem->flags = EXYNOS_BO_NONCACHABLE | EXYNOS_BO_CONTIG;
+#endif
+
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_EXYNOS_GEM_CREATE, gem);
+  if (ret < 0) {
+    GST_ERROR("failed to create gem buffer: %s", g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("create drm gem handle(%d)", gem->handle);
+
+  return 0;
+}
+
+int
+fimcconvert_gem_flush_cache(int drm_fimc_fd)
+{
+  int ret = 0;
+  struct drm_exynos_gem_cache_op cache_op;
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+
+  cache_op.flags = 0;
+  cache_op.flags = (EXYNOS_DRM_ALL_CACHES_CORES | EXYNOS_DRM_CACHE_FSH_ALL);
+
+  ret = ioctl (drm_fimc_fd, DRM_IOCTL_EXYNOS_GEM_CACHE_OP, &cache_op);
+  if  (ret < 0) {
+    GST_ERROR("failed to gem cache op: %s", g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("success to gem_flush_cache");
+
+  return 0;
+}
+
+int
+fimcconvert_drm_mmap_gem(int drm_fimc_fd, struct drm_exynos_gem_mmap *mmap)
+{
+  int ret = 0;
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+  if (!mmap) {
+    GST_ERROR("mmap is null..");
+    return -1;
+  }
+  /* NOTE : structure mmap should have its size */
+  if (!mmap->size) {
+    GST_ERROR("mmap size is null..");
+    return -1;
+  }
+
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_EXYNOS_GEM_MMAP, mmap);
+  if (ret < 0) {
+    GST_ERROR("failed to mmap gem: %s", g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("mmapped addr(0x%x)", (void*)(unsigned long)mmap->mapped);
+
+  return 0;
+}
+
+void
+fimcconvert_drm_close_gem(int drm_fimc_fd, unsigned int gem_handle)
+{
+  int ret = 0;
+  struct drm_gem_close close_arg = {0,};
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return;
+  }
+  if (gem_handle == 0) {
+    GST_ERROR("invalid gem_handle(%d)",gem_handle);
+    return;
+  }
+
+  close_arg.handle = gem_handle;
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_GEM_CLOSE, &close_arg);
+  if (ret < 0) {
+    GST_ERROR("failed to DRM_IOCTL_GEM_CLOSE, gem handle(%d) : %s",
+                gem_handle, g_strerror (errno));
+    return;
+  } else {
+    GST_DEBUG("close drm gem handle(%d)", gem_handle);
+  }
+
+  return;
+}
+
+int
+fimcconvert_drm_convert_fd_to_gemhandle(int drm_fimc_fd, int dmabuf_fd, uint32_t *gem_handle)
+{
+  int ret = 0;
+  struct drm_prime_handle prime_arg = {0,};
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+  /* some planes may have fd value 0, but keep going.. */
+  if (dmabuf_fd <= 0) {
+    GST_DEBUG("fd(%d) is not valid", dmabuf_fd); /* temporarily change log level to DEBUG for reducing WARNING level log */
+    return 0;
+  }
+
+  prime_arg.fd = dmabuf_fd;
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_PRIME_FD_TO_HANDLE, &prime_arg);
+  if (ret<0) {
+    GST_ERROR("failed to DRM_IOCTL_PRIME_FD_TO_HANDLE, fd(%d): %s",
+                  dmabuf_fd, g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("converted fd(%d) to gem_handle(%u)", dmabuf_fd, prime_arg.handle);
+
+  *gem_handle = prime_arg.handle;
+
+  return 0;
+}
+
+int
+fimcconvert_drm_convert_gemhandle_to_fd(int drm_fimc_fd, uint32_t gem_handle, int *dmabuf_fd)
+{
+  int ret = 0;
+  struct drm_prime_handle prime;
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+  if (gem_handle <= 0) {
+    GST_WARNING("gem_handle(%u) is not valid", gem_handle);
+    return 0;
+  }
+
+  memset (&prime, 0, sizeof (struct drm_prime_handle));
+  prime.handle = gem_handle;
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &prime);
+  if (ret<0) {
+    GST_ERROR("failed to DRM_IOCTL_PRIME_HANDLE_TO_FD: %s", g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("converted gem_handle(%u) to fd(%d)", gem_handle, prime.fd);
+
+  *dmabuf_fd = prime.fd;
+
+  return 0;
+}
+
+int
+fimcconvert_drm_gem_get_phy_addr(int drm_fimc_fd,  uint32_t gem_handle,
+    uint64_t *phy_addr)
+{
+  int ret = 0;
+  struct drm_exynos_gem_get_phy gem_dst_phy;
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+  if (gem_handle <= 0) {
+    GST_ERROR("gem_handle(%d) is not valid", gem_handle);
+    return -1;
+  }
+
+  /* initialize structure for gem_get_phy */
+  memset(&gem_dst_phy, 0x00, sizeof(struct drm_exynos_gem_get_phy));
+  gem_dst_phy.gem_handle = gem_handle;
+
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_EXYNOS_GEM_GET_PHY, &gem_dst_phy);
+  if (ret < 0) {
+    GST_ERROR("failed to get physical address: %s",g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("gem_handle=%d, phy addr=0x%x", gem_handle,
+             (void*)(unsigned long)gem_dst_phy.phy_addr);
+
+  *phy_addr = gem_dst_phy.phy_addr;
+
+  return 0;
+}
+
+int
+fimcconvert_drm_gem_import_phy_addr(int drm_fimc_fd,
+    struct drm_exynos_gem_phy_imp *gem_phy_imp)
+{
+  int ret = 0;
+
+  if (drm_fimc_fd < 0) {
+    GST_ERROR("DRM is not opened");
+    return -1;
+  }
+  if (!gem_phy_imp) {
+    GST_ERROR("gem_phy_imp is null..");
+    return -1;
+  }
+
+  if (!gem_phy_imp->phy_addr) {
+    GST_ERROR("phy_addr is null.. can not execute DRM_IOCTL_EXYNOS_GEM_PHY_IMP");
+    return -1;
+  }
+#ifdef USE_BO_TILED
+  if (!gem_phy_imp->gsize.tiled.width || !gem_phy_img->gsize.tiled.height) {
+#else
+  if (!gem_phy_imp->size) {
+#endif
+    GST_ERROR("size if null..can not execute DRM_IOCTL_EXYNOS_GEM_PHY_IMP");
+    return -1;
+  }
+
+  ret = ioctl(drm_fimc_fd, DRM_IOCTL_EXYNOS_GEM_PHY_IMP, gem_phy_imp);
+  if (ret < 0) {
+    GST_ERROR("DRM_IOCTL_EXYNOS_GEM_PHY_IMP failed : %s",g_strerror (errno));
+    return -1;
+  }
+
+  GST_DEBUG("gem_handle=%d, phy addr=0x%x", gem_phy_imp->gem_handle,
+              (void*)(unsigned long)gem_phy_imp->phy_addr);
+
+  return 0;
+}
diff --git a/fimcconvert/src/fimc_drm_api.h b/fimcconvert/src/fimc_drm_api.h
new file mode 100755 (executable)
index 0000000..ecb9846
--- /dev/null
@@ -0,0 +1,63 @@
+#ifndef __FIMC_H__
+#define __FIMC_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/time.h>
+#include <sys/mman.h>
+#include <gst/gstinfo.h>
+
+/* headers for drm and gem */
+#include <exynos_drm.h>
+#include <drm_fourcc.h>
+#include <xf86drm.h>
+#include <xf86drmMode.h>
+#include <X11/Xmd.h>
+#include <dri2/dri2.h>
+#include <libdrm/drm.h>
+
+/* tbm */
+#include <tbm_bufmgr.h>
+
+/* ioctl */
+#include <sys/ioctl.h>
+
+GST_DEBUG_CATEGORY_EXTERN(fimcconvert_debug);
+#define GST_CAT_DEFAULT fimcconvert_debug
+//#define USE_CACHABLE_GEM
+
+#if 1
+/* 2 non contiguous plane YCbCr */
+#define fourcc_code(a,b,c,d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | \
+                             ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
+#define DRM_FORMAT_NV12M       fourcc_code('N', 'M', '1', '2') /* 2x2 subsampled Cr:Cb plane */
+#define DRM_FORMAT_NV12MT      fourcc_code('T', 'M', '1', '2') /* 2x2 subsampled Cr:Cb plane 64x32 macroblocks */
+#endif
+
+/* macro for align ***********************************************************/
+#define ALIGN_TO_2B(x)         ((((x)  + (1 <<  1) - 1) >>  1) <<  1)
+#define ALIGN_TO_4B(x)         ((((x)  + (1 <<  2) - 1) >>  2) <<  2)
+#define ALIGN_TO_8B(x)         ((((x)  + (1 <<  3) - 1) >>  3) <<  3)
+#define ALIGN_TO_16B(x)                ((((x)  + (1 <<  4) - 1) >>  4) <<  4)
+#define ALIGN_TO_32B(x)                ((((x)  + (1 <<  5) - 1) >>  5) <<  5)
+#define ALIGN_TO_128B(x)       ((((x)  + (1 <<  7) - 1) >>  7) <<  7)
+#define ALIGN_TO_2KB(x)                ((((x)  + (1 << 11) - 1) >> 11) << 11)
+#define ALIGN_TO_8KB(x)                ((((x)  + (1 << 13) - 1) >> 13) << 13)
+#define ALIGN_TO_64KB(x)       ((((x)  + (1 << 16) - 1) >> 16) << 16)
+
+int exynos_drm_ipp_set_property(int fd, struct drm_exynos_ipp_property *property, struct drm_exynos_sz *src_sz, struct drm_exynos_sz *dst_sz, uint32_t src_format, uint32_t dst_format, enum drm_exynos_ipp_cmd cmd, enum drm_exynos_degree degree, enum drm_exynos_flip flip);
+int exynos_drm_ipp_queue_buf(int fd, enum drm_exynos_ops_id ops_id, enum drm_exynos_ipp_buf_type buf_type, int prop_id, int buf_id, uint32_t gem_handle_y, uint32_t gem_handle_cb, uint32_t gem_handle_cr);
+int exynos_drm_ipp_cmd_ctrl(int fd, int prop_id, enum drm_exynos_ipp_ctrl ctrl);
+int fimcconvert_drm_create_gem(int drm_fimc_fd, struct drm_exynos_gem_create *gem);
+void fimcconvert_drm_close_gem(int drm_fimc_fd, unsigned int gem_handle);
+int fimcconvert_drm_convert_fd_to_gemhandle(int drm_fimc_fd, int dmabuf_fd,  uint32_t *gem_handle);
+int fimcconvert_drm_convert_gemhandle_to_fd(int drm_fimc_fd, uint32_t gem_handle, int *dmabuf_fd);
+int fimcconvert_drm_gem_get_phy_addr(int drm_fimc_fd,  uint32_t gem_handle, uint64_t *phy_addr);
+int fimcconvert_drm_gem_import_phy_addr(int drm_fimc_fd, struct drm_exynos_gem_phy_imp *gem_phy_imp);
+int fimcconvert_drm_mmap_gem(int drm_fimc_fd, struct drm_exynos_gem_mmap *mmap);
+int fimcconvert_gem_flush_cache(int drm_fimc_fd);
+#endif
diff --git a/fimcconvert/src/gstfimcconvert.c b/fimcconvert/src/gstfimcconvert.c
new file mode 100755 (executable)
index 0000000..fdb13fa
--- /dev/null
@@ -0,0 +1,2931 @@
+/*
+ * FimcConvert
+ *
+ * Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd.
+ *
+ * Contact: Sangchul Lee <sc11.lee@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+/*! Revision History:
+ *! ------------------------------------------------------------------------------------
+ *!     DATE    |          AUTHOR          |              COMMENTS
+ *! ------------------------------------------------------------------------------------
+ *! 22-Sep-2010   naveen.ch@samsung.com
+ *! 02-Aug-2012   sc11.lee@samsung.com       expand input/output colorspace formats
+ *! 15-Oct-2012   sc11.lee@samsung.com       apply DRM-IPP interface
+ *! 24-Oct-2012   sc11.lee@samsung.com       support DMA-BUF
+ *! 16-Mar-2013   sc11.lee@samsung.com       support TBM
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "gstfimcconvert.h"
+
+//#define DEBUG_FOR_DV
+#ifdef DEBUG_FOR_DV
+int total_converted_frame_count = 0;
+int total_buffer_unref_count = 0;
+#endif
+
+/* debug variable definition */
+GST_DEBUG_CATEGORY (fimcconvert_debug);
+#define GST_CAT_DEFAULT fimcconvert_debug
+
+enum
+{
+  PROP_0,
+  PROP_ROT_ANG,
+  PROP_DST_WIDTH,
+  PROP_DST_HEIGHT,
+  PROP_FLIP,
+  PROP_SRC_RANDOM_IDX,
+  PROP_DST_BUFFER_NUM,
+};
+
+typedef enum
+{
+  FIMCCONVERT_ROTATE_NONE = 0,
+  FIMCCONVERT_ROTATE_90 = 90,
+  FIMCCONVERT_ROTATE_180 = 180,
+  FIMCCONVERT_ROTATE_270 = 270
+} FIMCConvertRotateType;
+
+typedef enum
+{
+  FIMCCONVERT_FLIP_NONE = 0,
+  FIMCCONVERT_FLIP_VERTICAL,
+  FIMCCONVERT_FLIP_HORIZONTAL
+} FIMCConvertFlipType;
+
+typedef enum
+{
+  FIMCCONVERT_GEM_FOR_SRC = 0,
+  FIMCCONVERT_GEM_FOR_DST = 1,
+} FimcConvertGemCreateType;
+
+typedef enum
+{
+  FIMCCONVERT_IPP_CTRL_STOP = 0,
+  FIMCCONVERT_IPP_CTRL_START = 1,
+} FimcConvertIppCtrl;
+
+static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
+    GST_PAD_SINK,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("video/x-raw, "
+        "framerate = (fraction) [ 0, MAX ], "
+        "width = (int) [ 1, MAX ], "
+        "height = (int) [ 1, MAX ]; "
+        GST_VIDEO_CAPS_MAKE ("ST12") ";"
+        GST_VIDEO_CAPS_MAKE ("SN12") ";"
+        GST_VIDEO_CAPS_MAKE ("NV12") ";"
+        GST_VIDEO_CAPS_MAKE ("S420") ";"
+        GST_VIDEO_CAPS_MAKE ("I420") ";"
+        GST_VIDEO_CAPS_MAKE ("SYVY") ";"
+        GST_VIDEO_CAPS_MAKE ("UYVY") ";"
+        GST_VIDEO_CAPS_MAKE ("SUYV") ";"
+        GST_VIDEO_CAPS_MAKE ("YUYV") ";"
+        GST_VIDEO_CAPS_MAKE ("SUY2") ";"
+        GST_VIDEO_CAPS_MAKE ("YUY2") ";" GST_VIDEO_CAPS_MAKE ("ITLV"))
+    );
+
+static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("BGRx") ";"
+        GST_VIDEO_CAPS_MAKE ("ST12") ";"
+        GST_VIDEO_CAPS_MAKE ("SN12") ";"
+        GST_VIDEO_CAPS_MAKE ("NV12") ";"
+        GST_VIDEO_CAPS_MAKE ("S420") ";"
+        GST_VIDEO_CAPS_MAKE ("I420") ";"
+        GST_VIDEO_CAPS_MAKE ("SYVY") ";"
+        GST_VIDEO_CAPS_MAKE ("UYVY") ";"
+        GST_VIDEO_CAPS_MAKE ("SUYV") ";"
+        GST_VIDEO_CAPS_MAKE ("YUYV") ";"
+        GST_VIDEO_CAPS_MAKE ("SUY2") ";" GST_VIDEO_CAPS_MAKE ("YUY2"))
+    );
+
+static void gst_fimcconvert_base_init (gpointer g_class);
+static void gst_fimcconvert_class_init (GstFimcConvertClass * klass);
+static void gst_fimcconvert_init (GstFimcConvert * fimcconvert);
+static void gst_fimcconvert_finalize (GstFimcConvert * fimcconvert);
+static GstStateChangeReturn gst_fimcconvert_change_state (GstElement * element,
+    GstStateChange transition);
+static GstCaps *gst_fimcconvert_transform_caps (GstBaseTransform * trans,
+    GstPadDirection direction, GstCaps * caps, GstCaps * filter);
+static GstCaps *gst_fimcconvert_fixate_caps (GstBaseTransform * trans,
+    GstPadDirection direction, GstCaps * caps, GstCaps * othercaps);
+static gboolean gst_fimcconvert_set_caps (GstBaseTransform * trans,
+    GstCaps * in, GstCaps * out);
+static gboolean gst_fimcconvert_start (GstBaseTransform * trans);
+static gboolean gst_fimcconvert_stop (GstBaseTransform * trans);
+static gboolean gst_fimcconvert_get_unit_size (GstBaseTransform * trans,
+    GstCaps * caps, guint * size);
+static GstFlowReturn gst_fimcconvert_transform (GstBaseTransform * trans,
+    GstBuffer * in, GstBuffer * out);
+static void gst_fimcconvert_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void gst_fimcconvert_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+static GstFlowReturn gst_fimcconvert_prepare_output_buffer (GstBaseTransform *
+    trans, GstBuffer * input, GstBuffer ** buf);
+static gboolean gst_fimcconvert_priv_init (GstFimcConvert * fimcconvert);
+static void gst_fimcconvert_reset (GstFimcConvert * fimcconvert);
+static gboolean gst_fimcconvert_tbm_create_and_map_bo (GstFimcConvert *
+    fimcconvert, FimcConvertGemCreateType type);
+static void gst_fimcconvert_tbm_unmap_and_destroy_bo (GstFimcConvert *
+    fimcconvert, FimcConvertGemCreateType type, int index);
+static void gst_fimcconvert_buffer_finalize (GstFimcConvertBuffer * buffer);
+static gboolean gst_fimcconvert_drm_ipp_init (GstFimcConvert * fimcconvert);
+static gboolean gst_fimcconvert_drm_ipp_ctrl (GstFimcConvert * fimcconvert,
+    FimcConvertIppCtrl cmd);
+static void gst_fimcconvert_drm_ipp_fini (GstFimcConvert * fimcconvert);
+
+static GstElementClass *parent_class = NULL;
+
+/* for fimc multi instance */
+GMutex *instance_lock = NULL;
+guint instance_lock_count;
+
+#define MAX_IPP_EVENT_BUFFER_SIZE    1024
+#define FIMCCONVERT_TYPE_ROTATE (fimcconvert_rotate_get_type())
+#define FIMCCONVERT_TYPE_FLIP (fimcconvert_flip_get_type())
+
+static GType
+fimcconvert_rotate_get_type (void)
+{
+  static GType fimcconvert_rotate_type = 0;
+  GST_LOG ("[%d : %s] ENTERING", __LINE__, __func__);
+
+  if (!fimcconvert_rotate_type) {
+    static GEnumValue fimcconvert_rotate_types[] = {
+      {FIMCCONVERT_ROTATE_NONE, "0", "No Rotation"},
+      {FIMCCONVERT_ROTATE_90, "90", "Rotate 90 degrees"},
+      {FIMCCONVERT_ROTATE_180, "180", "Rotate 180 degrees"},
+      {FIMCCONVERT_ROTATE_270, "270", "Rotate 270 degrees"},
+      {0, NULL, NULL},
+    };
+    fimcconvert_rotate_type = g_enum_register_static ("FIMCConvertRotateType",
+        fimcconvert_rotate_types);
+  }
+
+  GST_LOG ("[%d : %s] LEAVING", __LINE__, __func__);
+  return fimcconvert_rotate_type;
+}
+
+static GType
+fimcconvert_flip_get_type (void)
+{
+  static GType fimcconvert_flip_type = 0;
+  GST_LOG ("[%d : %s] ENTERING", __LINE__, __func__);
+
+  if (!fimcconvert_flip_type) {
+    static GEnumValue fimcconvert_flip_types[] = {
+      {FIMCCONVERT_FLIP_NONE, "NONE", "No Flip"},
+      {FIMCCONVERT_FLIP_VERTICAL, "VERTICAL", "Vertical Flip"},
+      {FIMCCONVERT_FLIP_HORIZONTAL, "HORIZONTAL", "Horizontal Flip"},
+      {0, NULL, NULL},
+    };
+    fimcconvert_flip_type = g_enum_register_static ("FIMCConvertFlipType",
+        fimcconvert_flip_types);
+  }
+
+  GST_LOG ("[%d : %s] LEAVING", __LINE__, __func__);
+  return fimcconvert_flip_type;
+}
+
+GType
+gst_fimcconvert_get_type (void)
+{
+  static GType fimcconvert_type = 0;
+
+  if (!fimcconvert_type) {
+    static const GTypeInfo fimcconvert_info = {
+      sizeof (GstFimcConvertClass),
+      gst_fimcconvert_base_init,
+      NULL,
+      (GClassInitFunc) gst_fimcconvert_class_init,
+      NULL,
+      NULL,
+      sizeof (GstFimcConvert),
+      0,
+      (GInstanceInitFunc) gst_fimcconvert_init,
+    };
+
+    fimcconvert_type = g_type_register_static (GST_TYPE_BASE_TRANSFORM,
+        "GstFimcConvert", &fimcconvert_info, 0);
+  }
+  return fimcconvert_type;
+}
+
+static GstFimcConvertBuffer *
+gst_fimcconvert_buffer_new (GstFimcConvert * fimcconvert, guint buf_size)
+{
+  GstFimcConvertBuffer *buffer = NULL;
+
+  buffer = (GstFimcConvertBuffer *) malloc (sizeof (*buffer));
+
+  GST_LOG_OBJECT (fimcconvert, "creating fimcconvert buffer(%p)", buffer);
+
+  buffer->actual_size = buf_size;
+  buffer->buffer = gst_buffer_new ();
+  buffer->fimcconvert = gst_object_ref (GST_OBJECT (fimcconvert));
+
+  return buffer;
+}
+
+static void
+gst_fimcconvert_buffer_finalize (GstFimcConvertBuffer * buffer)
+{
+  GstFimcConvert *fimcconvert = NULL;
+
+  fimcconvert = buffer->fimcconvert;
+
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+
+#ifdef DEBUG_FOR_DV
+  if (total_converted_frame_count > 0) {
+    if (++total_buffer_unref_count <= 10) {
+      GST_WARNING_OBJECT (fimcconvert,
+          "%2dth of buffer(%p) unrefering", total_buffer_unref_count, buffer);
+    }
+  }
+#endif
+
+  g_mutex_lock (fimcconvert->buf_idx_lock);
+  if (fimcconvert->dst_buf_num > 0) {
+    fimcconvert->dst_buf_num--;
+    GST_LOG_OBJECT (fimcconvert,
+        "unrefering a buffer(%p), now number of pending buffers(%d)",
+        buffer, fimcconvert->dst_buf_num);
+  } else {
+    if (fimcconvert->is_drm_inited) {
+      GST_WARNING_OBJECT (fimcconvert,
+          "something wrong..trying to unrefer a buffer(%p)", buffer);
+    }
+  }
+
+  gst_object_unref (fimcconvert);
+  free (buffer);
+
+  g_mutex_unlock (fimcconvert->buf_idx_lock);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+}
+
+static gboolean
+gst_fimcconvert_is_buffer_available (GstFimcConvert * fimcconvert)
+{
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  g_mutex_lock (fimcconvert->buf_idx_lock);
+  if (fimcconvert->dst_buf_num < fimcconvert->num_of_dst_buffers) {
+    fimcconvert->dst_buf_num++;
+  } else {
+    int timeout_count = 50;
+    g_mutex_unlock (fimcconvert->buf_idx_lock);
+    /* waiting for unref buffer */
+    while (fimcconvert->dst_buf_num == fimcconvert->num_of_dst_buffers) {
+      if (timeout_count == 0) {
+        GST_ERROR_OBJECT (fimcconvert, "timeout..");
+        return FALSE;
+      }
+      GST_WARNING_OBJECT (fimcconvert,
+          "wait until downstream plugin unrefers a buffer");
+      g_usleep (G_USEC_PER_SEC / 10);
+      timeout_count--;
+    }
+    g_mutex_lock (fimcconvert->buf_idx_lock);
+    fimcconvert->dst_buf_num++;
+  }
+  GST_LOG_OBJECT (fimcconvert,
+      "Number of dst buffers(%d), refered number of buffers(%d)",
+      fimcconvert->num_of_dst_buffers, fimcconvert->dst_buf_num);
+  g_mutex_unlock (fimcconvert->buf_idx_lock);
+
+  return TRUE;
+}
+
+static gboolean
+gst_fimcconvert_drm_ipp_init (GstFimcConvert * fimcconvert)
+{
+  Display *dpy = NULL;
+  int i = 0;
+  int j = 0;
+  int ret = 0;
+  int eventBase = 0;
+  int errorBase = 0;
+  int dri2Major = 0;
+  int dri2Minor = 0;
+  char *driverName = NULL;
+  char *deviceName = NULL;
+  struct drm_auth auth_arg = { 0 };
+  struct drm_exynos_ipp_property property;
+  struct drm_exynos_sz src_sz;
+  struct drm_exynos_sz dst_sz;
+  enum drm_exynos_degree dst_degree = EXYNOS_DRM_DEGREE_0;
+  enum drm_exynos_flip dst_flip = EXYNOS_DRM_FLIP_NONE;
+
+  if (fimcconvert->drm_fimc_fd != -1) {
+    /* maybe skipping convert case */
+    GST_WARNING_OBJECT (fimcconvert,
+        "already initialized drm_fd (%d)", fimcconvert->drm_fimc_fd);
+    return TRUE;
+  }
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  if (fimcconvert->drm_tbm_fd != -1) {
+    fimcconvert->drm_fimc_fd = fimcconvert->drm_tbm_fd;
+    GST_WARNING_OBJECT (fimcconvert, "use drm fd(%d) for IPP",
+        fimcconvert->drm_fimc_fd);
+  } else {
+
+    dpy = XOpenDisplay (0);
+    if (!dpy) {
+      GST_ERROR_OBJECT (fimcconvert, "failed to XOpenDisplay()");
+      goto ERROR_CASE;
+    }
+
+    /* DRI2 */
+    if (!DRI2QueryExtension (dpy, &eventBase, &errorBase)) {
+      GST_ERROR_OBJECT (fimcconvert, "failed to DRI2QueryExtension()");
+      goto ERROR_CASE;
+    }
+
+    if (!DRI2QueryVersion (dpy, &dri2Major, &dri2Minor)) {
+      GST_ERROR_OBJECT (fimcconvert, "failed to DRI2QueryVersion");
+      goto ERROR_CASE;
+    }
+
+    if (!DRI2Connect (dpy, RootWindow (dpy, DefaultScreen (dpy)), &driverName,
+            &deviceName)) {
+      GST_ERROR_OBJECT (fimcconvert, "failed to DRI2Connect");
+      goto ERROR_CASE;
+    }
+
+    /* get the drm_fd though opening the deviceName */
+    fimcconvert->drm_fimc_fd = open (deviceName, O_RDWR);
+    if (fimcconvert->drm_fimc_fd < 0) {
+      GST_ERROR_OBJECT (fimcconvert, "cannot open drm device (%s)", deviceName);
+      goto ERROR_CASE;
+    }
+    GST_INFO ("Open drm device : %s, fd(%d)", deviceName,
+        fimcconvert->drm_fimc_fd);
+
+    /* get magic from drm to authentication */
+    if (ioctl (fimcconvert->drm_fimc_fd, DRM_IOCTL_GET_MAGIC, &auth_arg)) {
+      GST_ERROR_OBJECT (fimcconvert, "cannot get drm auth magic");
+      close (fimcconvert->drm_fimc_fd);
+      fimcconvert->drm_fimc_fd = -1;
+      goto ERROR_CASE;
+    }
+
+    if (!DRI2Authenticate (dpy, RootWindow (dpy, DefaultScreen (dpy)),
+            auth_arg.magic)) {
+      GST_ERROR_OBJECT (fimcconvert, "cannot get drm authentication from X");
+      close (fimcconvert->drm_fimc_fd);
+      fimcconvert->drm_fimc_fd = -1;
+      goto ERROR_CASE;
+    }
+
+    fimcconvert->drm_tbm_fd = fimcconvert->drm_fimc_fd;
+  }
+
+  fimcconvert->tbm = tbm_bufmgr_init (fimcconvert->drm_tbm_fd);
+  if (!fimcconvert->tbm) {
+    GST_ERROR_OBJECT (fimcconvert,
+        "failed to initialize tizen buffer manager ");
+    goto ERROR_CASE;
+  } else {
+    GST_INFO_OBJECT (fimcconvert,
+        "tbm bufmgr(%x) initialized : using drm fd(%d)",
+        fimcconvert->tbm, fimcconvert->drm_tbm_fd);
+  }
+
+  for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+    for (j = 0; j < MM_VIDEO_BUFFER_MAX_PLANE; j++) {
+      memset (&fimcconvert->gem_info_src[i][j], 0x0, sizeof (GemInfoSrc));
+    }
+  }
+  for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+    memset (&fimcconvert->gem_info_src_normal_fmt[i], 0x0, sizeof (GemInfoDst));
+  }
+  for (i = 0; i < MAX_DST_BUF_NUM; i++) {
+    for (j = 0; j < MM_VIDEO_BUFFER_MAX_PLANE; j++) {
+      memset (&fimcconvert->gem_info_dst[i][j], 0x0, sizeof (GemInfoDst));
+    }
+  }
+  fimcconvert->ipp_prop_id = 0;
+
+  /* Update src/dst size */
+  src_sz.hsize = fimcconvert->in_caps_width;
+  src_sz.vsize = fimcconvert->in_caps_height;
+  dst_sz.hsize = fimcconvert->dst_caps_width;
+  dst_sz.vsize = fimcconvert->dst_caps_height;
+
+  /* Update rotation information */
+  switch (fimcconvert->rotate_ang) {
+    case 90:
+      dst_degree = EXYNOS_DRM_DEGREE_90;
+      break;
+    case 270:
+      dst_degree = EXYNOS_DRM_DEGREE_270;
+      break;
+    case 0:
+      dst_degree = EXYNOS_DRM_DEGREE_0;
+      break;
+    case 180:
+      dst_degree = EXYNOS_DRM_DEGREE_180;
+      break;
+    default:
+      break;
+  }
+  GST_INFO_OBJECT (fimcconvert, "set rotate angle to %d", dst_degree);
+
+  /* Update flip information */
+  switch (fimcconvert->dst_flip) {
+    case 0:
+      dst_flip = EXYNOS_DRM_FLIP_NONE;
+      break;
+    case 1:
+      dst_flip = EXYNOS_DRM_FLIP_VERTICAL;
+      break;
+    case 2:
+      dst_flip = EXYNOS_DRM_FLIP_HORIZONTAL;
+      break;
+    default:
+      break;
+  }
+  GST_INFO_OBJECT (fimcconvert, "set flip to %d", dst_flip);
+
+  /* Set DRM property, IPP_CMD_M2M */
+  ret = exynos_drm_ipp_set_property (fimcconvert->drm_fimc_fd,
+      &property,
+      &src_sz,
+      &dst_sz,
+      fimcconvert->src_drm_format,
+      fimcconvert->dst_drm_format, IPP_CMD_M2M, dst_degree, dst_flip);
+  if (ret) {
+    GST_ERROR_OBJECT (fimcconvert, "failed to set ipp property");
+    gst_fimcconvert_drm_ipp_fini (fimcconvert);
+    goto ERROR_CASE;
+  } else {
+    fimcconvert->ipp_prop_id = property.prop_id;
+    GST_INFO_OBJECT (fimcconvert,
+        "set IPP_CMD_M2M, ipp_prop_id(%d)", fimcconvert->ipp_prop_id);
+  }
+#if 0
+  /* Start */
+  if (!gst_fimcconvert_drm_ipp_ctrl (fimcconvert, FIMCCONVERT_IPP_CTRL_START)) {
+    GST_ERROR_OBJECT (fimcconvert,
+        "failed to gst_fimcconvert_drm_ipp_ctrl(START)");
+  }
+#endif
+  fimcconvert->is_drm_inited = FALSE;
+
+  if (dpy) {
+    XCloseDisplay (dpy);
+  }
+  if (driverName) {
+    free (driverName);
+  }
+  if (deviceName) {
+    free (deviceName);
+  }
+
+  return TRUE;
+
+ERROR_CASE:
+  if (dpy) {
+    XCloseDisplay (dpy);
+  }
+  if (driverName) {
+    free (driverName);
+  }
+  if (deviceName) {
+    free (deviceName);
+  }
+
+  return FALSE;
+}
+
+static gboolean
+gst_fimcconvert_drm_ipp_ctrl (GstFimcConvert * fimcconvert,
+    FimcConvertIppCtrl cmd)
+{
+  int ret = 0;
+  enum drm_exynos_ipp_ctrl ctrl_cmd;
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  if (fimcconvert->drm_fimc_fd < 0) {
+    GST_ERROR_OBJECT (fimcconvert,
+        "already closed drm_fimc_fd(%d)", fimcconvert->drm_fimc_fd);
+    return FALSE;
+  }
+  if (fimcconvert->ipp_prop_id == 0) {
+    GST_ERROR_OBJECT (fimcconvert, "ipp_prop_id is 0..");
+    return FALSE;
+  }
+
+  switch (cmd) {
+    case FIMCCONVERT_IPP_CTRL_STOP:
+      ctrl_cmd = IPP_CTRL_STOP;
+      break;
+    case FIMCCONVERT_IPP_CTRL_START:
+      ctrl_cmd = IPP_CTRL_PLAY;
+      break;
+    default:
+      GST_ERROR_OBJECT (fimcconvert, "cmd is not valid(%d)", cmd);
+      return FALSE;
+  }
+
+  ret = exynos_drm_ipp_cmd_ctrl (fimcconvert->drm_fimc_fd,
+      fimcconvert->ipp_prop_id, ctrl_cmd);
+  if (ret) {
+    GST_ERROR_OBJECT (fimcconvert, "failed to stop ipp ctrl IPP_CMD_M2M");
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+static void
+gst_fimcconvert_drm_ipp_fini (GstFimcConvert * fimcconvert)
+{
+  int i = 0;
+  int ret = 0;
+
+  g_return_if_fail (GST_IS_FIMCCONVERT (fimcconvert));
+
+  if (fimcconvert->drm_fimc_fd < 0) {
+    GST_WARNING_OBJECT (fimcconvert,
+        "already closed drm_fimc_fd(%d)", fimcconvert->drm_fimc_fd);
+    return;
+
+  } else if (fimcconvert->drm_fimc_fd >= 0) {
+    if (fimcconvert->is_drm_inited) {
+      /* For source buffer dequeue to IPP */
+      for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+        if (fimcconvert->gem_info_src[i][Y].gem_handle) {
+          ret = exynos_drm_ipp_queue_buf (fimcconvert->drm_fimc_fd,
+              EXYNOS_DRM_OPS_SRC,
+              IPP_BUF_DEQUEUE,
+              fimcconvert->ipp_prop_id,
+              i,
+              fimcconvert->gem_info_src[i][Y].gem_handle,
+              fimcconvert->gem_info_src[i][CB].gem_handle,
+              fimcconvert->gem_info_src[i][CR].gem_handle);
+          if (ret < 0) {
+            GST_ERROR_OBJECT (fimcconvert,
+                "src buffer map to IPP failed, src_buf_idx(%d)", i);
+          }
+        }
+      }
+      /* For destination buffer dequeue to IPP */
+      for (i = 0; i < fimcconvert->num_of_dst_buffers; i++) {
+        if (fimcconvert->gem_info_dst[i][Y].gem_handle) {
+          ret = exynos_drm_ipp_queue_buf (fimcconvert->drm_fimc_fd,
+              EXYNOS_DRM_OPS_DST,
+              IPP_BUF_DEQUEUE,
+              fimcconvert->ipp_prop_id,
+              i,
+              fimcconvert->gem_info_dst[i][Y].gem_handle,
+              fimcconvert->gem_info_dst[i][CB].gem_handle,
+              fimcconvert->gem_info_dst[i][CR].gem_handle);
+          if (ret < 0) {
+            GST_ERROR_OBJECT (fimcconvert,
+                "dst buffer map to IPP failed, dst_buf_idx(%d)", i);
+          }
+        }
+      }
+      /* Set IPP to stop */
+      if (!gst_fimcconvert_drm_ipp_ctrl (fimcconvert,
+              FIMCCONVERT_IPP_CTRL_STOP)) {
+        GST_ERROR_OBJECT (fimcconvert,
+            "failed to gst_fimcconvert_drm_ipp_ctrl(STOP)");
+      }
+      /* Memory unmap & close gem */
+      /* dst buffer */
+      for (i = 0; i < fimcconvert->num_of_dst_buffers; i++) {
+        gst_fimcconvert_tbm_unmap_and_destroy_bo (fimcconvert,
+            FIMCCONVERT_GEM_FOR_DST, i);
+      }
+      /* src buffer */
+      for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+        gst_fimcconvert_tbm_unmap_and_destroy_bo (fimcconvert,
+            FIMCCONVERT_GEM_FOR_SRC, i);
+      }
+    }
+
+    /* Deinitialize TBM */
+    if (fimcconvert->tbm) {
+      tbm_bufmgr_deinit (fimcconvert->tbm);
+    }
+
+    /* Close DRM */
+    if (fimcconvert->drm_tbm_fd != fimcconvert->drm_fimc_fd) {
+      GST_INFO_OBJECT (fimcconvert, "close drm_fimc_fd(%d)",
+          fimcconvert->drm_fimc_fd);
+      close (fimcconvert->drm_fimc_fd);
+    }
+
+    fimcconvert->drm_fimc_fd = -1;
+    fimcconvert->ipp_prop_id = 0;
+    fimcconvert->tbm = 0;
+    fimcconvert->drm_tbm_fd = -1;
+    fimcconvert->is_drm_inited = FALSE;
+
+    return;
+  }
+}
+
+static void
+gst_fimcconvert_base_init (gpointer g_class)
+{
+}
+
+static void
+gst_fimcconvert_class_init (GstFimcConvertClass * klass)
+{
+  GST_INFO ("");
+  GObjectClass *gobject_class;
+  GstBaseTransformClass *trans_class;
+  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
+
+  gobject_class = (GObjectClass *) klass;
+  trans_class = (GstBaseTransformClass *) klass;
+
+  gobject_class->finalize = (GObjectFinalizeFunc) gst_fimcconvert_finalize;
+  gobject_class->set_property = gst_fimcconvert_set_property;
+  gobject_class->get_property = gst_fimcconvert_get_property;
+
+  gstelement_class->change_state =
+      GST_DEBUG_FUNCPTR (gst_fimcconvert_change_state);
+  gst_element_class_set_static_metadata (gstelement_class,
+      "Video Scale, Rotate, Colorspace Convert Plug-in based on FIMC",
+      "Filter/Effect/Video",
+      "Video scale, rotate and colorspace convert using FIMC",
+      "Samsung Electronics Co");
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&src_template));
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&sink_template));
+  trans_class->transform_caps =
+      GST_DEBUG_FUNCPTR (gst_fimcconvert_transform_caps);
+  trans_class->fixate_caps = GST_DEBUG_FUNCPTR (gst_fimcconvert_fixate_caps);
+  trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_fimcconvert_set_caps);
+  trans_class->start = GST_DEBUG_FUNCPTR (gst_fimcconvert_start);
+  trans_class->stop = GST_DEBUG_FUNCPTR (gst_fimcconvert_stop);
+  trans_class->get_unit_size =
+      GST_DEBUG_FUNCPTR (gst_fimcconvert_get_unit_size);
+
+  trans_class->transform = GST_DEBUG_FUNCPTR (gst_fimcconvert_transform);
+  trans_class->prepare_output_buffer =
+      GST_DEBUG_FUNCPTR (gst_fimcconvert_prepare_output_buffer);
+
+  trans_class->passthrough_on_same_caps = TRUE;
+
+  parent_class = g_type_class_peek_parent (klass);
+
+  GST_DEBUG_CATEGORY_INIT (fimcconvert_debug, "fimcconvert", 0,
+      "fimcconvert element");
+
+  g_object_class_install_property (gobject_class, PROP_ROT_ANG,
+      g_param_spec_enum ("rotate", "Rotate", "Rotate can be 0, 90, 180 or 270",
+          FIMCCONVERT_TYPE_ROTATE, FIMCCONVERT_ROTATE_NONE, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_DST_WIDTH,
+      g_param_spec_int ("dst-width", "Output video width",
+          "Output video width. If setting 0, output video width will be media src's width",
+          FIMCCONVERT_DST_WIDTH_MIN, FIMCCONVERT_DST_WIDTH_MAX,
+          FIMCCONVERT_DST_WIDTH_DEFAULT, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_DST_HEIGHT,
+      g_param_spec_int ("dst-height", "Output video height",
+          "Output video height. If setting 0, output video height will be media src's height",
+          FIMCCONVERT_DST_HEIGHT_MIN, FIMCCONVERT_DST_HEIGHT_MAX,
+          FIMCCONVERT_DST_HEIGHT_DEFAULT, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_FLIP,
+      g_param_spec_enum ("flip", "Flip", "Flip can be 0, 1, 2",
+          FIMCCONVERT_TYPE_FLIP, FIMCCONVERT_FLIP_NONE, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_SRC_RANDOM_IDX,
+      g_param_spec_boolean ("src-rand-idx", "Random src buffer index",
+          "Random src buffer index. If setting TRUE, fimcconvert does not manage index of src buffer from upstream src-plugin",
+          TRUE, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_DST_BUFFER_NUM,
+      g_param_spec_int ("dst-buffer-num", "Number of dst buffers",
+          "Number of destination buffers",
+          FIMCCONVERT_DST_BUFFER_MIN, FIMCCONVERT_DST_BUFFER_MAX,
+          FIMCCONVERT_DST_BUFFER_DEFAULT, G_PARAM_READWRITE));
+}
+
+static void
+gst_fimcconvert_init (GstFimcConvert * fimcconvert)
+{
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+  gst_base_transform_set_qos_enabled (GST_BASE_TRANSFORM (fimcconvert), TRUE);
+
+  /* pad setting */
+  fimcconvert->src_pad = GST_BASE_TRANSFORM_SRC_PAD (fimcconvert);
+
+  /* private values init */
+  gst_fimcconvert_priv_init (fimcconvert);
+
+  /* property values init */
+  fimcconvert->is_random_src_idx = TRUE;
+  fimcconvert->num_of_dst_buffers = FIMCCONVERT_DST_BUFFER_DEFAULT;
+  fimcconvert->rotate_ang = FIMCCONVERT_ROTATE_NONE;
+  fimcconvert->dst_flip = FIMCCONVERT_FLIP_NONE;
+
+  if (!instance_lock) {
+    instance_lock = g_mutex_new ();
+  }
+  g_mutex_lock (instance_lock);
+  instance_lock_count++;
+  g_mutex_unlock (instance_lock);
+
+  fimcconvert->fd_lock = g_mutex_new ();
+  if (!fimcconvert->fd_lock) {
+    GST_ERROR ("Failed to created mutex...");
+  }
+  fimcconvert->buf_idx_lock = g_mutex_new ();
+  if (!fimcconvert->buf_idx_lock) {
+    GST_ERROR ("Failed to created mutex...");
+  }
+#ifdef DEBUG_FOR_DV
+  GST_WARNING_OBJECT (fimcconvert, "[END]");
+#else
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+#endif
+}
+
+static gboolean
+gst_fimcconvert_priv_init (GstFimcConvert * fimcconvert)
+{
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  fimcconvert->drm_fimc_fd = -1;
+  fimcconvert->drm_tbm_fd = -1;
+
+  fimcconvert->src_buf_idx = 0;
+  fimcconvert->dst_buf_idx = 0;
+
+  fimcconvert->is_first_set_for_src = TRUE;
+  fimcconvert->is_first_set_for_dst = TRUE;
+
+  fimcconvert->buf_type = 0;
+
+  fimcconvert->is_src_format_std = FALSE;
+  fimcconvert->is_same_caps = FALSE;
+  fimcconvert->do_skip = FALSE;
+
+  fimcconvert->jpeg_data = NULL;
+  fimcconvert->jpeg_data_size = 0;
+
+  return TRUE;
+}
+
+static void
+gst_fimcconvert_finalize (GstFimcConvert * fimcconvert)
+{
+  g_return_if_fail (GST_IS_FIMCCONVERT (fimcconvert));
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+
+  if (fimcconvert->is_drm_inited) {
+    gst_fimcconvert_reset (fimcconvert);
+  }
+
+  if (fimcconvert->fd_lock) {
+    g_mutex_free (fimcconvert->fd_lock);
+    fimcconvert->fd_lock = NULL;
+  }
+  if (fimcconvert->buf_idx_lock) {
+    g_mutex_free (fimcconvert->buf_idx_lock);
+    fimcconvert->buf_idx_lock = NULL;
+  }
+
+  g_mutex_lock (instance_lock);
+  instance_lock_count--;
+  g_mutex_unlock (instance_lock);
+  if (instance_lock_count == 0) {
+    g_mutex_free (instance_lock);
+    instance_lock = NULL;
+  }
+#ifdef DEBUG_FOR_DV
+  GST_WARNING_OBJECT (fimcconvert,
+      "[END] total number of converted frames : %d",
+      total_converted_frame_count);
+  GST_WARNING_OBJECT (fimcconvert,
+      "[END] total number of unrefered buffers : %d", total_buffer_unref_count);
+  total_converted_frame_count = 0;
+  total_buffer_unref_count = 0;
+#else
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+#endif
+
+  G_OBJECT_CLASS (parent_class)->finalize (G_OBJECT (fimcconvert));
+
+}
+
+static void
+gst_fimcconvert_reset (GstFimcConvert * fimcconvert)
+{
+  g_return_if_fail (GST_IS_FIMCCONVERT (fimcconvert));
+
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+
+  g_mutex_lock (fimcconvert->fd_lock);
+  g_mutex_lock (instance_lock);
+
+  if (fimcconvert->drm_fimc_fd >= 0) {
+    FIMCCONVERT_SEND_CUSTOM_EVENT_TO_SINK_WITH_DATA (0);
+    gst_fimcconvert_drm_ipp_fini (fimcconvert);
+    gst_fimcconvert_priv_init (fimcconvert);
+  }
+  g_mutex_unlock (instance_lock);
+  g_mutex_unlock (fimcconvert->fd_lock);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+
+  return;
+}
+
+static GstStateChangeReturn
+gst_fimcconvert_change_state (GstElement * element, GstStateChange transition)
+{
+  GstFimcConvert *fimcconvert = NULL;
+  GstStateChangeReturn stateret = GST_STATE_CHANGE_SUCCESS;
+
+  fimcconvert = GST_FIMCCONVERT (element);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_NULL_TO_READY:
+      GST_INFO_OBJECT (fimcconvert, "GST_STATE_CHANGE_NULL_TO_READY");
+      break;
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      GST_INFO_OBJECT (fimcconvert, "GST_STATE_CHANGE_READY_TO_PAUSED");
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      GST_INFO_OBJECT (fimcconvert, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
+      break;
+    default:
+      break;
+  }
+  stateret = parent_class->change_state (element, transition);
+  if (stateret != GST_STATE_CHANGE_SUCCESS) {
+    GST_ERROR_OBJECT (fimcconvert, "chane state error in parent class");
+    return GST_STATE_CHANGE_FAILURE;
+  }
+
+  switch (transition) {
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+      GST_INFO_OBJECT (fimcconvert, "GST_STATE_CHANGE_PLAYING_TO_PAUSED");
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      GST_INFO_OBJECT (fimcconvert, "GST_STATE_CHANGE_PAUSED_TO_READY");
+      break;
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      GST_INFO_OBJECT (fimcconvert, "GST_STATE_CHANGE_READY_TO_NULL");
+      gst_fimcconvert_reset (fimcconvert);
+      break;
+    default:
+      break;
+  }
+
+  return stateret;
+}
+
+static void
+gst_fimcconvert_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  GstFimcConvert *fimcconvert = GST_FIMCCONVERT (object);
+  guint rotate_ang;
+  gint width;
+  gint height;
+  gint flip;
+  gboolean is_rand_src_idx;
+  guint dst_buffer_num;
+
+  switch (prop_id) {
+    case PROP_ROT_ANG:
+      rotate_ang = g_value_get_enum (value);
+      if (rotate_ang != fimcconvert->rotate_ang) {
+        fimcconvert->rotate_ang = rotate_ang;
+        GST_INFO_OBJECT (fimcconvert, "Rotate angle value = %d", rotate_ang);
+        gst_fimcconvert_reset (fimcconvert);
+      }
+      break;
+
+    case PROP_DST_WIDTH:
+      width = g_value_get_int (value);
+      if (width != fimcconvert->dst_width) {
+        if (!width) {
+          fimcconvert->dst_width = fimcconvert->in_caps_width;
+        } else {
+          fimcconvert->dst_width = width;
+        }
+        GST_INFO_OBJECT (fimcconvert,
+            "Going to set output width = %d", fimcconvert->dst_width);
+        fimcconvert->dst_caps_width = fimcconvert->dst_width;
+        gst_fimcconvert_reset (fimcconvert);
+      } else {
+        GST_WARNING_OBJECT (fimcconvert,
+            "skip set width.. width(%d),fimcconvert->dst_width(%d)",
+            width, fimcconvert->dst_width);
+      }
+      break;
+
+    case PROP_DST_HEIGHT:
+      height = g_value_get_int (value);
+      if (height != fimcconvert->dst_height) {
+        if (!height) {
+          fimcconvert->dst_height = fimcconvert->in_caps_height;
+        } else {
+          fimcconvert->dst_height = height;
+        }
+        GST_INFO_OBJECT (fimcconvert,
+            "Going to set output height = %d", fimcconvert->dst_height);
+        fimcconvert->dst_caps_height = fimcconvert->dst_height;
+        gst_fimcconvert_reset (fimcconvert);
+      } else {
+        GST_WARNING_OBJECT (fimcconvert,
+            "skip set height.. height(%d),fimcconvert->dst_height(%d)",
+            height, fimcconvert->dst_height);
+      }
+      break;
+
+    case PROP_FLIP:
+      flip = g_value_get_enum (value);
+      if (flip != fimcconvert->dst_flip) {
+        fimcconvert->dst_flip = flip;
+        GST_INFO_OBJECT (fimcconvert, "Going to set flip = %d",
+            fimcconvert->dst_flip);
+        gst_fimcconvert_reset (fimcconvert);
+      }
+      break;
+
+    case PROP_SRC_RANDOM_IDX:
+      is_rand_src_idx = g_value_get_boolean (value);
+      if (fimcconvert->is_random_src_idx != is_rand_src_idx) {
+        fimcconvert->is_random_src_idx = is_rand_src_idx;
+        GST_INFO_OBJECT (fimcconvert,
+            "src index ordering from upstream src plugin is random? %d",
+            fimcconvert->is_random_src_idx);
+        gst_fimcconvert_reset (fimcconvert);
+      }
+      break;
+
+    case PROP_DST_BUFFER_NUM:
+      dst_buffer_num = (guint) g_value_get_int (value);
+      if (fimcconvert->num_of_dst_buffers != dst_buffer_num) {
+        fimcconvert->num_of_dst_buffers = dst_buffer_num;
+        GST_INFO_OBJECT (fimcconvert, "Number of dst buffers = %d",
+            dst_buffer_num);
+        gst_fimcconvert_reset (fimcconvert);
+      }
+      break;
+
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_fimcconvert_get_property (GObject * object, guint prop_id, GValue * value,
+    GParamSpec * pspec)
+{
+  GstFimcConvert *fimcconvert = GST_FIMCCONVERT (object);
+
+  switch (prop_id) {
+    case PROP_ROT_ANG:
+      g_value_set_enum (value, fimcconvert->rotate_ang);
+      break;
+    case PROP_DST_WIDTH:
+      g_value_set_int (value, fimcconvert->dst_width);
+      break;
+    case PROP_DST_HEIGHT:
+      g_value_set_int (value, fimcconvert->dst_height);
+      break;
+    case PROP_FLIP:
+      g_value_set_enum (value, fimcconvert->dst_flip);
+      break;
+    case PROP_SRC_RANDOM_IDX:
+      g_value_set_boolean (value, fimcconvert->is_random_src_idx);
+      break;
+    case PROP_DST_BUFFER_NUM:
+      g_value_set_int (value, (int) fimcconvert->num_of_dst_buffers);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static gboolean
+gst_fimcconvert_start (GstBaseTransform * trans)
+{
+  /* Not doing anything here */
+  return TRUE;
+}
+
+static gboolean
+gst_fimcconvert_stop (GstBaseTransform * trans)
+{
+  /* Not doing anything here */
+  return TRUE;
+}
+
+static gboolean
+gst_fimcconvert_set_mm_video_buf_info_for_dst (GstFimcConvert * fimcconvert,
+    GstBuffer * buf)
+{
+  MMVideoBuffer *mm_video_buf = NULL;
+  guint idx = 0;
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+  g_return_val_if_fail (buf, FALSE);
+
+  idx = fimcconvert->dst_buf_idx;
+
+  g_return_val_if_fail (fimcconvert->gem_info_dst[idx][Y].gem_handle, FALSE);
+  g_return_val_if_fail (fimcconvert->gem_info_dst[idx][Y].usr_addr, FALSE);
+
+  mm_video_buf = (MMVideoBuffer *) malloc (sizeof (MMVideoBuffer));
+  if (mm_video_buf == NULL) {
+    GST_ERROR_OBJECT (fimcconvert, "MMVideoBuffer memory allocation failed");
+    return FALSE;
+  }
+  memset (mm_video_buf, 0x0, sizeof (MMVideoBuffer));
+
+  GST_INFO_OBJECT (fimcconvert, "OutBuf :: buf_type (%d)",
+      fimcconvert->buf_type);
+
+  if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS) {
+
+    if (!fimcconvert->gem_info_dst[idx][Y].phy_addr) {
+      free (mm_video_buf);
+      GST_ERROR_OBJECT (fimcconvert, "OutBuf :: phy_addr is null");
+      return FALSE;
+    }
+
+    mm_video_buf->handle.paddr[Y] =
+        (void *) (unsigned long) fimcconvert->gem_info_dst[idx][Y].phy_addr;
+    mm_video_buf->data[Y] =
+        (void *) (unsigned long) fimcconvert->gem_info_dst[idx][Y].usr_addr;
+    mm_video_buf->width[Y] = fimcconvert->dst_caps_width;
+    mm_video_buf->height[Y] = fimcconvert->dst_caps_height;
+    mm_video_buf->stride_width[Y] = mm_video_buf->width[Y];
+    mm_video_buf->stride_height[Y] = mm_video_buf->height[Y];
+    mm_video_buf->type = MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS;
+
+    if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'T', '1', '2')
+        || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1',
+            '2')) {
+      if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1',
+              '2')) {
+        GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SN12");
+        mm_video_buf->format = MM_PIXEL_FORMAT_NV12;
+      } else {
+        GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's ST12");
+        mm_video_buf->format = MM_PIXEL_FORMAT_NV12T;
+      }
+      mm_video_buf->handle.paddr[CB] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CB].phy_addr;
+      mm_video_buf->data[CB] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CB].usr_addr;
+      mm_video_buf->width[CB] = fimcconvert->dst_caps_width;
+      mm_video_buf->height[CB] = fimcconvert->dst_caps_height >> 1;
+      mm_video_buf->stride_width[CB] = mm_video_buf->width[CB];
+      mm_video_buf->stride_height[CB] = mm_video_buf->height[CB];
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4', '2',
+            '0')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's S420");
+      mm_video_buf->format = MM_PIXEL_FORMAT_I420;
+      mm_video_buf->handle.paddr[CB] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CB].phy_addr;
+      mm_video_buf->data[CB] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CB].usr_addr;
+      mm_video_buf->handle.paddr[CR] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CR].phy_addr;
+      mm_video_buf->data[CR] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CR].usr_addr;
+      mm_video_buf->width[CB] = mm_video_buf->width[CR] =
+          fimcconvert->dst_caps_width;
+      mm_video_buf->height[CB] = mm_video_buf->height[CR] =
+          fimcconvert->dst_caps_height >> 2;
+      mm_video_buf->stride_width[CB] = mm_video_buf->width[CB];
+      mm_video_buf->stride_height[CB] = mm_video_buf->height[CB];
+      mm_video_buf->stride_width[CR] = mm_video_buf->width[CR];
+      mm_video_buf->stride_height[CR] = mm_video_buf->height[CR];
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'U', 'Y',
+            'V')
+        || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'U', 'Y',
+            '2')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SUYV, SUY2");
+      mm_video_buf->format = MM_PIXEL_FORMAT_YUYV;
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'Y', 'V',
+            'Y')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SYVY");
+      mm_video_buf->format = MM_PIXEL_FORMAT_UYVY;
+    } else {
+      free (mm_video_buf);
+      GST_ERROR_OBJECT (fimcconvert,
+          "OutBuf :: can not support this format (%d)",
+          fimcconvert->dst_fourcc_format);
+      return FALSE;
+    }
+    GST_DEBUG_OBJECT (fimcconvert,
+        "OutBuf :: y_phy_addr(0x%x), cb_phy_addr(0x%x), cr_phy_addr(0x%x)",
+        mm_video_buf->handle.paddr[0], mm_video_buf->handle.paddr[1],
+        mm_video_buf->handle.paddr[2]);
+
+  } else if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD ||
+      fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_TBM_BO) {
+
+    if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+      mm_video_buf->handle.dmabuf_fd[Y] =
+          fimcconvert->gem_info_dst[idx][Y].dma_buf_fd;
+    } else {
+      mm_video_buf->handle.bo[Y] = fimcconvert->gem_info_dst[idx][Y].bo;
+    }
+    mm_video_buf->data[Y] =
+        (void *) (unsigned long) fimcconvert->gem_info_dst[idx][Y].usr_addr;
+    mm_video_buf->width[Y] = fimcconvert->dst_caps_width;
+    mm_video_buf->height[Y] = fimcconvert->dst_caps_height;
+    mm_video_buf->stride_width[Y] = mm_video_buf->width[Y];
+    mm_video_buf->stride_height[Y] = mm_video_buf->height[Y];
+    mm_video_buf->type = fimcconvert->buf_type;
+
+    if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'T', '1', '2')
+        || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1',
+            '2')) {
+      if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+        mm_video_buf->handle.dmabuf_fd[CB] =
+            fimcconvert->gem_info_dst[idx][CB].dma_buf_fd;
+      } else {
+        mm_video_buf->handle.bo[CB] = fimcconvert->gem_info_dst[idx][CB].bo;
+      }
+      if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1',
+              '2')) {
+        GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SN12");
+        mm_video_buf->format = MM_PIXEL_FORMAT_NV12;
+      } else {
+        GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's ST12");
+        mm_video_buf->format = MM_PIXEL_FORMAT_NV12T;
+      }
+      mm_video_buf->data[CB] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CB].usr_addr;
+      mm_video_buf->width[CB] = fimcconvert->dst_caps_width;
+      mm_video_buf->height[CB] = fimcconvert->dst_caps_height >> 1;
+      mm_video_buf->stride_width[CB] = mm_video_buf->width[CB];
+      mm_video_buf->stride_height[CB] = mm_video_buf->height[CB];
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4', '2',
+            '0')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's S420");
+      if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+        mm_video_buf->handle.dmabuf_fd[CB] =
+            fimcconvert->gem_info_dst[idx][CB].dma_buf_fd;
+        mm_video_buf->handle.dmabuf_fd[CR] =
+            fimcconvert->gem_info_dst[idx][CR].dma_buf_fd;
+      } else {
+        mm_video_buf->handle.bo[CB] = fimcconvert->gem_info_dst[idx][CB].bo;
+        mm_video_buf->handle.bo[CR] = fimcconvert->gem_info_dst[idx][CR].bo;
+      }
+      mm_video_buf->format = MM_PIXEL_FORMAT_I420;
+      mm_video_buf->data[CB] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CB].usr_addr;
+      mm_video_buf->data[CR] =
+          (void *) (unsigned long) fimcconvert->gem_info_dst[idx][CR].usr_addr;
+      mm_video_buf->width[CB] = mm_video_buf->width[CR] =
+          fimcconvert->dst_caps_width;
+      mm_video_buf->height[CB] = mm_video_buf->height[CR] =
+          fimcconvert->dst_caps_height >> 2;
+      mm_video_buf->stride_width[CB] = mm_video_buf->width[CB];
+      mm_video_buf->stride_height[CB] = mm_video_buf->height[CB];
+      mm_video_buf->stride_width[CR] = mm_video_buf->width[CR];
+      mm_video_buf->stride_height[CR] = mm_video_buf->height[CR];
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'U', 'Y',
+            'V')
+        || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'U', 'Y',
+            '2')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SUYV, SUY2");
+      mm_video_buf->format = MM_PIXEL_FORMAT_YUYV;
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'Y', 'V',
+            'Y')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SYVY");
+      mm_video_buf->format = MM_PIXEL_FORMAT_UYVY;
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'R', '3',
+            '2')) {
+      GST_INFO_OBJECT (fimcconvert, "OutBuf :: It's SR32");
+      mm_video_buf->format = MM_PIXEL_FORMAT_RGB888;
+    } else {
+      free (mm_video_buf);
+      GST_ERROR_OBJECT (fimcconvert,
+          "OutBuf :: can not support this format (%d)",
+          fimcconvert->dst_fourcc_format);
+      return FALSE;
+    }
+
+    if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+      GST_DEBUG_OBJECT (fimcconvert, "OutBuf :: y_fd(%d), cb_fd(%d), cr_fd(%d)",
+          mm_video_buf->handle.dmabuf_fd[Y], mm_video_buf->handle.dmabuf_fd[CB],
+          mm_video_buf->handle.dmabuf_fd[CR]);
+    } else {
+      GST_DEBUG_OBJECT (fimcconvert, "OutBuf :: y_bo(%p), cb_bo(%p), cr_bo(%p)",
+          mm_video_buf->handle.bo[Y], mm_video_buf->handle.bo[CB],
+          mm_video_buf->handle.bo[CR]);
+    }
+
+  } else {
+    free (mm_video_buf);
+    GST_ERROR_OBJECT (fimcconvert,
+        "OutBuf :: invalid buffer sharing method type (%d)",
+        fimcconvert->buf_type);
+    return FALSE;
+  }
+
+  /* Set MMVideoBuffer pointer */
+  gst_buffer_prepend_memory (buf,
+      gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, mm_video_buf,
+          sizeof (*mm_video_buf), 0, sizeof (*mm_video_buf), mm_video_buf,
+          free));
+
+  return TRUE;
+}
+
+static guint32
+gst_fimcconvert_get_drm_format (GstCaps * caps)
+{
+  GstStructure *str = NULL;
+  GstVideoInfo video_info;
+  GstVideoFormat format = GST_VIDEO_FORMAT_UNKNOWN;
+  const gchar *s;
+
+  str = gst_caps_get_structure (caps, 0);
+
+  if (gst_structure_has_name (str, "video/x-raw")) {
+    gst_video_info_from_caps (&video_info, caps);
+    if (GST_VIDEO_INFO_IS_RGB (&video_info)) {
+      gint bpp = 0;
+
+      if (!gst_structure_get_int (str, "bpp", &bpp) || (bpp & 0x07) != 0)
+        return 0;
+      if (bpp == 16) {
+        GST_INFO ("It's RGB565, bpp(16)");
+        return DRM_FORMAT_RGB565;
+      } else if (bpp == 24) {
+        GST_INFO ("It's RGB888, bpp(24)");
+        return DRM_FORMAT_RGB888;
+      } else if (bpp == 32) {
+#if 1
+        GST_INFO ("It's XRGB8888, bpp(32)");
+        return DRM_FORMAT_XRGB8888;
+#else
+        /* NOTE : BGRA8888 test required if kernel support it */
+        GST_INFO ("It's BGRA8888, bpp(32)");
+        return DRM_FORMAT_BGRA8888;
+#endif
+      } else {
+        GST_ERROR ("bpp is not valid. bpp(%d)", bpp);
+        return 0;
+      }
+    } else if (GST_VIDEO_INFO_IS_YUV (&video_info)) {
+      if (!(s = gst_structure_get_string (str, "format"))) {
+        GST_INFO ("Failed to get format from in_caps");
+        return 0;
+      }
+      format = gst_video_format_from_string (s);
+      if (format == GST_VIDEO_FORMAT_UNKNOWN) {
+        GST_INFO ("Failed to get format from in_caps");
+        return FALSE;
+      }
+      switch (format) {
+        case GST_VIDEO_FORMAT_ST12:
+          GST_INFO ("Returning DRM format is DRM_FORMAT_NV12MT");
+          return DRM_FORMAT_NV12MT;
+        case GST_VIDEO_FORMAT_SN12:
+        case GST_VIDEO_FORMAT_NV12:
+          GST_INFO ("Returning DRM format is DRM_FORMAT_NV12");
+          return DRM_FORMAT_NV12;
+        case GST_VIDEO_FORMAT_SUY2:
+        case GST_VIDEO_FORMAT_YUY2:
+          GST_INFO ("Returning DRM format is DRM_FORMAT_YUYV");
+          return DRM_FORMAT_YUYV;
+        case GST_VIDEO_FORMAT_I420:
+        case GST_VIDEO_FORMAT_S420:
+          GST_INFO ("Returning DRM format is DRM_FORMAT_YUV420");
+          return DRM_FORMAT_YUV420;
+        case GST_VIDEO_FORMAT_ITLV:
+        case GST_VIDEO_FORMAT_SYVY:
+        case GST_VIDEO_FORMAT_UYVY:
+          GST_INFO ("Returning DRM format is DRM_FORMAT_UYVY");
+          return DRM_FORMAT_UYVY;
+        default:
+          GST_WARNING ("not supported DRM format");
+          return 0;
+      }
+    }
+
+  }
+  return 0;
+}
+
+/* copies the given caps */
+static GstCaps *
+gst_fimcconvert_caps_remove_format_info (GstCaps * caps)
+{
+  GstStructure *st;
+  GstCapsFeatures *f;
+  gint i, n;
+  GstCaps *res;
+
+  res = gst_caps_new_empty ();
+
+  n = gst_caps_get_size (caps);
+  for (i = 0; i < n; i++) {
+    st = gst_caps_get_structure (caps, i);
+    f = gst_caps_get_features (caps, i);
+
+    /* If this is already expressed by the existing caps
+     * skip this structure */
+    if (i > 0 && gst_caps_is_subset_structure_full (res, st, f))
+      continue;
+
+    st = gst_structure_copy (st);
+    /* Only remove format info for the cases when we can actually convert */
+    if (!gst_caps_features_is_any (f)
+        && gst_caps_features_is_equal (f,
+            GST_CAPS_FEATURES_MEMORY_SYSTEM_MEMORY))
+      gst_structure_remove_fields (st, "format", "colorimetry", "chroma-site",
+          NULL);
+
+    gst_caps_append_structure_full (res, st, gst_caps_features_copy (f));
+  }
+
+  return res;
+}
+
+static GstCaps *
+gst_fimcconvert_transform_caps (GstBaseTransform * trans,
+    GstPadDirection direction, GstCaps * caps, GstCaps * filter)
+{
+  GstCaps *tmp, *tmp2;
+  GstCaps *result;
+
+  /* Get all possible caps that we can transform to */
+  tmp = gst_fimcconvert_caps_remove_format_info (caps);
+
+  if (filter) {
+    tmp2 = gst_caps_intersect_full (filter, tmp, GST_CAPS_INTERSECT_FIRST);
+    gst_caps_unref (tmp);
+    tmp = tmp2;
+  }
+
+  result = tmp;
+
+  GST_DEBUG_OBJECT (trans, "transformed %" GST_PTR_FORMAT " into %"
+      GST_PTR_FORMAT, caps, result);
+  return result;
+}
+
+/*
+ * This is an incomplete matrix of in formats and a score for the prefered output
+ * format.
+ *
+ *         out: RGB24   RGB16  ARGB  AYUV  YUV444  YUV422 YUV420 YUV411 YUV410  PAL  GRAY
+ *  in
+ * RGB24          0      2       1     2     2       3      4      5      6      7    8
+ * RGB16          1      0       1     2     2       3      4      5      6      7    8
+ * ARGB           2      3       0     1     4       5      6      7      8      9    10
+ * AYUV           3      4       1     0     2       5      6      7      8      9    10
+ * YUV444         2      4       3     1     0       5      6      7      8      9    10
+ * YUV422         3      5       4     2     1       0      6      7      8      9    10
+ * YUV420         4      6       5     3     2       1      0      7      8      9    10
+ * YUV411         4      6       5     3     2       1      7      0      8      9    10
+ * YUV410         6      8       7     5     4       3      2      1      0      9    10
+ * PAL            1      3       2     6     4       6      7      8      9      0    10
+ * GRAY           1      4       3     2     1       5      6      7      8      9    0
+ *
+ * PAL or GRAY are never prefered, if we can we would convert to PAL instead
+ * of GRAY, though
+ * less subsampling is prefered and if any, preferably horizontal
+ * We would like to keep the alpha, even if we would need to to colorspace conversion
+ * or lose depth.
+ */
+#define SCORE_PALETTE_LOSS        1
+#define SCORE_COLOR_LOSS          2
+#define SCORE_ALPHA_LOSS          4
+#define SCORE_CHROMA_W_LOSS       8
+#define SCORE_CHROMA_H_LOSS      16
+#define SCORE_DEPTH_LOSS         32
+
+#define COLOR_MASK   (GST_VIDEO_FORMAT_FLAG_YUV | \
+                      GST_VIDEO_FORMAT_FLAG_RGB | GST_VIDEO_FORMAT_FLAG_GRAY)
+#define ALPHA_MASK   (GST_VIDEO_FORMAT_FLAG_ALPHA)
+#define PALETTE_MASK (GST_VIDEO_FORMAT_FLAG_PALETTE)
+
+static void
+score_value (GstBaseTransform * base, const GstVideoFormatInfo * in_info,
+    const GValue * val, gint * min_loss, const GstVideoFormatInfo ** out_info)
+{
+  const gchar *fname;
+  const GstVideoFormatInfo *t_info;
+  GstVideoFormatFlags in_flags, t_flags;
+  gint loss;
+
+  fname = g_value_get_string (val);
+  t_info = gst_video_format_get_info (gst_video_format_from_string (fname));
+  if (!t_info)
+    return;
+
+  /* accept input format immediately without loss */
+  if (in_info == t_info) {
+    *min_loss = 0;
+    *out_info = t_info;
+    return;
+  }
+
+  loss = 1;
+
+  in_flags = GST_VIDEO_FORMAT_INFO_FLAGS (in_info);
+  in_flags &= ~GST_VIDEO_FORMAT_FLAG_LE;
+  in_flags &= ~GST_VIDEO_FORMAT_FLAG_COMPLEX;
+  in_flags &= ~GST_VIDEO_FORMAT_FLAG_UNPACK;
+
+  t_flags = GST_VIDEO_FORMAT_INFO_FLAGS (t_info);
+  t_flags &= ~GST_VIDEO_FORMAT_FLAG_LE;
+  t_flags &= ~GST_VIDEO_FORMAT_FLAG_COMPLEX;
+  t_flags &= ~GST_VIDEO_FORMAT_FLAG_UNPACK;
+
+  if ((t_flags & PALETTE_MASK) != (in_flags & PALETTE_MASK))
+    loss += SCORE_PALETTE_LOSS;
+
+  if ((t_flags & COLOR_MASK) != (in_flags & COLOR_MASK))
+    loss += SCORE_COLOR_LOSS;
+
+  if ((t_flags & ALPHA_MASK) != (in_flags & ALPHA_MASK))
+    loss += SCORE_ALPHA_LOSS;
+
+  if ((in_info->h_sub[1]) < (t_info->h_sub[1]))
+    loss += SCORE_CHROMA_H_LOSS;
+  if ((in_info->w_sub[1]) < (t_info->w_sub[1]))
+    loss += SCORE_CHROMA_W_LOSS;
+
+  if ((in_info->bits) > (t_info->bits))
+    loss += SCORE_DEPTH_LOSS;
+
+  GST_DEBUG_OBJECT (base, "score %s -> %s = %d",
+      GST_VIDEO_FORMAT_INFO_NAME (in_info),
+      GST_VIDEO_FORMAT_INFO_NAME (t_info), loss);
+
+  if (loss < *min_loss) {
+    GST_DEBUG_OBJECT (base, "found new best %d", loss);
+    *out_info = t_info;
+    *min_loss = loss;
+  }
+}
+
+static void
+gst_fimcconvert_fixate_format (GstBaseTransform * base, GstCaps * caps,
+    GstCaps * result)
+{
+  GstStructure *ins, *outs;
+  const gchar *in_format;
+  const GstVideoFormatInfo *in_info, *out_info = NULL;
+  gint min_loss = G_MAXINT;
+  guint i, capslen;
+
+  ins = gst_caps_get_structure (caps, 0);
+  in_format = gst_structure_get_string (ins, "format");
+  if (!in_format) {
+    GST_WARNING_OBJECT (base, "Failed to get source format");
+    return;
+  }
+  GST_DEBUG_OBJECT (base, "source format %s", in_format);
+
+  in_info =
+      gst_video_format_get_info (gst_video_format_from_string (in_format));
+  if (!in_info) {
+    GST_WARNING_OBJECT (base, "Failed to get video format info");
+    return;
+  }
+  outs = gst_caps_get_structure (result, 0);
+
+  capslen = gst_caps_get_size (result);
+  GST_DEBUG_OBJECT (base, "iterate %d structures", capslen);
+  for (i = 0; i < capslen; i++) {
+    GstStructure *tests;
+    const GValue *format;
+
+    tests = gst_caps_get_structure (result, i);
+    format = gst_structure_get_value (tests, "format");
+    /* should not happen */
+    if (format == NULL)
+      continue;
+
+    if (GST_VALUE_HOLDS_LIST (format)) {
+      gint j, len;
+
+      len = gst_value_list_get_size (format);
+      GST_DEBUG_OBJECT (base, "have %d formats", len);
+      for (j = 0; j < len; j++) {
+        const GValue *val;
+
+        val = gst_value_list_get_value (format, j);
+        if (G_VALUE_HOLDS_STRING (val)) {
+          score_value (base, in_info, val, &min_loss, &out_info);
+          if (min_loss == 0)
+            break;
+        }
+      }
+    } else if (G_VALUE_HOLDS_STRING (format)) {
+      score_value (base, in_info, format, &min_loss, &out_info);
+    }
+  }
+  if (out_info)
+    gst_structure_set (outs, "format", G_TYPE_STRING,
+        GST_VIDEO_FORMAT_INFO_NAME (out_info), NULL);
+}
+
+// fixate_caps function is from videoconvert plugin
+static GstCaps *
+gst_fimcconvert_fixate_caps (GstBaseTransform * base, GstPadDirection direction,
+    GstCaps * caps, GstCaps * othercaps)
+{
+  GstCaps *result;
+
+  GST_DEBUG_OBJECT (base, "trying to fixate othercaps %" GST_PTR_FORMAT
+      " based on caps %" GST_PTR_FORMAT, othercaps, caps);
+
+  result = gst_caps_intersect (othercaps, caps);
+  if (gst_caps_is_empty (result)) {
+    gst_caps_unref (result);
+    result = othercaps;
+  } else {
+    gst_caps_unref (othercaps);
+  }
+
+  GST_DEBUG_OBJECT (base, "now fixating %" GST_PTR_FORMAT, result);
+
+  result = gst_caps_make_writable (result);
+  gst_fimcconvert_fixate_format (base, caps, result);
+
+  /* fixate remaining fields */
+  result = gst_caps_fixate (result);
+
+  return result;
+}
+
+static gboolean
+gst_fimcconvert_set_caps (GstBaseTransform * trans, GstCaps * in, GstCaps * out)
+{
+  GstFimcConvert *fimcconvert = NULL;
+  GstStructure *in_str, *out_str;
+  const gchar *format_name = NULL;
+  GstVideoFormat format = GST_VIDEO_FORMAT_UNKNOWN;
+  const gchar *s;
+  gint in_caps_width = 0;
+  gint in_caps_height = 0;
+
+  fimcconvert = GST_FIMCCONVERT (trans);
+
+  GST_WARNING_OBJECT (fimcconvert, "[incaps] %" GST_PTR_FORMAT, in);
+  GST_WARNING_OBJECT (fimcconvert, "[outcaps] %" GST_PTR_FORMAT, out);
+
+  /* get src width/height/format of video frame */
+  in_str = gst_caps_get_structure (in, 0);
+  if (!gst_structure_get_int (in_str, "width", &in_caps_width) ||
+      !gst_structure_get_int (in_str, "height", &in_caps_height)) {
+    GST_ERROR_OBJECT (fimcconvert,
+        "Failed to get width or height from in_caps");
+    return FALSE;
+  }
+  if (!(s = gst_structure_get_string (in_str, "format"))) {
+    GST_DEBUG_OBJECT (fimcconvert, "Failed to get format from in_caps");
+    return FALSE;
+  }
+  format = gst_video_format_from_string (s);
+  if (format == GST_VIDEO_FORMAT_UNKNOWN) {
+    GST_ERROR_OBJECT (fimcconvert, "Failed to get format from in_caps");
+    return FALSE;
+  }
+  if (format != GST_VIDEO_FORMAT_UNKNOWN &&
+      format != GST_VIDEO_FORMAT_ITLV &&
+      format != GST_VIDEO_FORMAT_SN12 &&
+      format != GST_VIDEO_FORMAT_ST12 &&
+      format != GST_VIDEO_FORMAT_S420 &&
+      format != GST_VIDEO_FORMAT_SUY2 && format != GST_VIDEO_FORMAT_SYVY) {
+    fimcconvert->is_src_format_std = TRUE;
+    GST_LOG_OBJECT (fimcconvert, "input format is a standard format");
+  } else {
+    fimcconvert->is_src_format_std = FALSE;
+    GST_LOG_OBJECT (fimcconvert, "input format is not a standard format");
+  }
+
+  /* determine whether if incaps is same as outcaps */
+  if (gst_caps_is_equal (in, out) &&
+      ((!fimcconvert->dst_width && !fimcconvert->dst_height) ||
+          ((fimcconvert->dst_width == in_caps_width)
+              && (fimcconvert->dst_height == in_caps_height)))
+      && !fimcconvert->dst_flip && !fimcconvert->rotate_ang) {
+    GST_LOG_OBJECT (fimcconvert, "incaps is same as outcaps");
+    fimcconvert->is_same_caps = TRUE;
+    return TRUE;
+  } else {
+    fimcconvert->is_same_caps = FALSE;
+  }
+
+  /* set src width/height of video frame */
+  fimcconvert->in_caps_width = in_caps_width;
+  fimcconvert->in_caps_height = in_caps_height;
+  fimcconvert->src_drm_format = gst_fimcconvert_get_drm_format (in);
+  GST_INFO_OBJECT (fimcconvert, "[incaps] width(%d) height(%d)",
+      fimcconvert->in_caps_width, fimcconvert->in_caps_height);
+
+  /* set dst width/height of video frame */
+  if (!fimcconvert->dst_width || !fimcconvert->dst_height) {
+    out_str = gst_caps_get_structure (out, 0);
+    if (!gst_structure_get_int (out_str, "width", &fimcconvert->dst_caps_width)
+        || !gst_structure_get_int (out_str, "height",
+            &fimcconvert->dst_caps_height)) {
+      GST_ERROR_OBJECT (fimcconvert,
+          "output frame width or height is not set...");
+      return FALSE;
+    }
+  }
+  fimcconvert->dst_drm_format = gst_fimcconvert_get_drm_format (out);
+  fimcconvert->dst_format_name = gst_structure_get_string (out_str, "format");
+  format_name = fimcconvert->dst_format_name;
+  fimcconvert->dst_fourcc_format =
+      gst_video_format_to_fourcc (gst_video_format_from_string (format_name));
+  if (!fimcconvert->dst_fourcc_format) {
+    GST_DEBUG_OBJECT (fimcconvert,
+        "format(dst) is not set...it may be rgb series");
+  }
+  GST_INFO_OBJECT (fimcconvert, "[outcaps] width(%d) height(%d)",
+      fimcconvert->dst_caps_width, fimcconvert->dst_caps_height);
+  if (fimcconvert->dst_fourcc_format) {
+    GST_INFO_OBJECT (fimcconvert, "[set dst_caps] format(%c%c%c%c)",
+        fimcconvert->dst_fourcc_format, fimcconvert->dst_fourcc_format >> 8,
+        fimcconvert->dst_fourcc_format >> 16,
+        fimcconvert->dst_fourcc_format >> 24);
+  }
+  gst_fimcconvert_reset (fimcconvert);
+
+  return TRUE;
+}
+
+static gboolean
+gst_fimcconvert_get_unit_size (GstBaseTransform * trans, GstCaps * caps,
+    guint * size)
+{
+  GstVideoInfo info;
+  GstFimcConvert *fimcconvert;
+  fimcconvert = GST_FIMCCONVERT (trans);
+
+  if (!gst_video_info_from_caps (&info, caps)) {
+    GST_WARNING_OBJECT (fimcconvert, "Failed to parse caps %" GST_PTR_FORMAT,
+        caps);
+    return FALSE;
+  }
+
+  *size = info.size;
+
+  GST_DEBUG_OBJECT (fimcconvert, "Returning size %" G_GSIZE_FORMAT " bytes"
+      "for caps %" GST_PTR_FORMAT, *size, caps);
+
+  return TRUE;
+}
+
+static GstFlowReturn
+gst_fimcconvert_prepare_output_buffer (GstBaseTransform * trans,
+    GstBuffer * in_buf, GstBuffer ** out_buf)
+{
+  gboolean ret = TRUE;
+  guint out_size = 0;
+  guint in_size = 0;
+  GstFimcConvert *fimcconvert = GST_FIMCCONVERT (trans);
+  GstCaps *out_caps;
+  GstCaps *in_caps;
+  GstFimcConvertBuffer *fimcconvert_buffer = NULL;
+
+  GST_DEBUG ("[START]");
+
+  if (fimcconvert->is_same_caps) {
+    GST_INFO ("in/out caps are same. skipping it");
+    *out_buf = in_buf;
+    GST_DEBUG ("[END]");
+    return GST_FLOW_OK;
+  }
+
+  g_mutex_lock (fimcconvert->fd_lock);
+
+  in_caps = gst_pad_get_current_caps (trans->sinkpad);
+  out_caps = gst_pad_get_current_caps (trans->srcpad);
+  GST_INFO ("Get in_buf size");
+  ret = gst_fimcconvert_get_unit_size (trans, in_caps, &in_size);
+  if (ret == FALSE) {
+    GST_ERROR ("ERROR in _get_unit_size from in_caps...");
+    return GST_FLOW_ERROR;
+  }
+  GST_INFO ("Get out_buf size");
+  ret = gst_fimcconvert_get_unit_size (trans, out_caps, &out_size);
+  if (ret == FALSE) {
+    GST_ERROR ("ERROR in _get_unit_size from out_caps...");
+    return GST_FLOW_ERROR;
+  }
+
+  GST_INFO ("In buffer size = %d", in_size);
+  GST_INFO ("Out buffer size = %d", out_size);
+
+  fimcconvert->dst_buf_size = out_size;
+
+
+  fimcconvert_buffer = gst_fimcconvert_buffer_new (fimcconvert, out_size);
+  *out_buf = fimcconvert_buffer->buffer;
+  if (*out_buf == NULL) {
+    GST_ERROR ("ERROR in creating outbuf...");
+    return GST_FLOW_ERROR;
+  }
+
+  gst_buffer_copy_into (*out_buf, in_buf, GST_BUFFER_COPY_METADATA, 0, -1);
+  GST_LOG ("out ts : %" GST_TIME_FORMAT " and out dur : %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (*out_buf)),
+      GST_TIME_ARGS (GST_BUFFER_DURATION (*out_buf)));
+  GST_DEBUG ("output buffer ready");
+  gst_caps_unref (out_caps);
+
+  gst_buffer_append_memory (*out_buf,
+      gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
+          fimcconvert_buffer,
+          sizeof (*fimcconvert_buffer),
+          0,
+          sizeof (*fimcconvert_buffer),
+          fimcconvert_buffer,
+          (GDestroyNotify) gst_fimcconvert_buffer_finalize));
+  g_mutex_unlock (fimcconvert->fd_lock);
+
+  GST_DEBUG ("[END]");
+
+  return GST_FLOW_OK;
+}
+
+static gboolean
+gst_fimcconvert_check_new_src (GstFimcConvert * fimcconvert, GstBuffer * inbuf)
+{
+  MMVideoBuffer *mm_video_buf = NULL;
+  GstMemory *mm_video_buf_memory = NULL;
+  GstMapInfo mm_video_buf_info = GST_MAP_INFO_INIT;
+  int i = 0;
+  guint phy_addr = 0;
+  gint fd = 0;
+  tbm_bo bo = 0;
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  if (!fimcconvert->is_src_format_std) {
+    if (gst_buffer_n_memory (inbuf) >= 2) {
+      mm_video_buf_memory = gst_buffer_peek_memory (inbuf, 1);
+      gst_memory_map (mm_video_buf_memory, &mm_video_buf_info, GST_MAP_READ);
+      mm_video_buf = (MMVideoBuffer *) mm_video_buf_info.data;
+      gst_memory_unmap (mm_video_buf_memory, &mm_video_buf_info);
+      if (!mm_video_buf) {
+        GST_ERROR_OBJECT (fimcconvert, "mm_video_buf is NULL");
+        return FALSE;
+      }
+      if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS) {
+        GST_LOG_OBJECT (fimcconvert, "Samsung colorspace format, PADDR type");
+        phy_addr = (guint) mm_video_buf->handle.paddr[Y];
+        if (phy_addr) {
+          for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+            if (fimcconvert->gem_info_src[i][Y].gem_handle) {
+              if (phy_addr == fimcconvert->gem_info_src[i][Y].phy_addr) {
+                return FALSE;
+              }
+            } else {
+              return TRUE;
+            }
+          }
+        } else {
+          GST_WARNING_OBJECT (fimcconvert,
+              "invalid value : mm_video_buf->handle.paddr[Y] = 0");
+          fimcconvert->do_skip = TRUE;
+          return FALSE;
+        }
+      } else if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+        GST_LOG_OBJECT (fimcconvert, "Samsung colorspace format, FD type");
+        fd = mm_video_buf->handle.dmabuf_fd[Y];
+        if (fd) {
+          for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+            if (fimcconvert->gem_info_src[i][Y].dma_buf_fd) {
+              if (fd == fimcconvert->gem_info_src[i][Y].dma_buf_fd) {
+                return FALSE;
+              }
+            } else {
+              return TRUE;
+            }
+          }
+        } else {
+          GST_WARNING_OBJECT (fimcconvert,
+              "invalid value : mm_video_buf->handle.dmabuf_fd[Y] = 0");
+          fimcconvert->do_skip = TRUE;
+          return FALSE;
+        }
+      } else if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_TBM_BO) {
+        GST_LOG_OBJECT (fimcconvert, "Samsung colorspace format, TBM type");
+        bo = mm_video_buf->handle.bo[Y];
+        if (bo) {
+          for (i = 0; i < MAX_SRC_BUF_NUM; i++) {
+            if (fimcconvert->gem_info_src[i][Y].bo) {
+              if (bo == fimcconvert->gem_info_src[i][Y].bo) {
+                return FALSE;
+              }
+            } else {
+              return TRUE;
+            }
+          }
+        } else {
+          GST_WARNING_OBJECT (fimcconvert,
+              "invalid value : mm_video_buf->handle.bo[Y] = 0");
+          fimcconvert->do_skip = TRUE;
+          return FALSE;
+        }
+      } else {
+        GST_ERROR_OBJECT (fimcconvert,
+            "Samsung colorspace format, could not find BUF_SHARE_METHOD type");
+        return FALSE;
+      }
+    } else {
+      GST_ERROR_OBJECT (fimcconvert,
+          "Samsung colorspace format, could not get IMGB");
+      return FALSE;
+    }
+  } else {
+    /* if a buffer passed from src plugin has a standard colorspace format, return TRUE */
+    if (fimcconvert->src_buf_idx == SRC_BUF_NUM_FOR_STD_FMT) {
+      return FALSE;
+    } else {
+      return TRUE;
+    }
+  }
+
+  GST_ERROR_OBJECT (fimcconvert, "should not reach here");
+  return TRUE;
+}
+
+static gboolean
+gst_fimcconvert_drm_prepare_src_buf (GstFimcConvert * fimcconvert,
+    GstBuffer * inbuf)
+{
+  /*Actually, IPP use non-aligned width and  height of src image
+     but let's assign memory by a wide margin */
+  MMVideoBuffer *mm_video_buf = NULL;
+  GstMemory *mm_video_buf_memory = NULL;
+  GstMapInfo mm_video_buf_info = GST_MAP_INFO_INIT;
+  guint src_idx = 0;
+  guint dst_idx = 0;
+  guint width = 0;
+  guint height = 0;
+
+  struct drm_exynos_gem_phy_imp gem_src_phy_imp_y;
+  struct drm_exynos_gem_phy_imp gem_src_phy_imp_cb;
+  struct drm_exynos_gem_phy_imp gem_src_phy_imp_cr;
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+#ifdef DEBUG_FOR_DV
+  if (total_converted_frame_count <= 10) {
+    GST_WARNING_OBJECT (fimcconvert, "[START]");
+  }
+#endif
+
+  memset (&gem_src_phy_imp_y, 0x0, sizeof (struct drm_exynos_gem_phy_imp));
+  memset (&gem_src_phy_imp_cb, 0x0, sizeof (struct drm_exynos_gem_phy_imp));
+  memset (&gem_src_phy_imp_cr, 0x0, sizeof (struct drm_exynos_gem_phy_imp));
+
+  src_idx = fimcconvert->src_buf_idx;
+  dst_idx = fimcconvert->dst_buf_idx;
+  width = fimcconvert->in_caps_width;
+  height = fimcconvert->in_caps_height;
+
+  GST_INFO_OBJECT (fimcconvert, "InBuf :: input buffer(%p)", inbuf);
+
+  if (!fimcconvert->is_src_format_std) {
+    if (gst_buffer_n_memory (inbuf) >= 2) {
+      mm_video_buf_memory = gst_buffer_peek_memory (inbuf, 1);
+      gst_memory_map (mm_video_buf_memory, &mm_video_buf_info, GST_MAP_READ);
+      mm_video_buf = (MMVideoBuffer *) mm_video_buf_info.data;
+      gst_memory_unmap (mm_video_buf_memory, &mm_video_buf_info);
+      if (!mm_video_buf) {
+        GST_ERROR_OBJECT (fimcconvert, "mm_video_buf is NULL");
+        return FALSE;
+      }
+      GST_LOG_OBJECT (fimcconvert,
+          "InBuf :: buf_type=%d (0:PADDR/1:FD/2:TBM)", mm_video_buf->type);
+
+      if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS) {
+        fimcconvert->buf_type = MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS;
+
+        switch (fimcconvert->src_drm_format) {
+          case DRM_FORMAT_NV12MT:
+            GST_LOG_OBJECT (fimcconvert, "DRM format is DRM_FORMAT_NV12MT");
+            gem_src_phy_imp_y.phy_addr = (guint) mm_video_buf->handle.paddr[0];
+            gem_src_phy_imp_cb.phy_addr = (guint) mm_video_buf->handle.paddr[1];
+            gem_src_phy_imp_y.size =
+                ALIGN_TO_8KB (ALIGN_TO_128B (width) * ALIGN_TO_32B (height));
+            gem_src_phy_imp_cb.size =
+                ALIGN_TO_8KB (ALIGN_TO_128B (width) *
+                ALIGN_TO_32B (height >> 1));
+            break;
+          case DRM_FORMAT_NV12:
+            GST_LOG_OBJECT (fimcconvert, "DRM format is DRM_FORMAT_NV12");
+            gem_src_phy_imp_y.phy_addr = (guint) mm_video_buf->handle.paddr[0];
+            gem_src_phy_imp_cb.phy_addr = (guint) mm_video_buf->handle.paddr[1];
+            gem_src_phy_imp_y.size =
+                mm_video_buf->width[0] * mm_video_buf->height[0];
+            gem_src_phy_imp_cb.size =
+                mm_video_buf->width[0] * mm_video_buf->height[0] >> 1;
+            break;
+
+          case DRM_FORMAT_UYVY:
+          case DRM_FORMAT_YUYV:
+            GST_LOG_OBJECT (fimcconvert,
+                "DRM format is DRM_FORMAT_UYVY or DRM_FORMAT_YUYV");
+            gem_src_phy_imp_y.phy_addr = (guint) mm_video_buf->handle.paddr[0];
+            gem_src_phy_imp_y.size =
+                (mm_video_buf->width[0] * mm_video_buf->height[0]) << 1;
+            break;
+          case DRM_FORMAT_YUV420:
+            GST_LOG_OBJECT (fimcconvert, "DRM format is DRM_FORMAT_YUV420");
+            gem_src_phy_imp_y.phy_addr = (guint) mm_video_buf->handle.paddr[0];
+            gem_src_phy_imp_cb.phy_addr = (guint) mm_video_buf->handle.paddr[1];
+            gem_src_phy_imp_cr.phy_addr = (guint) mm_video_buf->handle.paddr[2];
+            gem_src_phy_imp_y.size =
+                mm_video_buf->width[0] * mm_video_buf->height[0];
+            gem_src_phy_imp_cb.size =
+                mm_video_buf->width[0] * mm_video_buf->height[0] >> 2;
+            gem_src_phy_imp_cr.size = gem_src_phy_imp_cb.size;
+            break;
+          default:
+            GST_ERROR_OBJECT (fimcconvert,
+                "Un-Supported Input color format...");
+            return FALSE;
+        }
+        GST_INFO_OBJECT (fimcconvert,
+            "InBuf :: It's a samsung extension format(%d)",
+            fimcconvert->src_drm_format);
+
+        if (!gem_src_phy_imp_y.phy_addr) {
+          GST_WARNING_OBJECT (fimcconvert,
+              "gem_src_phy_imp_y.phy_addr is null..");
+          fimcconvert->do_skip = TRUE;
+          return TRUE;
+        }
+
+        /* Do DRM_IOCTL_EXYNOS_GEM_GET_PHY */
+        if (fimcconvert->drm_fimc_fd) {
+          if (fimcconvert_drm_gem_import_phy_addr (fimcconvert->drm_fimc_fd,
+                  &gem_src_phy_imp_y)) {
+            return FALSE;
+          }
+          fimcconvert->gem_info_src[src_idx][Y].gem_handle =
+              gem_src_phy_imp_y.gem_handle;
+          fimcconvert->gem_info_src[src_idx][Y].phy_addr =
+              gem_src_phy_imp_y.phy_addr;
+          GST_DEBUG_OBJECT (fimcconvert,
+              "InBuf :: gem_src_phy_imp_y[%d] : gem_handle=%d, y_phy_addr=0x%x",
+              src_idx, gem_src_phy_imp_y.gem_handle,
+              (void *) (unsigned long) gem_src_phy_imp_y.phy_addr);
+
+          switch (fimcconvert->src_drm_format) {
+            case DRM_FORMAT_NV12MT:
+            case DRM_FORMAT_NV12:
+              if (fimcconvert_drm_gem_import_phy_addr (fimcconvert->drm_fimc_fd,
+                      &gem_src_phy_imp_cb)) {
+                return FALSE;
+              }
+              fimcconvert->gem_info_src[src_idx][CB].gem_handle =
+                  gem_src_phy_imp_cb.gem_handle;
+              GST_DEBUG_OBJECT (fimcconvert,
+                  "InBuf :: gem_src_phy_imp_cb[%d] : gem_handle=%d, cb_phy_addr=0x%x",
+                  src_idx, gem_src_phy_imp_cb.gem_handle,
+                  (void *) (unsigned long) gem_src_phy_imp_cb.phy_addr);
+              break;
+
+            case DRM_FORMAT_YUV420:
+              if (fimcconvert_drm_gem_import_phy_addr (fimcconvert->drm_fimc_fd,
+                      &gem_src_phy_imp_cb)) {
+                return FALSE;
+              }
+              fimcconvert->gem_info_src[src_idx][CB].gem_handle =
+                  gem_src_phy_imp_cb.gem_handle;
+              GST_DEBUG_OBJECT (fimcconvert,
+                  "InBuf :: gem_src_phy_imp_cb[%d] : gem_handle=%d, cb_phy_addr=0x%x",
+                  src_idx, gem_src_phy_imp_cb.gem_handle,
+                  (void *) (unsigned long) gem_src_phy_imp_cb.phy_addr);
+              if (fimcconvert_drm_gem_import_phy_addr (fimcconvert->drm_fimc_fd,
+                      &gem_src_phy_imp_cr)) {
+                return FALSE;
+              }
+              fimcconvert->gem_info_src[src_idx][CR].gem_handle =
+                  gem_src_phy_imp_cr.gem_handle;
+              GST_DEBUG_OBJECT (fimcconvert,
+                  "InBuf :: gem_src_phy_imp_cr[%d] : gem_handle=%d, cr_phy_addr=0x%x",
+                  src_idx, gem_src_phy_imp_cr.gem_handle,
+                  (void *) (unsigned long) gem_src_phy_imp_cr.phy_addr);
+              break;
+          }
+        } else {
+          GST_ERROR_OBJECT (fimcconvert, "drm_fimc_fd is null..");
+          return FALSE;
+        }
+
+      } else if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+        int ret = 0;
+        int i = 0;
+        fimcconvert->buf_type = MM_VIDEO_BUFFER_TYPE_DMABUF_FD;
+
+        /* convert dma-buf fd into drm gem handle */
+        for (i = 0; i < MM_VIDEO_BUFFER_MAX_PLANE - 1; i++) {
+          fimcconvert->gem_info_src[src_idx][i].dma_buf_fd =
+              mm_video_buf->handle.dmabuf_fd[i];
+          ret =
+              fimcconvert_drm_convert_fd_to_gemhandle (fimcconvert->drm_fimc_fd,
+              (int) mm_video_buf->handle.dmabuf_fd[i],
+              &fimcconvert->gem_info_src[src_idx][i].gem_handle);
+          if (ret) {
+            return FALSE;
+          }
+        }
+        GST_DEBUG_OBJECT (fimcconvert,
+            "InBuf :: gem_info_src[%d] : gem_handle_y=%u, gem_handle_cb=%u, gem_handle_cr=%u",
+            src_idx,
+            fimcconvert->gem_info_src[src_idx][Y].gem_handle,
+            fimcconvert->gem_info_src[src_idx][CB].gem_handle,
+            fimcconvert->gem_info_src[src_idx][CR].gem_handle);
+
+      } else if (mm_video_buf->type == MM_VIDEO_BUFFER_TYPE_TBM_BO) {
+        int i = 0;
+        tbm_bo_handle bo_handle_gem;
+
+        fimcconvert->buf_type = MM_VIDEO_BUFFER_TYPE_TBM_BO;
+
+        /* convert bo into drm gem handle */
+        for (i = 0; i < MM_VIDEO_BUFFER_MAX_PLANE - 1; i++) {
+          if (mm_video_buf->handle.bo[i] > 0) {
+            GST_LOG_OBJECT (fimcconvert, "mm_video_buf->handle.bo[%d] = %p", i,
+                mm_video_buf->handle.bo[i]);
+            fimcconvert->gem_info_src[src_idx][i].bo =
+                mm_video_buf->handle.bo[i];
+            FIMCCONVERT_TBM_BO_GET_GEM_HANDLE (mm_video_buf->handle.bo[i],
+                bo_handle_gem);
+            fimcconvert->gem_info_src[src_idx][i].gem_handle =
+                bo_handle_gem.u32;
+          }
+        }
+        GST_DEBUG_OBJECT (fimcconvert,
+            "InBuf :: gem_info_src[%d] : gem_handle_y=%u, gem_handle_cb=%u, gem_handle_cr=%u",
+            src_idx,
+            fimcconvert->gem_info_src[src_idx][Y].gem_handle,
+            fimcconvert->gem_info_src[src_idx][CB].gem_handle,
+            fimcconvert->gem_info_src[src_idx][CR].gem_handle);
+      } else {
+        GST_ERROR_OBJECT (fimcconvert, "InBuf :: Unknown BUF_SHARE_METHOD");
+        return FALSE;
+      }
+    } else {
+      GST_WARNING_OBJECT (fimcconvert,
+          "InBuf :: could not get mm_video_buf from inbuf.. let this frame skip..");
+      fimcconvert->do_skip = TRUE;
+      return FALSE;
+    }
+  } else {
+    /* for a standard colorspace format */
+    fimcconvert->src_buf_size = gst_buffer_get_size (inbuf);
+
+    GST_INFO_OBJECT (fimcconvert,
+        "InBuf :: It's a standard format(%d)", fimcconvert->src_drm_format);
+    GST_DEBUG_OBJECT (fimcconvert,
+        "InBuf :: Prepare for memory copy, src data size(%d)",
+        fimcconvert->src_buf_size);
+
+    /* Make gem handle and do map for src buffer */
+    if (!gst_fimcconvert_tbm_create_and_map_bo (fimcconvert,
+            FIMCCONVERT_GEM_FOR_SRC)) {
+      return FALSE;
+    }
+
+    /* determine buf_type */
+    if (!fimcconvert->is_drm_inited) {
+      if (fimcconvert_drm_gem_get_phy_addr (fimcconvert->drm_fimc_fd,
+              fimcconvert->gem_info_src_normal_fmt[src_idx].gem_handle,
+              &fimcconvert->gem_info_src_normal_fmt[src_idx].phy_addr)) {
+#ifdef USE_TBM
+        fimcconvert->buf_type = MM_VIDEO_BUFFER_TYPE_TBM_BO;
+        GST_WARNING_OBJECT (fimcconvert, "InBuf :: buf_type = TIZEN_BUFFER");
+#else
+        fimcconvert->buf_type = MM_VIDEO_BUFFER_TYPE_DMABUF_FD;
+        GST_WARNING_OBJECT (fimcconvert, "InBuf :: buf_type = FD");
+#endif
+      } else {
+        fimcconvert->buf_type = MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS;
+        GST_WARNING_OBJECT (fimcconvert, "InBuf :: buf_type = PADDR");
+      }
+    }
+
+    fimcconvert->gem_info_src[src_idx][Y].gem_handle =
+        fimcconvert->gem_info_src_normal_fmt[src_idx].gem_handle;
+    GST_DEBUG_OBJECT (fimcconvert, "InBuf :: gem_info_src[%d].gem_handle_y=%u",
+        src_idx, fimcconvert->gem_info_src[src_idx][Y].gem_handle);
+  }
+
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+#ifdef DEBUG_FOR_DV
+  if (total_converted_frame_count <= 10) {
+    GST_WARNING_OBJECT (fimcconvert, "[END]");
+  }
+#endif
+
+  return TRUE;
+}
+
+static gboolean
+gst_fimcconvert_drm_prepare_dst_buf (GstFimcConvert * fimcconvert)
+{
+  guint dst_idx = 0;
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+#ifdef DEBUG_FOR_DV
+  if (total_converted_frame_count <= 10) {
+    GST_WARNING_OBJECT (fimcconvert, "[START]");
+  }
+#endif
+
+  dst_idx = fimcconvert->dst_buf_idx;
+
+  /* We have to make gem handle always and map for dst buffer */
+  /* allocate and map memory */
+  if (!gst_fimcconvert_tbm_create_and_map_bo (fimcconvert,
+          FIMCCONVERT_GEM_FOR_DST)) {
+    return FALSE;
+  }
+
+  if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS) {
+    GST_LOG_OBJECT (fimcconvert, "OutBuf :: buf_type == PADDR");
+
+    /* Get Y plane phy address of each gem handle for destination */
+    if (fimcconvert_drm_gem_get_phy_addr (fimcconvert->drm_fimc_fd,
+            fimcconvert->gem_info_dst[dst_idx][Y].gem_handle,
+            &fimcconvert->gem_info_dst[dst_idx][Y].phy_addr)) {
+      return FALSE;
+    }
+    if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1', '2')
+        || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'T', '1',
+            '2')) {
+      /* Get CBCR Plane phy address */
+      if (fimcconvert_drm_gem_get_phy_addr (fimcconvert->drm_fimc_fd,
+              fimcconvert->gem_info_dst[dst_idx][CB].gem_handle,
+              &fimcconvert->gem_info_dst[dst_idx][CB].phy_addr)) {
+        return FALSE;
+      }
+    } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4', '2',
+            '0')) {
+      /* CB Plane */
+      if (fimcconvert_drm_gem_get_phy_addr (fimcconvert->drm_fimc_fd,
+              fimcconvert->gem_info_dst[dst_idx][CB].gem_handle,
+              &fimcconvert->gem_info_dst[dst_idx][CB].phy_addr)) {
+        return FALSE;
+      }
+      /* CR Plane */
+      if (fimcconvert_drm_gem_get_phy_addr (fimcconvert->drm_fimc_fd,
+              fimcconvert->gem_info_dst[dst_idx][CR].gem_handle,
+              &fimcconvert->gem_info_dst[dst_idx][CR].phy_addr)) {
+        return FALSE;
+      }
+    }
+  } else if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD
+      || fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_TBM_BO) {
+    GST_LOG_OBJECT (fimcconvert, "OutBuf :: buf_type (%d)",
+        fimcconvert->buf_type);
+  }
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+#ifdef DEBUG_FOR_DV
+  if (total_converted_frame_count <= 10) {
+    GST_WARNING_OBJECT (fimcconvert, "[END]");
+  }
+#endif
+
+  return TRUE;
+}
+
+static void
+gst_fimcconvert_tbm_unmap_and_destroy_bo (GstFimcConvert * fimcconvert,
+    FimcConvertGemCreateType type, int index)
+{
+  int i = 0;
+  int tbm_ret = 0;
+  if (type == FIMCCONVERT_GEM_FOR_SRC) {
+    /* for standard colorspace format */
+    if (fimcconvert->gem_info_src_normal_fmt[index].bo) {
+      GST_LOG_OBJECT (fimcconvert, "SRC : (standard format) unmap src(%p)",
+          (void *) (unsigned long) fimcconvert->gem_info_src_normal_fmt[index].
+          usr_addr);
+      tbm_ret = tbm_bo_unmap (fimcconvert->gem_info_src_normal_fmt[index].bo);
+      if (tbm_ret == 0) {
+        GST_ERROR_OBJECT (fimcconvert,
+            "SRC : (standard format) failed to tbm_bo_unmap(bo:%p), index(%d)",
+            fimcconvert->gem_info_src_normal_fmt[index].bo, index);
+      }
+      GST_LOG_OBJECT (fimcconvert,
+          "SRC : (standard format) tbm_bo_unref(bo:%p), index(%d)",
+          fimcconvert->gem_info_src_normal_fmt[index].bo, index);
+      tbm_bo_unref (fimcconvert->gem_info_src_normal_fmt[index].bo);
+      memset (&fimcconvert->gem_info_src_normal_fmt[index], 0x00,
+          sizeof (GemInfoDst));
+    }
+    /* for samsung extension colorspace format */
+    for (i = 0; i < MM_VIDEO_BUFFER_MAX_PLANE - 1; i++) {
+      if (fimcconvert->gem_info_src[index][i].bo) {
+        memset (&fimcconvert->gem_info_src[index], 0x00, sizeof (GemInfoSrc));
+      }
+      if (fimcconvert->gem_info_src[index][i].dma_buf_fd
+          || fimcconvert->gem_info_src[index][i].phy_addr) {
+        GST_LOG_OBJECT (fimcconvert, "SRC : close gem_handle(%d)",
+            fimcconvert->gem_info_src[index][i].gem_handle);
+        fimcconvert_drm_close_gem (fimcconvert->drm_fimc_fd,
+            fimcconvert->gem_info_src[index][i].gem_handle);
+        memset (&fimcconvert->gem_info_src[index], 0x00, sizeof (GemInfoSrc));
+      }
+    }
+  } else if (type == FIMCCONVERT_GEM_FOR_DST) {
+    for (i = 0; i < MM_VIDEO_BUFFER_MAX_PLANE - 1; i++) {
+      if (fimcconvert->gem_info_dst[index][i].bo) {
+        GST_LOG_OBJECT (fimcconvert, "DST : unref dst(%p)",
+            (void *) (unsigned long) fimcconvert->gem_info_dst[index][i].
+            usr_addr);
+        tbm_bo_unref (fimcconvert->gem_info_dst[index][i].bo);
+      }
+      if (fimcconvert->gem_info_dst[index][i].dma_buf_fd) {
+        GST_LOG_OBJECT (fimcconvert, "DST : close fd(%d)",
+            fimcconvert->gem_info_dst[index][i].dma_buf_fd);
+        close (fimcconvert->gem_info_dst[index][i].dma_buf_fd);
+      }
+      memset (&fimcconvert->gem_info_dst[index][i], 0x00, sizeof (GemInfoDst));
+    }
+  }
+
+  return;
+}
+
+static gboolean
+gst_fimcconvert_tbm_create_and_map_bo (GstFimcConvert * fimcconvert,
+    FimcConvertGemCreateType type)
+{
+  tbm_bo bo;
+  tbm_bo_handle bo_handle_vaddr;
+  tbm_bo_handle bo_handle_gem;
+  guint src_idx = 0;
+  guint dst_idx = 0;
+  gint mem_option = 0;
+
+  g_return_val_if_fail (GST_IS_FIMCCONVERT (fimcconvert), FALSE);
+  g_return_val_if_fail (fimcconvert->drm_fimc_fd, -1);
+  g_return_val_if_fail (fimcconvert->dst_buf_size, -1);
+
+  src_idx = fimcconvert->src_buf_idx;
+  dst_idx = fimcconvert->dst_buf_idx;
+
+  if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS) {
+    mem_option = MEM_OP_NONCACHE_CONTIG;
+  } else {
+    mem_option = MEM_OP_NONCACHE_NONCONTIG;
+  }
+  GST_WARNING_OBJECT (fimcconvert,
+      "memory option=%d (2:NONCACHEABLE_NONCONTIG 3:NONCACHEABLE_CONTIG)",
+      mem_option);
+
+  if (type == FIMCCONVERT_GEM_FOR_SRC) {
+
+    GST_DEBUG_OBJECT (fimcconvert, "create and map bo for SRC");
+
+    g_return_val_if_fail (fimcconvert->src_buf_size, -1);
+
+    /* allocate and map memory */
+    FIMCCONVERT_TBM_BO_ALLOC_AND_MAP (bo, bo_handle_vaddr,
+        fimcconvert->src_buf_size, mem_option);
+
+    /* get gem handle */
+    FIMCCONVERT_TBM_BO_GET_GEM_HANDLE (bo, bo_handle_gem);
+
+    /* update information */
+    fimcconvert->gem_info_src_normal_fmt[src_idx].gem_handle =
+        bo_handle_gem.u32;
+    fimcconvert->gem_info_src_normal_fmt[src_idx].usr_addr =
+        bo_handle_vaddr.ptr;
+    fimcconvert->gem_info_src_normal_fmt[src_idx].size =
+        fimcconvert->src_buf_size;
+    fimcconvert->gem_info_src_normal_fmt[src_idx].bo = bo;
+    GST_DEBUG_OBJECT (fimcconvert, "gem_handle=%u, user addr=%p, size=%u",
+        bo_handle_gem.u32, bo_handle_vaddr.ptr, fimcconvert->src_buf_size);
+
+  } else if (type == FIMCCONVERT_GEM_FOR_DST) {
+
+    GST_DEBUG_OBJECT (fimcconvert, "create and map bo for DST");
+
+    g_return_val_if_fail (fimcconvert->dst_buf_size, -1);
+    g_return_val_if_fail (fimcconvert->dst_caps_width, -1);
+    g_return_val_if_fail (fimcconvert->dst_caps_height, -1);
+
+    int y_size = 0;
+    int cb_size = 0;
+    int cr_size = 0;
+    int width = 0, height = 0;  //dst caps witdh, height
+    width = fimcconvert->dst_caps_width;
+    height = fimcconvert->dst_caps_height;
+
+    /* for Y plane */
+    /* initialize structure for gem create */
+
+    switch (fimcconvert->dst_fourcc_format) {
+      case GST_MAKE_FOURCC ('S', 'T', '1', '2'):
+        GST_LOG ("PSH");
+        y_size = ALIGN_TO_8KB (ALIGN_TO_128B (width) * ALIGN_TO_32B (height));
+        break;
+      case GST_MAKE_FOURCC ('S', 'N', '1', '2'):
+        y_size = ALIGN_TO_16B (width) * ALIGN_TO_16B (height);
+        break;
+      case GST_MAKE_FOURCC ('S', '4', '2', '0'):
+      {
+        if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS)
+          y_size = ALIGN_TO_16B (width) * ALIGN_TO_2B (height);
+        else
+          y_size = (ALIGN_TO_16B (width) * ALIGN_TO_2B (height) * 3) >> 1;
+      }
+        break;
+      case GST_MAKE_FOURCC ('N', 'V', '1', '2'):
+      case GST_MAKE_FOURCC ('I', '4', '2', '0'):
+        y_size = fimcconvert->dst_buf_size;
+        break;
+      case GST_MAKE_FOURCC ('S', 'U', 'Y', '2'):
+      case GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'):
+      case GST_MAKE_FOURCC ('I', 'T', 'L', 'V'):
+      case GST_MAKE_FOURCC ('S', 'Y', 'V', 'Y'):
+      case GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'):
+        y_size = (ALIGN_TO_16B (width) * ALIGN_TO_2B (height) * 2);
+        break;
+      default:
+        /* maybe, it's rgb case */
+        y_size = fimcconvert->dst_buf_size;
+        break;
+    }
+    GST_INFO ("Y Plane size is %d", y_size);
+
+    /* allocate and map memory */
+    FIMCCONVERT_TBM_BO_ALLOC (bo, y_size, mem_option);
+    FIMCCONVERT_TBM_BO_GET_VADDR (bo, bo_handle_vaddr, y_size);
+
+    /* get gem handle */
+    FIMCCONVERT_TBM_BO_GET_GEM_HANDLE (bo, bo_handle_gem);
+
+    /* update information */
+    fimcconvert->gem_info_dst[dst_idx][Y].gem_handle = bo_handle_gem.u32;
+    fimcconvert->gem_info_dst[dst_idx][Y].usr_addr = bo_handle_vaddr.ptr;
+    fimcconvert->gem_info_dst[dst_idx][Y].size = y_size;
+    fimcconvert->gem_info_dst[dst_idx][Y].bo = bo;
+
+    if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+      if (fimcconvert_drm_convert_gemhandle_to_fd (fimcconvert->drm_fimc_fd,
+              fimcconvert->gem_info_dst[dst_idx][Y].gem_handle,
+              &fimcconvert->gem_info_dst[dst_idx][Y].dma_buf_fd)) {
+        return FALSE;
+      }
+    }
+    GST_DEBUG_OBJECT (fimcconvert, "Y: gem_handle=%u, user addr=%p, size=%u",
+        bo_handle_gem.u32, bo_handle_vaddr.ptr, y_size);
+
+    /* SN12, ST12 need to get Cb plane.
+       S420 need to get cb and Cr plane with PADDR. */
+    if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1', '2')
+        || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'T', '1',
+            '2')
+        || ((fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS)
+            && fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4', '2',
+                '0'))) {
+
+      /* for CB(CR) plane */
+      /* initialize structure for gem create */
+      if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'T', '1',
+              '2')) {
+        /* for cbcr plane */
+        GST_DEBUG_OBJECT (fimcconvert, "It's ST12, set CBCR plane");
+        cb_size =
+            ALIGN_TO_8KB (ALIGN_TO_128B (width) * ALIGN_TO_32B (height >> 1));
+      } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N',
+              '1', '2')) {
+        /* for cbcr plane */
+        cb_size = y_size >> 1;
+      } else if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4',
+              '2', '0')) {
+        cb_size = y_size >> 2;
+      }
+      GST_INFO ("Cb Plane size is %d", cb_size);
+
+      /* allocate and map memory */
+      FIMCCONVERT_TBM_BO_ALLOC (bo, cb_size, mem_option);
+      FIMCCONVERT_TBM_BO_GET_VADDR (bo, bo_handle_vaddr, cb_size);
+
+      /* get gem handle */
+      FIMCCONVERT_TBM_BO_GET_GEM_HANDLE (bo, bo_handle_gem);
+
+      /* update information */
+      fimcconvert->gem_info_dst[dst_idx][CB].gem_handle = bo_handle_gem.u32;
+      fimcconvert->gem_info_dst[dst_idx][CB].usr_addr = bo_handle_vaddr.ptr;
+      fimcconvert->gem_info_dst[dst_idx][CB].size = cb_size;
+      fimcconvert->gem_info_dst[dst_idx][CB].bo = bo;
+
+      if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+        if (fimcconvert_drm_convert_gemhandle_to_fd (fimcconvert->drm_fimc_fd,
+                fimcconvert->gem_info_dst[dst_idx][CB].gem_handle,
+                &fimcconvert->gem_info_dst[dst_idx][CB].dma_buf_fd)) {
+          return FALSE;
+        }
+      }
+      GST_DEBUG_OBJECT (fimcconvert,
+          "CB(CR): gem_handle=%u, user addr=%p, size=%u", bo_handle_gem.u32,
+          bo_handle_vaddr.ptr, cb_size);
+
+      /* for CR plane */
+      if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4', '2',
+              '0')) {
+        cr_size = cb_size;
+        GST_INFO ("Cr Plane size is %d", cr_size);
+
+        /* allocate and map memory */
+        FIMCCONVERT_TBM_BO_ALLOC (bo, cr_size, mem_option);
+        FIMCCONVERT_TBM_BO_GET_VADDR (bo, bo_handle_vaddr, cr_size);
+
+        /* get gem handle */
+        FIMCCONVERT_TBM_BO_GET_GEM_HANDLE (bo, bo_handle_gem);
+
+        /* update information */
+        fimcconvert->gem_info_dst[dst_idx][CR].gem_handle = bo_handle_gem.u32;
+        fimcconvert->gem_info_dst[dst_idx][CR].usr_addr = bo_handle_vaddr.ptr;
+        fimcconvert->gem_info_dst[dst_idx][CR].size = cr_size;
+        fimcconvert->gem_info_dst[dst_idx][CR].bo = bo;
+
+        if (fimcconvert->buf_type == MM_VIDEO_BUFFER_TYPE_DMABUF_FD) {
+          if (fimcconvert_drm_convert_gemhandle_to_fd (fimcconvert->drm_fimc_fd,
+                  fimcconvert->gem_info_dst[dst_idx][CR].gem_handle,
+                  &fimcconvert->gem_info_dst[dst_idx][CR].dma_buf_fd)) {
+            return FALSE;
+          }
+        }
+        GST_DEBUG_OBJECT (fimcconvert,
+            "CR: gem_handle=%u, user addr=%p, size=%u", bo_handle_gem.u32,
+            bo_handle_vaddr.ptr, cr_size);
+      }
+    }
+  } else {
+    GST_ERROR ("invalid type(%d) for gem creation", type);
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+int
+util_write_rawdata (const char *file, const void *data, unsigned int size)
+{
+  FILE *fp;
+
+  fp = fopen (file, "wb");
+  if (fp == NULL)
+    return -1;
+
+  fwrite ((char *) data, sizeof (char), size, fp);
+  fclose (fp);
+
+  return 0;
+}
+
+static GstFlowReturn
+gst_fimcconvert_transform (GstBaseTransform * trans, GstBuffer * inbuf,
+    GstBuffer * outbuf)
+{
+  int ret = 0;
+  int gret = TRUE;
+
+  GstFimcConvert *fimcconvert = NULL;
+  MMVideoBuffer *mm_video_buf = NULL;
+  GstMemory *mm_video_buf_memory = NULL;
+  GstMapInfo mm_video_buf_info = GST_MAP_INFO_INIT;
+  guint src_idx = 0;
+  guint dst_idx = 0;
+
+  struct timeval timeout = {.tv_sec = 3,.tv_usec = 0 };
+  fd_set fds;
+
+  fimcconvert = GST_FIMCCONVERT (trans);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[START]");
+
+  /* check if all destination buffers are full */
+  if (!gst_fimcconvert_is_buffer_available (fimcconvert)) {
+    GST_DEBUG_OBJECT (fimcconvert, "[END]");
+    return GST_FLOW_ERROR;
+  }
+
+  /* Set src/dst index */
+  src_idx = fimcconvert->src_buf_idx;
+  dst_idx = fimcconvert->dst_buf_idx;
+
+  g_mutex_lock (fimcconvert->fd_lock);
+  g_mutex_lock (instance_lock);
+
+#ifdef DEBUG_FOR_DV
+  if (total_converted_frame_count <= 10) {
+    GST_WARNING_OBJECT (fimcconvert, "is_src_format_std(%d), inbuf(%p)",
+        fimcconvert->is_src_format_std, inbuf);
+  }
+#endif
+  if (!fimcconvert->is_src_format_std) {
+    GST_DEBUG_OBJECT (fimcconvert, "Samsung EXT format");
+    /* get an mm_video_buf of input buffer */
+    if (gst_buffer_n_memory (inbuf) < 2) {
+      GST_WARNING_OBJECT (fimcconvert, "failed to get MMVideoBuffer");
+      goto SKIP_CONVERTING;
+    }
+  }
+
+  /* initializing DRM IPP */
+  if (!fimcconvert->is_drm_inited) {
+    GST_DEBUG_OBJECT (fimcconvert, "initializing DRM IPP");
+
+    /* Open DRM */
+    if (!gst_fimcconvert_drm_ipp_init (fimcconvert)) {
+      GST_ERROR_OBJECT (fimcconvert,
+          "failed to gst_fimcconvert_drm_ipp_init()");
+      g_mutex_unlock (instance_lock);
+      g_mutex_unlock (fimcconvert->fd_lock);
+      return GST_FLOW_ERROR;
+    }
+  }
+
+  /* Do below only when first round */
+  if (fimcconvert->is_random_src_idx) {
+    GST_DEBUG_OBJECT (fimcconvert, "======= Set for SRC =======");
+    if (fimcconvert->is_src_format_std) {
+      /* if src colorspace format is standard format, do below just once. */
+      if (!fimcconvert->gem_info_src_normal_fmt[0].gem_handle) {
+        gret = gst_fimcconvert_drm_prepare_src_buf (fimcconvert, inbuf);
+        if (!gret) {
+          if (!fimcconvert->do_skip) {
+            goto ERROR;
+          }
+        }
+      }
+    } else {
+      gret = gst_fimcconvert_drm_prepare_src_buf (fimcconvert, inbuf);
+      if (!gret) {
+        if (!fimcconvert->do_skip) {
+          goto ERROR;
+        }
+      }
+    }
+    GST_DEBUG_OBJECT (fimcconvert, "==========================");
+  } else if (fimcconvert->is_first_set_for_src) {
+    /* Check if src buffer from decoder has new phy address */
+    if (gst_fimcconvert_check_new_src (fimcconvert, inbuf)) {
+      GST_DEBUG_OBJECT (fimcconvert, "=== First Set for SRC : Round %d ===",
+          src_idx + 1);
+      gret = gst_fimcconvert_drm_prepare_src_buf (fimcconvert, inbuf);
+      if (!gret) {
+        if (!fimcconvert->do_skip) {
+          goto ERROR;
+        }
+      }
+      GST_DEBUG_OBJECT (fimcconvert, "==========================");
+    } else {
+      /* check if this buffer should be skipped */
+      if (fimcconvert->do_skip) {
+        GST_WARNING_OBJECT (fimcconvert,
+            "something wrong, gem_handle_y is 0. maybe this src buffer has invalid paddr/fd");
+        /* set is_random_src_idx to TRUE and reset all buffers */
+        fimcconvert->is_random_src_idx = TRUE;
+        g_mutex_unlock (instance_lock);
+        g_mutex_unlock (fimcconvert->fd_lock);
+        gst_fimcconvert_reset (fimcconvert);
+        g_mutex_lock (fimcconvert->fd_lock);
+        g_mutex_lock (instance_lock);
+      } else {
+        GST_INFO_OBJECT (fimcconvert,
+            "found number of decoder output buffer(%d)", src_idx);
+        fimcconvert->src_buf_num = src_idx;
+        fimcconvert->is_first_set_for_src = FALSE;
+        fimcconvert->src_buf_idx = src_idx = 0;
+      }
+    }
+  }
+
+  /* check if this buffer should be skipped */
+  if (fimcconvert->do_skip) {
+    goto SKIP_CONVERTING;
+  }
+
+  if (fimcconvert->is_first_set_for_dst) {
+    GST_DEBUG_OBJECT (fimcconvert, "=== First Set for DST : Round %d ===",
+        dst_idx + 1);
+    gret = gst_fimcconvert_drm_prepare_dst_buf (fimcconvert);
+    if (!gret) {
+      goto ERROR;
+    }
+    GST_DEBUG_OBJECT (fimcconvert, "====================================");
+  }
+
+  /* Check if src data's colorspace is normal format */
+  if (fimcconvert->is_src_format_std) {
+    GST_INFO_OBJECT (fimcconvert,
+        "InBuf :: It's a standard format(%d), Do memory copy",
+        fimcconvert->src_drm_format);
+    gst_buffer_extract (inbuf, 0,
+        (void *) (unsigned int) fimcconvert->gem_info_src_normal_fmt[src_idx].
+        usr_addr, gst_buffer_get_size (inbuf));
+#ifdef USE_CACHABLE_GEM
+    fimcconvert_gem_flush_cache (fimcconvert->drm_fimc_fd);
+#endif
+
+  }
+
+  /* Enqueue src buffer */
+  GST_LOG_OBJECT (fimcconvert,
+      "enqueue src buffer : src_idx(%d), gem_handle_y(%u), gem_handle_cb(%u), gem_handle_cr(%u)",
+      src_idx,
+      fimcconvert->gem_info_src[src_idx][Y].gem_handle,
+      fimcconvert->gem_info_src[src_idx][CB].gem_handle,
+      fimcconvert->gem_info_src[src_idx][CR].gem_handle);
+  ret = exynos_drm_ipp_queue_buf (fimcconvert->drm_fimc_fd,
+      EXYNOS_DRM_OPS_SRC,
+      IPP_BUF_ENQUEUE,
+      fimcconvert->ipp_prop_id,
+      src_idx,
+      fimcconvert->gem_info_src[src_idx][Y].gem_handle,
+      fimcconvert->gem_info_src[src_idx][CB].gem_handle,
+      fimcconvert->gem_info_src[src_idx][CR].gem_handle);
+  if (ret) {
+    GST_ERROR_OBJECT (fimcconvert,
+        "src buffer map to IPP failed, src_buf_idx(%d)", src_idx);
+    goto ERROR;
+  }
+
+  /* Enqueue dst buffer */
+  GST_LOG_OBJECT (fimcconvert,
+      "enqueue dst buffer : dst_idx(%d), gem_handle_y(%u), gem_handle_cb(%u), gem_handle_cr(%u)",
+      dst_idx,
+      fimcconvert->gem_info_dst[dst_idx][Y].gem_handle,
+      fimcconvert->gem_info_dst[dst_idx][CB].gem_handle,
+      fimcconvert->gem_info_dst[dst_idx][CR].gem_handle);
+  ret = exynos_drm_ipp_queue_buf (fimcconvert->drm_fimc_fd,
+      EXYNOS_DRM_OPS_DST,
+      IPP_BUF_ENQUEUE,
+      fimcconvert->ipp_prop_id,
+      dst_idx,
+      fimcconvert->gem_info_dst[dst_idx][Y].gem_handle,
+      fimcconvert->gem_info_dst[dst_idx][CB].gem_handle,
+      fimcconvert->gem_info_dst[dst_idx][CR].gem_handle);
+  if (ret) {
+    GST_ERROR_OBJECT (fimcconvert,
+        "dst buffer map to IPP failed, dst_buf_idx(%d)", dst_idx);
+    goto ERROR;
+  }
+
+  /* Set IPP to start */
+  if (!fimcconvert->is_drm_inited) {
+    if (!gst_fimcconvert_drm_ipp_ctrl (fimcconvert, FIMCCONVERT_IPP_CTRL_START)) {
+      GST_ERROR_OBJECT (fimcconvert,
+          "failed to gst_fimcconvert_drm_ipp_ctrl(START)");
+      goto ERROR;
+    }
+  }
+
+  /* Wait using select */
+  FD_ZERO (&fds);
+  FD_SET (0, &fds);
+  FD_SET (fimcconvert->drm_fimc_fd, &fds);
+  ret = select (fimcconvert->drm_fimc_fd + 1, &fds, NULL, NULL, &timeout);
+  if (ret == 0) {
+    GST_ERROR_OBJECT (fimcconvert, "select timed out..");
+    goto ERROR;
+  }
+  if (ret == -1) {
+    GST_ERROR_OBJECT (fimcconvert, "select error, error num(%d)", errno);
+    goto ERROR;
+  }
+
+  /* Event handling */
+  {
+    char buffer[MAX_IPP_EVENT_BUFFER_SIZE] = { 0 };
+    int len = 0;
+    int i = 0;
+    struct drm_event *e;
+    struct drm_exynos_ipp_event *ipp_event;
+
+#ifdef DEBUG_FOR_DV
+    if (total_converted_frame_count <= 10) {
+      GST_WARNING_OBJECT (fimcconvert, "before reading IPP event (no.%d)",
+          total_converted_frame_count + 1);
+    }
+#endif
+
+    len =
+        read (fimcconvert->drm_fimc_fd, buffer, MAX_IPP_EVENT_BUFFER_SIZE - 1);
+    if (len == 0 || len < sizeof *e) {
+      GST_ERROR_OBJECT (fimcconvert, "lengh(%d) is not valid", len);
+      goto ERROR;
+    }
+
+    while (i < len) {
+      e = (struct drm_event *) &buffer[i];
+      switch (e->type) {
+        case DRM_EXYNOS_IPP_EVENT:
+          ipp_event = (struct drm_exynos_ipp_event *) e;
+          src_idx = ipp_event->buf_id[EXYNOS_DRM_OPS_SRC];
+          dst_idx = ipp_event->buf_id[EXYNOS_DRM_OPS_DST];
+          GST_LOG_OBJECT (fimcconvert,
+              "got DRM_EXYNOS_IPP_EVENT : src_buf_idx(%d), dst_buf_idx(%d)",
+              src_idx, dst_idx);
+          break;
+        default:
+          GST_WARNING_OBJECT (fimcconvert, "got DRM_EXYNOS Other EVENT(%d)",
+              e->type);
+          break;
+      }
+      i += e->length;
+    }
+
+#ifdef DEBUG_FOR_DV
+    if (total_converted_frame_count <= 10) {
+      GST_WARNING_OBJECT (fimcconvert,
+          "after reading IPP event (no.%d), got DRM_EXYNOS_IPP_EVENT : src_buf_idx(%d), dst_buf_idx(%d)",
+          total_converted_frame_count + 1, src_idx, dst_idx);
+    }
+#endif
+  }
+
+  /* Update MMVideoBuffer information for outbuf */
+  if (fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'N', '1', '2')
+      || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'T', '1', '2')
+      || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'U', 'Y', 'V')
+      || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'U', 'Y', '2')
+      || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'Y', 'V', 'Y')
+      || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', '4', '2', '0')
+      || fimcconvert->dst_fourcc_format == GST_MAKE_FOURCC ('S', 'R', '3', '2')) {
+    if (!gst_fimcconvert_set_mm_video_buf_info_for_dst (fimcconvert, outbuf)) {
+      GST_ERROR_OBJECT (fimcconvert,
+          "set MMVideoBuffer information failed..idx(%d)", dst_idx);
+      goto ERROR;
+    }
+  }
+
+  if (fimcconvert->is_random_src_idx) {
+    if (!fimcconvert->is_src_format_std) {
+      gst_fimcconvert_tbm_unmap_and_destroy_bo (fimcconvert,
+          FIMCCONVERT_GEM_FOR_SRC, src_idx);
+    }
+  } else {
+    fimcconvert->src_buf_idx++;
+    if (fimcconvert->src_buf_idx == fimcconvert->src_buf_num
+        || fimcconvert->src_buf_idx == MAX_SRC_BUF_NUM) {
+      if (fimcconvert->is_first_set_for_src) {
+        if (fimcconvert->src_buf_idx == MAX_SRC_BUF_NUM) {
+        }
+        GST_WARNING_OBJECT (fimcconvert, "it reached MAX_SRC_BUF_NUM(%d)",
+            fimcconvert->src_buf_idx);
+        fimcconvert->is_first_set_for_src = FALSE;
+      }
+      fimcconvert->src_buf_idx = 0;
+    }
+  }
+  fimcconvert->dst_buf_idx++;
+  if (fimcconvert->dst_buf_idx == fimcconvert->num_of_dst_buffers) {
+    if (fimcconvert->is_first_set_for_dst) {
+      fimcconvert->is_first_set_for_dst = FALSE;
+    }
+    fimcconvert->dst_buf_idx = 0;
+  }
+
+  {
+    GstFimcConvertBuffer *fimc_buf = NULL;
+    GstMemory *fimc_memory =
+        gst_buffer_peek_memory (outbuf, gst_buffer_n_memory (outbuf) - 1);
+    GstMapInfo fimc_info = GST_MAP_INFO_INIT;
+    gst_memory_map (fimc_memory, &fimc_info, GST_MAP_READ);
+    fimc_buf = (GstFimcConvertBuffer *) fimc_info.data;
+    gst_memory_unmap (fimc_memory, &fimc_info);
+    gst_buffer_prepend_memory (outbuf,
+        gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
+            (void *) (unsigned long) fimcconvert->gem_info_dst[dst_idx][Y].
+            usr_addr, fimc_buf->actual_size, 0, fimc_buf->actual_size, NULL,
+            NULL));
+#ifdef DUMP_IMG
+    int ret;
+    ret = util_write_rawdata ("dump_raw_dst_img",
+        fimcconvert->gem_info_dst[dst_idx][Y].usr_addr, fimc_buf->actual_size);
+    if (ret) {
+      GST_ERROR_OBJECT (fimcconvert, "util_write_rawdata() failed");
+    }
+#endif
+  }
+  if (!fimcconvert->is_drm_inited) {
+    fimcconvert->is_drm_inited = TRUE;
+    FIMCCONVERT_SEND_CUSTOM_EVENT_TO_SINK_WITH_DATA (1);
+  }
+#ifdef USE_CACHABLE_GEM
+  __ta__ ("    flush_cache() after IPP",
+      fimcconvert_gem_flush_cache (fimcconvert->drm_fimc_fd););
+#endif
+  g_mutex_unlock (instance_lock);
+  g_mutex_unlock (fimcconvert->fd_lock);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+
+#ifdef DEBUG_FOR_DV
+  if (++total_converted_frame_count <= 10) {
+    GST_WARNING_OBJECT (fimcconvert,
+        "%2dth of IPP operation, buffer(%p)", total_converted_frame_count,
+        outbuf);
+  }
+#endif
+
+  return GST_FLOW_OK;
+
+SKIP_CONVERTING:
+  /* skipping converting in case of incoming src buf's information is not valid */
+  GST_WARNING_OBJECT (fimcconvert, "SKIPPING CONVERTING..");
+
+  fimcconvert->do_skip = FALSE;
+
+  g_mutex_lock (fimcconvert->buf_idx_lock);
+  if (fimcconvert->dst_buf_num > 0) {
+    fimcconvert->dst_buf_num--;
+  }
+  g_mutex_unlock (fimcconvert->buf_idx_lock);
+
+  g_mutex_unlock (instance_lock);
+  g_mutex_unlock (fimcconvert->fd_lock);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+  return GST_BASE_TRANSFORM_FLOW_DROPPED;
+
+ERROR:
+  g_mutex_unlock (instance_lock);
+  g_mutex_unlock (fimcconvert->fd_lock);
+
+  gst_fimcconvert_reset (fimcconvert);
+
+  GST_DEBUG_OBJECT (fimcconvert, "[END]");
+  return GST_FLOW_ERROR;
+}
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+  GST_DEBUG_CATEGORY_INIT (fimcconvert_debug, "fimcconvert", 0,
+      "Fimc Converter");
+  return gst_element_register (plugin, "fimcconvert", GST_RANK_NONE,
+      GST_TYPE_FIMCCONVERT);
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+    GST_VERSION_MINOR,
+    fimcconvert,
+    "Fimc Converter",
+    plugin_init, VERSION, "LGPL", "Samsung Electronics Co",
+    "http://www.samsung.com")
diff --git a/fimcconvert/src/gstfimcconvert.h b/fimcconvert/src/gstfimcconvert.h
new file mode 100755 (executable)
index 0000000..e094de8
--- /dev/null
@@ -0,0 +1,258 @@
+/*
+ * FimcConvert
+ *
+ * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Sangchul Lee <sc11.lee@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifndef __GST_FIMC_CONVERT_H__
+#define __GST_FIMC_CONVERT_H__
+
+#include <stdio.h>
+#include <gst/gst.h>
+#include <gst/base/gstbasetransform.h>
+#include <string.h>
+#include <gst/video/video.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <linux/vt.h>
+#include <error.h>
+#include <mm_types.h>
+#include "fimc_drm_api.h"
+
+G_BEGIN_DECLS GST_DEBUG_CATEGORY_EXTERN (fimcconvert_debug);
+#define GST_CAT_DEFAULT fimcconvert_debug
+
+#define GST_TYPE_FIMCCONVERT (gst_fimcconvert_get_type())
+#define GST_FIMCCONVERT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_FIMCCONVERT,GstFimcConvert))
+#define GST_FIMCCONVERT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_FIMCCONVERT,GstFimcConvertClass))
+#define GST_IS_FIMCCONVERT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_FIMCCONVERT))
+#define GST_IS_FIMCCONVERT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_FIMCCONVERT))
+
+typedef struct _GstFimcConvert GstFimcConvert;
+typedef struct _GstFimcConvertClass GstFimcConvertClass;
+typedef struct _GstFimcConvertBuffer GstFimcConvertBuffer;
+typedef struct _GemInfoSrc GemInfoSrc;
+typedef struct _GemInfoDst GemInfoDst;
+
+/* macro for sending custom event ********************************************/
+#define FIMCCONVERT_SEND_CUSTOM_EVENT_TO_SINK_WITH_DATA( x_addr ) \
+do \
+{ \
+  GstEvent *event = NULL; \
+  GstStructure *st = NULL; \
+  st =  gst_structure_new ("GstStructureForCustomEvent", "data-addr", G_TYPE_UINT, x_addr, NULL); \
+  if (!st) { \
+    GST_WARNING_OBJECT(fimcconvert,"structure make failed"); \
+  } \
+  GST_DEBUG ("set data addr(%x) in GstStructure",x_addr); \
+  event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_OOB, st); \
+  if (!event) { \
+  GST_WARNING_OBJECT(fimcconvert,"event make failed"); \
+  } \
+  if (GST_IS_PAD (fimcconvert->src_pad)) { \
+    if (!gst_pad_push_event(fimcconvert->src_pad, event)) { \
+      GST_DEBUG_OBJECT(fimcconvert, "sending event failed, but keep going.."); \
+    } \
+  } \
+}while(0)
+
+/* macro related to TBM ******************************************************/
+#define FIMCCONVERT_TBM_BO_ALLOC( x_bo, x_size, x_mem_option ) \
+do \
+{ \
+  x_bo = tbm_bo_alloc (fimcconvert->tbm, x_size, x_mem_option); \
+  if (!x_bo) { \
+    GST_ERROR_OBJECT(fimcconvert,"failed to tbm_bo_alloc(), size(%d)", x_size); \
+    return FALSE; \
+  } \
+}while(0)
+
+#define FIMCCONVERT_TBM_BO_ALLOC_AND_MAP( x_bo, x_bo_handle, x_size, x_mem_option ) \
+do \
+{ \
+  x_bo = tbm_bo_alloc (fimcconvert->tbm, x_size, x_mem_option); \
+  if (!x_bo) { \
+    GST_ERROR_OBJECT(fimcconvert,"failed to tbm_bo_alloc(), size(%d)", x_size); \
+    return FALSE; \
+  } \
+  x_bo_handle = tbm_bo_map (x_bo, TBM_DEVICE_CPU, TBM_OPTION_READ | TBM_OPTION_WRITE); \
+  if (!x_bo_handle.ptr) { \
+    GST_ERROR_OBJECT(fimcconvert,"failed to tbm_bo_map(), bo(%p)", x_bo); \
+    return FALSE; \
+  } \
+  memset (x_bo_handle.ptr, 0x0, x_size); \
+}while(0)
+
+#define FIMCCONVERT_TBM_BO_GET_GEM_HANDLE( x_bo, x_bo_handle ) \
+do \
+{ \
+  x_bo_handle = tbm_bo_get_handle(x_bo, TBM_DEVICE_2D); \
+  if (!x_bo_handle.u32) { \
+    GST_ERROR_OBJECT(fimcconvert,"failed to tbm_bo_get_handle(GEM_HANDLE), bo(%p), gem_handle(%d)", x_bo, x_bo_handle.u32); \
+    return FALSE; \
+  } else { \
+    GST_LOG_OBJECT(fimcconvert,"tbm_bo_get_handle(GEM_HANDLE) finished, bo(%p), gem_handle(%d)", x_bo, x_bo_handle.u32); \
+  } \
+}while(0)
+
+#define FIMCCONVERT_TBM_BO_GET_VADDR( x_bo, x_bo_handle, x_size ) \
+do \
+{ \
+  x_bo_handle = tbm_bo_get_handle(x_bo, TBM_DEVICE_CPU); \
+  if (!x_bo_handle.ptr) { \
+    GST_ERROR_OBJECT(fimcconvert,"failed to tbm_bo_get_handle(VADDR), bo(%p), vaddr(%p)", x_bo, x_bo_handle.ptr); \
+    return FALSE; \
+  } else { \
+    memset (x_bo_handle.ptr, 0x0, x_size); \
+    GST_LOG_OBJECT(fimcconvert,"tbm_bo_get_handle(VADDR) finished, bo(%p), vaddr(%p)", x_bo, x_bo_handle.ptr); \
+  } \
+}while(0)
+
+/* max channel count *********************************************************/
+
+#define MM_VIDEO_BUFFER_MAX_PLANE         (4)
+
+/*Y  PLANE */
+#define Y                 0
+/*Cb PLANE */
+#define CB                1
+/*Cr PLAME */
+#define CR                2
+
+
+#define FIMCCONVERT_DST_WIDTH_DEFAULT 0
+#define FIMCCONVERT_DST_WIDTH_MIN 0
+#define FIMCCONVERT_DST_WIDTH_MAX 32767
+#define FIMCCONVERT_DST_HEIGHT_DEFAULT 0
+#define FIMCCONVERT_DST_HEIGHT_MIN 0
+#define FIMCCONVERT_DST_HEIGHT_MAX 32767
+#define FIMCCONVERT_DST_BUFFER_MIN 2
+#define FIMCCONVERT_DST_BUFFER_DEFAULT 3
+#define FIMCCONVERT_DST_BUFFER_MAX 12
+
+#define SRC_BUF_NUM_FOR_STD_FMT  6      /* fixed number of buffer for standard colorspace format */
+#define MAX_SRC_BUF_NUM          12     /* Max number of upstream src plugins's buffer */
+#define MAX_DST_BUF_NUM          FIMCCONVERT_DST_BUFFER_MAX
+
+/* Dump raw img (src and dst) */
+//#define DUMP_IMG
+
+//#define USE_TBM
+
+#define MEM_OP_NONCACHE_NONCONTIG ( TBM_BO_DEFAULT | TBM_BO_NONCACHABLE )
+#define MEM_OP_NONCACHE_CONTIG    ( TBM_BO_SCANOUT | TBM_BO_NONCACHABLE )
+
+struct _GstFimcConvertBuffer
+{
+  GstBuffer *buffer;
+  GstFimcConvert *fimcconvert;
+  guint actual_size;
+};
+
+struct _GemInfoSrc
+{
+  unsigned int gem_handle;
+  uint64_t phy_addr;
+  int dma_buf_fd;
+  tbm_bo bo;
+  uint64_t size;
+};
+
+struct _GemInfoDst
+{
+  unsigned int gem_handle;
+  uint64_t usr_addr;
+  uint64_t phy_addr;
+  int dma_buf_fd;
+  tbm_bo bo;
+  uint64_t size;
+};
+
+struct _GstFimcConvert
+{
+  GstBaseTransform element;
+  GstPad *src_pad;
+
+  /* Src paramters */
+  gint in_caps_width;
+  gint in_caps_height;
+  guint src_buf_size;    /**< for a standard colorspace format */
+  guint32 src_drm_format;    /**< fourcc colorspace format for src */
+  gboolean is_src_format_std;   /*is standard format */
+
+  /* Dst paramters */
+  gint dst_caps_width;
+  gint dst_caps_height;
+  guint dst_buf_size;
+  guint32 dst_drm_format;    /**< fourcc colorspace format for dst */
+  guint32 dst_fourcc_format;    /**< fourcc colorspace format of GST */
+  gchar *dst_format_name;
+
+  /* Properties */
+  guint rotate_ang;
+  gint dst_width;
+  gint dst_height;
+  gint dst_flip;
+  gboolean is_random_src_idx;
+  guint num_of_dst_buffers;
+
+  /* DRM/GEM information */
+  gint drm_fimc_fd;
+  guint32 ipp_prop_id;
+  GemInfoSrc gem_info_src[MAX_SRC_BUF_NUM][MM_VIDEO_BUFFER_MAX_PLANE];
+  GemInfoDst gem_info_src_normal_fmt[MAX_SRC_BUF_NUM];
+  GemInfoDst gem_info_dst[MAX_DST_BUF_NUM][MM_VIDEO_BUFFER_MAX_PLANE];
+  MMVideoBufferType buf_type;
+
+  /* Tizen Buffer Manager */
+  tbm_bufmgr tbm;
+  gint drm_tbm_fd;
+
+  gboolean do_skip;
+  gboolean is_same_caps;
+  gboolean is_drm_inited;
+  gboolean is_first_set_for_src;
+  gboolean is_first_set_for_dst;
+  guint src_buf_num;
+  guint src_buf_idx;
+  guint dst_buf_num;
+  guint dst_buf_idx;
+
+  /* JPEG data */
+  void *jpeg_data;
+  int jpeg_data_size;
+
+  GMutex *fd_lock;
+  GMutex *buf_idx_lock;
+};
+
+struct _GstFimcConvertClass
+{
+  GstBaseTransformClass parent_class;
+};
+
+GType gst_fimcconvert_get_type (void);
+
+G_END_DECLS
+#endif /* __GST_FIMC_CONVERT_H__ */
diff --git a/gst-autogen.sh b/gst-autogen.sh
new file mode 100755 (executable)
index 0000000..7b31212
--- /dev/null
@@ -0,0 +1,308 @@
+# a silly hack that generates autoregen.sh but it's handy
+# Remove the old autoregen.sh first to create a new file,
+# as the current one may be being read by the shell executing
+# this script.
+if [ -f "autoregen.sh" ]; then
+  rm autoregen.sh
+fi
+echo "#!/bin/sh" > autoregen.sh
+echo "./autogen.sh $@ \$@" >> autoregen.sh
+chmod +x autoregen.sh
+
+# helper functions for autogen.sh
+
+debug ()
+# print out a debug message if DEBUG is a defined variable
+{
+  if test ! -z "$DEBUG"
+  then
+    echo "DEBUG: $1"
+  fi
+}
+
+version_check ()
+# check the version of a package
+# first argument : package name (executable)
+# second argument : optional path where to look for it instead
+# third argument : source download url
+# rest of arguments : major, minor, micro version
+# all consecutive ones : suggestions for binaries to use
+# (if not specified in second argument)
+{
+  PACKAGE=$1
+  PKG_PATH=$2
+  URL=$3
+  MAJOR=$4
+  MINOR=$5
+  MICRO=$6
+
+  # for backwards compatibility, we let PKG_PATH=PACKAGE when PKG_PATH null
+  if test -z "$PKG_PATH"; then PKG_PATH=$PACKAGE; fi
+  debug "major $MAJOR minor $MINOR micro $MICRO"
+  VERSION=$MAJOR
+  if test ! -z "$MINOR"; then VERSION=$VERSION.$MINOR; else MINOR=0; fi
+  if test ! -z "$MICRO"; then VERSION=$VERSION.$MICRO; else MICRO=0; fi
+
+  debug "major $MAJOR minor $MINOR micro $MICRO"
+  
+  for SUGGESTION in $PKG_PATH; do 
+    COMMAND="$SUGGESTION"
+
+    # don't check if asked not to
+    test -z "$NOCHECK" && {
+      echo -n "  checking for $COMMAND >= $VERSION ... "
+    } || {
+      # we set a var with the same name as the package, but stripped of
+      # unwanted chars
+      VAR=`echo $PACKAGE | sed 's/-//g'`
+      debug "setting $VAR"
+      eval $VAR="$COMMAND"
+      return 0
+    }
+
+    debug "checking version with $COMMAND"
+    ($COMMAND --version) < /dev/null > /dev/null 2>&1 || 
+    {
+      echo "not found."
+      continue
+    }
+    # strip everything that's not a digit, then use cut to get the first field
+    pkg_version=`$COMMAND --version|head -n 1|sed 's/^.*)[^0-9]*//'|cut -d' ' -f1`
+    debug "pkg_version $pkg_version"
+    # remove any non-digit characters from the version numbers to permit numeric
+    # comparison
+    pkg_major=`echo $pkg_version | cut -d. -f1 | sed s/[a-zA-Z\-].*//g`
+    pkg_minor=`echo $pkg_version | cut -d. -f2 | sed s/[a-zA-Z\-].*//g`
+    pkg_micro=`echo $pkg_version | cut -d. -f3 | sed s/[a-zA-Z\-].*//g`
+    test -z "$pkg_major" && pkg_major=0
+    test -z "$pkg_minor" && pkg_minor=0
+    test -z "$pkg_micro" && pkg_micro=0
+    debug "found major $pkg_major minor $pkg_minor micro $pkg_micro"
+
+    #start checking the version
+    debug "version check"
+
+    # reset check
+    WRONG=
+
+    if [ ! "$pkg_major" -gt "$MAJOR" ]; then
+      debug "major: $pkg_major <= $MAJOR"
+      if [ "$pkg_major" -lt "$MAJOR" ]; then
+        debug "major: $pkg_major < $MAJOR"
+        WRONG=1
+      elif [ ! "$pkg_minor" -gt "$MINOR" ]; then
+        debug "minor: $pkg_minor <= $MINOR"
+        if [ "$pkg_minor" -lt "$MINOR" ]; then
+          debug "minor: $pkg_minor < $MINOR"
+          WRONG=1
+        elif [ "$pkg_micro" -lt "$MICRO" ]; then
+          debug "micro: $pkg_micro < $MICRO"
+         WRONG=1
+        fi
+      fi
+    fi
+
+    if test ! -z "$WRONG"; then
+      echo "found $pkg_version, not ok !"
+      continue
+    else
+      echo "found $pkg_version, ok."
+      # we set a var with the same name as the package, but stripped of
+      # unwanted chars
+      VAR=`echo $PACKAGE | sed 's/-//g'`
+      debug "setting $VAR"
+      eval $VAR="$COMMAND"
+      return 0
+    fi
+  done
+
+  echo "not found !"
+  echo "You must have $PACKAGE installed to compile $package."
+  echo "Download the appropriate package for your distribution,"
+  echo "or get the source tarball at $URL"
+  return 1;
+}
+
+aclocal_check ()
+{
+  # normally aclocal is part of automake
+  # so we expect it to be in the same place as automake
+  # so if a different automake is supplied, we need to adapt as well
+  # so how's about replacing automake with aclocal in the set var,
+  # and saving that in $aclocal ?
+  # note, this will fail if the actual automake isn't called automake*
+  # or if part of the path before it contains it
+  if [ -z "$automake" ]; then
+    echo "Error: no automake variable set !"
+    return 1
+  else
+    aclocal=`echo $automake | sed s/automake/aclocal/`
+    debug "aclocal: $aclocal"
+    if [ "$aclocal" != "aclocal" ];
+    then
+      CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-aclocal=$aclocal"
+    fi
+    if [ ! -x `which $aclocal` ]; then
+      echo "Error: cannot execute $aclocal !"
+      return 1
+    fi
+  fi
+}
+
+autoheader_check ()
+{
+  # same here - autoheader is part of autoconf
+  # use the same voodoo
+  if [ -z "$autoconf" ]; then
+    echo "Error: no autoconf variable set !"
+    return 1
+  else
+    autoheader=`echo $autoconf | sed s/autoconf/autoheader/`
+    debug "autoheader: $autoheader"
+    if [ "$autoheader" != "autoheader" ];
+    then
+      CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-autoheader=$autoheader"
+    fi
+    if [ ! -x `which $autoheader` ]; then
+      echo "Error: cannot execute $autoheader !"
+      return 1
+    fi
+  fi
+
+}
+autoconf_2_52d_check ()
+{
+  # autoconf 2.52d has a weird issue involving a yes:no error
+  # so don't allow it's use
+  test -z "$NOCHECK" && {
+    ac_version=`$autoconf --version|head -n 1|sed 's/^[a-zA-Z\.\ ()]*//;s/ .*$//'`
+    if test "$ac_version" = "2.52d"; then
+      echo "autoconf 2.52d has an issue with our current build."
+      echo "We don't know who's to blame however.  So until we do, get a"
+      echo "regular version.  RPM's of a working version are on the gstreamer site."
+      exit 1
+    fi
+  }
+  return 0
+}
+
+die_check ()
+{
+  # call with $DIE
+  # if set to 1, we need to print something helpful then die
+  DIE=$1
+  if test "x$DIE" = "x1";
+  then
+    echo
+    echo "- Please get the right tools before proceeding."
+    echo "- Alternatively, if you're sure we're wrong, run with --nocheck."
+    exit 1
+  fi
+}
+
+autogen_options ()
+{
+  if test "x$1" = "x"; then
+    return 0
+  fi
+
+  while test "x$1" != "x" ; do
+    optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
+    case "$1" in
+      --noconfigure)
+          NOCONFIGURE=defined
+         AUTOGEN_EXT_OPT="$AUTOGEN_EXT_OPT --noconfigure"
+          echo "+ configure run disabled"
+          shift
+          ;;
+      --nocheck)
+         AUTOGEN_EXT_OPT="$AUTOGEN_EXT_OPT --nocheck"
+          NOCHECK=defined
+          echo "+ autotools version check disabled"
+          shift
+          ;;
+      --debug)
+          DEBUG=defined
+         AUTOGEN_EXT_OPT="$AUTOGEN_EXT_OPT --debug"
+          echo "+ debug output enabled"
+          shift
+          ;;
+      --prefix=*)
+         CONFIGURE_EXT_OPT="$CONFIGURE_EXT_OPT --prefix=$optarg"
+         echo "+ passing --prefix=$optarg to configure"
+          shift
+          ;;
+      --prefix)
+         shift
+         echo "DEBUG: $1"
+         CONFIGURE_EXT_OPT="$CONFIGURE_EXT_OPT --prefix=$1"
+         echo "+ passing --prefix=$1 to configure"
+          shift
+          ;;
+
+      -h|--help)
+          echo "autogen.sh (autogen options) -- (configure options)"
+          echo "autogen.sh help options: "
+          echo " --noconfigure            don't run the configure script"
+          echo " --nocheck                don't do version checks"
+          echo " --debug                  debug the autogen process"
+         echo " --prefix                 will be passed on to configure"
+          echo
+          echo " --with-autoconf PATH     use autoconf in PATH"
+          echo " --with-automake PATH     use automake in PATH"
+          echo
+          echo "to pass options to configure, put them as arguments after -- "
+         exit 1
+          ;;
+      --with-automake=*)
+          AUTOMAKE=$optarg
+          echo "+ using alternate automake in $optarg"
+         CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-automake=$AUTOMAKE"
+          shift
+          ;;
+      --with-autoconf=*)
+          AUTOCONF=$optarg
+          echo "+ using alternate autoconf in $optarg"
+         CONFIGURE_DEF_OPT="$CONFIGURE_DEF_OPT --with-autoconf=$AUTOCONF"
+          shift
+          ;;
+      --disable*|--enable*|--with*)
+          echo "+ passing option $1 to configure"
+         CONFIGURE_EXT_OPT="$CONFIGURE_EXT_OPT $1"
+          shift
+          ;;
+       --) shift ; break ;;
+      *) echo "- ignoring unknown autogen.sh argument $1"; shift ;;
+    esac
+  done
+
+  for arg do CONFIGURE_EXT_OPT="$CONFIGURE_EXT_OPT $arg"; done
+  if test ! -z "$CONFIGURE_EXT_OPT"
+  then
+    echo "+ options passed to configure: $CONFIGURE_EXT_OPT"
+  fi
+}
+
+toplevel_check ()
+{
+  srcfile=$1
+  test -f $srcfile || {
+        echo "You must run this script in the top-level $package directory"
+        exit 1
+  }
+}
+
+
+tool_run ()
+{
+  tool=$1
+  options=$2
+  run_if_fail=$3
+  echo "+ running $tool $options..."
+  $tool $options || {
+    echo
+    echo $tool failed
+    eval $run_if_fail
+    exit 1
+  }
+}
diff --git a/gst-plugins-tizen1.0.manifest b/gst-plugins-tizen1.0.manifest
new file mode 100644 (file)
index 0000000..a76fdba
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+       <request>
+               <domain name="_" />
+       </request>
+</manifest>
diff --git a/m4/Makefile.am b/m4/Makefile.am
new file mode 100644 (file)
index 0000000..5fa63aa
--- /dev/null
@@ -0,0 +1 @@
+EXTRA_DIST = as-version.m4 as-compiler-flag.m4\r
diff --git a/m4/as-compiler-flag.m4 b/m4/as-compiler-flag.m4
new file mode 100755 (executable)
index 0000000..4134857
--- /dev/null
@@ -0,0 +1,25 @@
+dnl as-compiler-flag.m4 0.0.1\r
+dnl autostars m4 macro for detection of compiler flags\r
+dnl\r
+dnl ds@schleef.org\r
+\r
+AC_DEFUN([AS_COMPILER_FLAG],\r
+[\r
+  AC_MSG_CHECKING([to see if compiler understands $1])\r
+\r
+  save_CFLAGS="$CFLAGS"\r
+  CFLAGS="$CFLAGS $1"\r
+\r
+  AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no])\r
+  CFLAGS="$save_CFLAGS"\r
+\r
+  if test "X$flag_ok" = Xyes ; then\r
+    $2\r
+    true\r
+  else\r
+    $3\r
+    true\r
+  fi\r
+  AC_MSG_RESULT([$flag_ok])\r
+])\r
+\r
diff --git a/m4/as-version.m4 b/m4/as-version.m4
new file mode 100755 (executable)
index 0000000..249102b
--- /dev/null
@@ -0,0 +1,66 @@
+dnl as-version.m4 0.1.0\r
+\r
+dnl autostars m4 macro for versioning\r
+\r
+dnl Thomas Vander Stichele <thomas at apestaart dot org>\r
+\r
+dnl $Id: as-version.m4,v 1.2 2004-09-17 22:18:03 leroutier Exp $\r
+\r
+dnl AS_VERSION(PACKAGE, PREFIX, MAJOR, MINOR, MICRO, NANO,\r
+dnl            ACTION-IF-NO-NANO, [ACTION-IF-NANO])\r
+\r
+dnl example\r
+dnl AS_VERSION(gstreamer, GST_VERSION, 0, 3, 2,)\r
+dnl for a 0.3.2 release version\r
+\r
+dnl this macro\r
+dnl - defines [$PREFIX]_MAJOR, MINOR and MICRO\r
+dnl - if NANO is empty, then we're in release mode, else in cvs/dev mode\r
+dnl - defines [$PREFIX], VERSION, and [$PREFIX]_RELEASE\r
+dnl - executes the relevant action\r
+dnl - AC_SUBST's PACKAGE, VERSION, [$PREFIX] and [$PREFIX]_RELEASE\r
+dnl   as well as the little ones\r
+dnl - doesn't call AM_INIT_AUTOMAKE anymore because it prevents\r
+dnl   maintainer mode from running ok\r
+dnl\r
+dnl don't forget to put #undef [$2] and [$2]_RELEASE in acconfig.h\r
+dnl if you use acconfig.h\r
+\r
+AC_DEFUN([AS_VERSION],\r
+[\r
+  PACKAGE=[$1]\r
+  [$2]_MAJOR=[$3]\r
+  [$2]_MINOR=[$4]\r
+  [$2]_MICRO=[$5]\r
+  NANO=[$6]\r
+  [$2]_NANO=$NANO\r
+  if test "x$NANO" = "x" || test "x$NANO" = "x0";\r
+  then\r
+      AC_MSG_NOTICE(configuring [$1] for release)\r
+      VERSION=[$3].[$4].[$5]\r
+      [$2]_RELEASE=1\r
+      dnl execute action\r
+      ifelse([$7], , :, [$7])\r
+  else\r
+      AC_MSG_NOTICE(configuring [$1] for development with nano $NANO)\r
+      VERSION=[$3].[$4].[$5].$NANO\r
+      [$2]_RELEASE=0.`date +%Y%m%d.%H%M%S`\r
+      dnl execute action\r
+      ifelse([$8], , :, [$8])\r
+  fi\r
+\r
+  [$2]=$VERSION\r
+  AC_DEFINE_UNQUOTED([$2], "$[$2]", [Define the version])\r
+  AC_SUBST([$2])\r
+  AC_DEFINE_UNQUOTED([$2]_RELEASE, "$[$2]_RELEASE", [Define the release version])\r
+  AC_SUBST([$2]_RELEASE)\r
+\r
+  AC_SUBST([$2]_MAJOR)\r
+  AC_SUBST([$2]_MINOR)\r
+  AC_SUBST([$2]_MICRO)\r
+  AC_SUBST([$2]_NANO)\r
+  AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Define the package name])\r
+  AC_SUBST(PACKAGE)\r
+  AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Define the version])\r
+  AC_SUBST(VERSION)\r
+])\r
diff --git a/packaging/gst-plugins-tizen.spec b/packaging/gst-plugins-tizen.spec
new file mode 100644 (file)
index 0000000..b897ae6
--- /dev/null
@@ -0,0 +1,52 @@
+Name:       gst-plugins-tizen1.0
+Version:    1.2.4
+Summary:    GStreamer tizen plugins (common)
+Release:    47
+Group:      libs
+License:    LGPL-2.1+
+Source0:    %{name}-%{version}.tar.gz
+BuildRequires:  pkgconfig(mm-common)
+BuildRequires:  pkgconfig(ecore)
+BuildRequires:  pkgconfig(ecore-x)
+BuildRequires:  pkgconfig(evas)
+BuildRequires:  pkgconfig(gstreamer-video-1.0)
+BuildRequires:  pkgconfig(gstreamer-plugins-base-1.0)
+BuildRequires:  pkgconfig(gstreamer-1.0)  
+BuildRequires: pkgconfig(libdri2)
+BuildRequires: pkgconfig(x11)
+BuildRequires: pkgconfig(xext)
+BuildRequires: pkgconfig(xv)
+BuildRequires: pkgconfig(xdamage)
+BuildRequires: pkgconfig(libdrm)
+BuildRequires:  pkgconfig(libtbm)
+BuildRequires: libdrm-devel
+
+%description
+GStreamer tizen plugins (common)
+
+%prep
+%setup -q
+
+
+%build
+export CFLAGS+=" -DEXPORT_API=\"__attribute__((visibility(\\\"default\\\")))\" "
+
+./autogen.sh --disable-static
+%configure --disable-static \
+--disable-ext-fimcconvert
+
+make %{?jobs:-j%jobs}
+
+%install
+rm -rf %{buildroot}
+%make_install
+mkdir -p %{buildroot}/%{_datadir}/license
+cp -rf %{_builddir}/%{name}-%{version}/COPYING %{buildroot}%{_datadir}/license/%{name}
+
+
+%files
+%manifest gst-plugins-tizen1.0.manifest
+%defattr(-,root,root,-)
+%{_libdir}/libgstwfdbase.so*
+%{_libdir}/gstreamer-1.0/*.so
+%{_datadir}/license/%{name}
diff --git a/pdpushsrc/Makefile.am b/pdpushsrc/Makefile.am
new file mode 100755 (executable)
index 0000000..308a09c
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src\r
diff --git a/pdpushsrc/src/Makefile.am b/pdpushsrc/src/Makefile.am
new file mode 100755 (executable)
index 0000000..090c2d1
--- /dev/null
@@ -0,0 +1,26 @@
+# plugindir is set in configure
+
+##############################################################################
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #
+##############################################################################
+plugin_LTLIBRARIES = libgstpdpushsrc.la
+
+##############################################################################
+# for the next set of variables, rename the prefix if you renamed the .la,   #
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #
+##############################################################################
+
+# sources used to compile this plug-in
+libgstpdpushsrc_la_SOURCES = gstpdpushsrc.c
+
+# flags used to compile this plugin
+# add other _CFLAGS and _LIBS as needed
+libgstpdpushsrc_la_CFLAGS = $(GST_CFLAGS)  $(GST_PLUGINS_BASE_CFLAGS) $(GST_BASE_CFLAGS)
+libgstpdpushsrc_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS)  $(GST_BASE_LIBS)
+libgstpdpushsrc_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gstpdpushsrc.h
diff --git a/pdpushsrc/src/gstpdpushsrc.c b/pdpushsrc/src/gstpdpushsrc.c
new file mode 100755 (executable)
index 0000000..064a311
--- /dev/null
@@ -0,0 +1,845 @@
+/*
+ * pdpushsrc
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Seungbae Shin <seungbae.shin@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#include <gst/gst.h>
+#include "gstpdpushsrc.h"
+#include <errno.h>
+#include <stdio.h>
+#include <sys/types.h>
+#ifdef G_OS_WIN32
+#include <io.h>                 /* lseek, open, close, read */
+/* On win32, stat* default to 32 bit; we need the 64-bit
+ * variants, so explicitly define it that way. */
+#define stat __stat64
+#define fstat _fstat64
+#undef lseek
+#define lseek _lseeki64
+#undef off_t
+#define off_t guint64
+/* Prevent stat.h from defining the stat* functions as
+ * _stat*, since we're explicitly overriding that */
+#undef _INC_STAT_INL
+#endif
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#ifdef HAVE_UNISTD_H
+#  include <unistd.h>
+#endif
+
+#include <errno.h>
+#include <string.h>
+
+static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS_ANY);
+
+/* FIXME we should be using glib for this */
+#ifndef S_ISREG
+#define S_ISREG(mode) ((mode)&_S_IFREG)
+#endif
+#ifndef S_ISDIR
+#define S_ISDIR(mode) ((mode)&_S_IFDIR)
+#endif
+#ifndef S_ISSOCK
+#define S_ISSOCK(x) (0)
+#endif
+#ifndef O_BINARY
+#define O_BINARY (0)
+#endif
+
+static int
+file_open (const gchar * filename, int flags, int mode)
+{
+  return open (filename, flags, mode);
+}
+
+GST_DEBUG_CATEGORY_STATIC (gst_pd_pushsrc_debug);
+#define GST_CAT_DEFAULT gst_pd_pushsrc_debug
+
+/* FileSrc signals and args */
+enum
+{
+  /* FILL ME */
+  LAST_SIGNAL
+};
+
+#define DEFAULT_BLOCKSIZE       4*1024
+
+enum
+{
+  ARG_0,
+  ARG_LOCATION,
+  ARG_EOS,
+};
+
+static void gst_pd_pushsrc_finalize (GObject * object);
+
+static void gst_pd_pushsrc_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);
+static void gst_pd_pushsrc_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
+
+static gboolean gst_pd_pushsrc_start (GstBaseSrc * basesrc);
+static gboolean gst_pd_pushsrc_stop (GstBaseSrc * basesrc);
+
+static gboolean gst_pd_pushsrc_is_seekable (GstBaseSrc * src);
+static gboolean gst_pd_pushsrc_get_size (GstBaseSrc * src, guint64 * size);
+static gboolean gst_pd_pushsrc_query (GstBaseSrc * src, GstQuery * query);
+static void gst_pd_pushsrc_uri_handler_init (gpointer g_iface, gpointer iface_data);
+static GstFlowReturn gst_pd_pushsrc_create (GstBaseSrc * basesrc, guint64 offset, guint length, GstBuffer ** buffer);
+static gboolean gst_pd_pushsrc_unlock (GstBaseSrc *src);
+
+static gboolean gst_pd_pushsrc_checkgetrange (GstPad * pad);
+
+G_DEFINE_TYPE_WITH_CODE (GstPDPushSrc, gst_pd_pushsrc, GST_TYPE_BASE_SRC,
+                         G_IMPLEMENT_INTERFACE(GST_TYPE_URI_HANDLER, gst_pd_pushsrc_uri_handler_init));
+
+static void
+gst_pd_pushsrc_base_init (gpointer g_class)
+{
+  GST_LOG ("IN");
+
+  GST_LOG ("OUT");
+}
+
+static void
+gst_pd_pushsrc_class_init (GstPDPushSrcClass * klass)
+{
+  GST_LOG ("IN");
+
+  GObjectClass *gobject_class;
+  GstElementClass *gstelement_class;
+  GstBaseSrcClass *gstbasesrc_class;
+
+  gobject_class = G_OBJECT_CLASS (klass);
+  gstelement_class = GST_ELEMENT_CLASS (klass);
+  gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
+
+  gobject_class->set_property = gst_pd_pushsrc_set_property;
+  gobject_class->get_property = gst_pd_pushsrc_get_property;
+  gobject_class->finalize = gst_pd_pushsrc_finalize;
+
+  g_object_class_install_property (gobject_class, ARG_LOCATION,
+      g_param_spec_string ("location", "File Location",
+          "Location of the file to read", NULL,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
+          GST_PARAM_MUTABLE_READY));
+
+    g_object_class_install_property (gobject_class, ARG_EOS,
+                                    g_param_spec_boolean ("eos",
+                                        "EOS recived on downloading pipeline",
+                                        "download of clip is over",
+                                        0,
+                                        G_PARAM_READWRITE));
+
+  gst_element_class_set_details_simple (gstelement_class,
+      "PD push source",
+      "Source/File",
+      "Read from arbitrary point in a file",
+      "Naveen Ch <naveen.ch@samsung.com>");
+  gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&srctemplate));
+
+  gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_start);
+  gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_stop);
+  gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_is_seekable);
+  gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_get_size);
+  gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_query);
+  gstbasesrc_class->create = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_create);
+  gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_pd_pushsrc_unlock);
+
+  if (sizeof (off_t) < 8) {
+    GST_LOG ("No large file support, sizeof (off_t) = %" G_GSIZE_FORMAT "!",
+        sizeof (off_t));
+  }
+
+  GST_DEBUG_CATEGORY_INIT (gst_pd_pushsrc_debug, "pdpushsrc", 0,
+      "pd push src");
+
+  GST_LOG ("OUT");
+
+}
+
+static void
+gst_pd_pushsrc_init (GstPDPushSrc * src)
+{
+  GST_LOG ("IN");
+  GstBaseSrc *basesrc = GST_BASE_SRC (src);
+
+  src->filename = NULL;
+  src->fd = 0;
+  src->uri = NULL;
+  src->is_regular = FALSE;
+  src->is_eos = FALSE;
+  src->is_stop = FALSE;
+
+  GST_LOG ("OUT");
+}
+
+static void
+gst_pd_pushsrc_finalize (GObject * object)
+{
+  GST_LOG ("IN");
+
+  GstPDPushSrc *src;
+
+  src = GST_PD_PUSHSRC (object);
+
+  g_free (src->filename);
+  g_free (src->uri);
+
+  G_OBJECT_CLASS (gst_pd_pushsrc_parent_class)->finalize (object);
+
+  GST_LOG ("OUT");
+}
+
+static gboolean
+gst_pd_pushsrc_set_location (GstPDPushSrc * src, const gchar * location)
+{
+  GST_LOG ("IN");
+
+  GstState state;
+
+  /* the element must be stopped in order to do this */
+  GST_OBJECT_LOCK (src);
+  state = GST_STATE (src);
+  if (state != GST_STATE_READY && state != GST_STATE_NULL)
+    goto wrong_state;
+  GST_OBJECT_UNLOCK (src);
+
+  g_free (src->filename);
+  g_free (src->uri);
+
+  /* clear the filename if we get a NULL (is that possible?) */
+  if (location == NULL) {
+    src->filename = NULL;
+    src->uri = NULL;
+  } else {
+    /* we store the filename as received by the application. On Windows this
+     * should be UTF8 */
+    src->filename = g_strdup (location);
+    src->uri = gst_filename_to_uri (location, NULL);
+    GST_INFO ("filename : %s", src->filename);
+    GST_INFO ("uri      : %s", src->uri);
+  }
+  g_object_notify (G_OBJECT (src), "location");
+
+  GST_LOG ("OUT");
+
+  return TRUE;
+
+  /* ERROR */
+wrong_state:
+  {
+    g_warning ("Changing the `location' property on filesrc when a file is "
+        "open is not supported.");
+    GST_OBJECT_UNLOCK (src);
+    GST_LOG ("OUT :: wrong_state");
+    return FALSE;
+  }
+}
+
+static void
+gst_pd_pushsrc_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec)
+{
+  GST_LOG ("IN");
+
+  GstPDPushSrc *src;
+
+  g_return_if_fail (GST_IS_PD_PUSHSRC (object));
+
+  src = GST_PD_PUSHSRC (object);
+
+  switch (prop_id) {
+    case ARG_LOCATION:
+      gst_pd_pushsrc_set_location (src, g_value_get_string (value));
+      break;
+    case ARG_EOS:
+      src->is_eos = g_value_get_boolean (value);
+      g_print ("\n\n\nis_eos is becoming %d\n\n\n", src->is_eos);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+  GST_LOG ("OUT");
+}
+
+static void
+gst_pd_pushsrc_get_property (GObject * object, guint prop_id, GValue * value,
+    GParamSpec * pspec)
+{
+  GST_LOG ("IN");
+  GstPDPushSrc *src;
+
+  g_return_if_fail (GST_IS_PD_PUSHSRC (object));
+
+  src = GST_PD_PUSHSRC (object);
+
+  switch (prop_id) {
+    case ARG_LOCATION:
+      g_value_set_string (value, src->filename);
+      break;
+    case ARG_EOS:
+      g_value_set_boolean (value, src->is_eos);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+  GST_LOG ("OUT");
+}
+
+static GstFlowReturn
+gst_pd_pushsrc_create_read (GstBaseSrc * basesrc, guint64 offset, guint length, GstBuffer ** buffer)
+{
+  GST_LOG ("IN");
+
+  int ret;
+  GstBuffer *buf = NULL;
+  GstMapInfo buf_info = GST_MAP_INFO_INIT;
+  struct stat stat_results;
+  GstPDPushSrc *src;
+
+  src = GST_PD_PUSHSRC_CAST (basesrc);
+
+  GST_LOG_OBJECT (src, "read position = %"G_GUINT64_FORMAT ", offset = %"G_GUINT64_FORMAT", length = %d",
+    src->read_position, offset, length);
+
+  memset (&stat_results, 0, sizeof (stat_results));
+
+  if (fstat (src->fd, &stat_results) < 0)
+    goto could_not_stat;
+
+  GST_LOG_OBJECT (src, "offset + length = %"G_GUINT64_FORMAT " and filesize = %"G_GUINT64_FORMAT, offset + length, stat_results.st_size);
+
+  while ((offset + length) > stat_results.st_size)
+  {
+    fd_set fds;
+    int ret;
+    struct timeval timeout = {0,};
+    guint64 avail_size = 0;
+
+    if (src->is_eos)
+      goto eos;
+
+    if (src->is_stop) {
+      GST_DEBUG_OBJECT (src, "reading was stopped");
+      goto was_stopped;
+    }
+
+    FD_ZERO (&fds);
+    FD_SET (src->fd, &fds);
+
+    timeout.tv_sec = 0;
+    timeout.tv_usec = ((basesrc->blocksize * 8 * 1000) / 64000); // wait_time = (blocksize * 8) / (min downloadratei.e. 64Kbps)
+
+    GST_DEBUG_OBJECT (src, "Going to wait for %ld msec", timeout.tv_usec);
+
+    ret = select (src->fd + 1, &fds, NULL, NULL, &timeout);
+    if (-1 == ret)
+    {
+      GST_ERROR_OBJECT (src, "ERROR in select () : reason - %s...\n", g_strerror(errno));
+      return GST_FLOW_ERROR;
+    }
+    else if (0 == ret)
+    {
+      GST_WARNING_OBJECT (src, "select () timeout happened...");
+    }
+    else
+    {
+      memset (&stat_results, 0, sizeof (stat_results));
+
+      if (fstat (src->fd, &stat_results) < 0)
+        goto could_not_stat;
+
+      avail_size = stat_results.st_size;
+
+      GST_LOG_OBJECT (src, "Available data size in file = %"G_GUINT64_FORMAT, avail_size);
+
+      if ((offset + length) > avail_size)
+      {
+        GST_LOG_OBJECT (src, "Enough data is NOT available...");
+      }
+      else
+      {
+        GST_LOG_OBJECT (src, "Enough data is available...");
+      }
+    }
+  }
+
+  if (G_UNLIKELY (src->read_position != offset)) {
+    off_t res;
+
+    res = lseek (src->fd, offset, SEEK_SET);
+    if (G_UNLIKELY (res < 0 || res != offset))
+      goto seek_failed;
+    src->read_position = offset;
+  }
+
+  buf = gst_buffer_new_and_alloc (length);
+  if (G_UNLIKELY (buf == NULL && length > 0)) {
+    GST_ERROR_OBJECT (src, "Failed to allocate %u bytes", length);
+    return GST_FLOW_ERROR;
+  }
+
+  /* No need to read anything if length is 0 */
+  if (length > 0) {
+    GST_LOG_OBJECT (src, "Reading %d bytes at offset 0x%" G_GINT64_MODIFIER "x",
+        length, offset);
+    gst_buffer_map(buf, &buf_info, GST_MAP_WRITE);
+    ret = read (src->fd, buf_info.data, length);
+    gst_buffer_unmap(buf, &buf_info);
+    if (G_UNLIKELY (ret < 0))
+      goto could_not_read;
+
+    /* seekable regular files should have given us what we expected */
+    if (G_UNLIKELY ((guint) ret < length && src->seekable))
+      goto unexpected_eos;
+
+    /* other files should eos if they read 0 and more was requested */
+    if (G_UNLIKELY (ret == 0 && length > 0))
+      goto eos;
+
+    length = ret;
+    GST_BUFFER_OFFSET (buf) = offset;
+    GST_BUFFER_OFFSET_END (buf) = offset + length;
+
+    src->read_position += length;
+  }
+
+  *buffer = buf;
+  GST_LOG ("OUT");
+
+  return GST_FLOW_OK;
+
+  /* ERROR */
+seek_failed:
+  {
+    GST_ERROR_OBJECT (src, "Seek failed...");
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
+    return GST_FLOW_ERROR;
+  }
+could_not_stat:
+  {
+    GST_ERROR_OBJECT (src, "Could not stat");
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
+    return GST_FLOW_ERROR;
+  }
+could_not_read:
+  {
+    GST_ERROR_OBJECT (src, "Could not read...");
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
+    if (buf)
+      gst_buffer_unref (buf);
+    return GST_FLOW_ERROR;
+  }
+unexpected_eos:
+  {
+    GST_ERROR_OBJECT (src, "Unexpected EOS occured...");
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("unexpected end of file."));
+    if (buf)
+      gst_buffer_unref (buf);
+    return GST_FLOW_ERROR;
+  }
+eos:
+  {
+    GST_ERROR_OBJECT (src, "non-regular file hits EOS");
+    if (buf)
+      gst_buffer_unref (buf);
+    return GST_FLOW_EOS;
+  }
+was_stopped:
+  {
+    return GST_FLOW_FLUSHING;
+  }
+}
+
+static GstFlowReturn
+gst_pd_pushsrc_create (GstBaseSrc * basesrc, guint64 offset, guint length, GstBuffer ** buffer)
+{
+  GST_LOG ("IN");
+
+  GstPDPushSrc *pdsrc;
+  GstFlowReturn ret;
+
+  pdsrc = GST_PD_PUSHSRC_CAST (basesrc);
+  ret = gst_pd_pushsrc_create_read (basesrc, offset, length, buffer);
+  GST_LOG ("OUT");
+
+  return ret;
+}
+
+static gboolean
+gst_pd_pushsrc_query (GstBaseSrc * basesrc, GstQuery * query)
+{
+  GST_LOG ("IN");
+
+  gboolean ret = FALSE;
+  GstPDPushSrc *src = GST_PD_PUSHSRC (basesrc);
+
+  switch (GST_QUERY_TYPE (query)) {
+    case GST_QUERY_URI:
+      gst_query_set_uri (query, src->uri);
+      ret = TRUE;
+      break;
+
+    case GST_QUERY_SCHEDULING:
+        ret = gst_pd_pushsrc_checkgetrange(basesrc->srcpad);
+        break;
+
+    default:
+      ret = FALSE;
+      break;
+  }
+
+  if (!ret)
+    ret = GST_BASE_SRC_CLASS (gst_pd_pushsrc_parent_class)->query (basesrc, query);
+  GST_LOG ("OUT");
+
+  return ret;
+}
+
+static gboolean
+gst_pd_pushsrc_checkgetrange (GstPad * pad)
+{
+  GST_LOG ("IN");
+
+  GST_LOG ("OUT");
+
+  return FALSE;
+}
+
+static gboolean
+gst_pd_pushsrc_is_seekable (GstBaseSrc * basesrc)
+{
+  GST_LOG ("IN");
+
+  GstPDPushSrc *src = GST_PD_PUSHSRC (basesrc);
+
+  GST_DEBUG_OBJECT (src, "seekable = %d", src->seekable);
+  GST_LOG ("OUT");
+
+  return src->seekable;
+
+}
+
+static gboolean
+gst_pd_pushsrc_get_size (GstBaseSrc * basesrc, guint64 * size)
+{
+  GST_LOG ("IN");
+
+  struct stat stat_results;
+  GstPDPushSrc *src;
+
+  src = GST_PD_PUSHSRC (basesrc);
+
+  if (!src->seekable) {
+    /* If it isn't seekable, we won't know the length (but fstat will still
+     * succeed, and wrongly say our length is zero. */
+    return FALSE;
+  }
+
+  if (fstat (src->fd, &stat_results) < 0)
+    goto could_not_stat;
+
+  //*size = stat_results.st_size;
+  /* Naveen : Intentionally, doing this because we dont know the file size...because its keep on increasing in PD case */
+  *size = G_MAXUINT64;
+
+  GST_DEBUG ("size of the file = %"G_GUINT64_FORMAT, *size);
+
+  GST_LOG ("OUT");
+
+  return TRUE;
+
+  /* ERROR */
+could_not_stat:
+  {
+    GST_ERROR_OBJECT (src, "Could not stat");
+    return FALSE;
+  }
+}
+
+/* open the file, necessary to go to READY state */
+static gboolean
+gst_pd_pushsrc_start (GstBaseSrc * basesrc)
+{
+  GST_LOG ("IN");
+
+  GstPDPushSrc *src = GST_PD_PUSHSRC (basesrc);
+  struct stat stat_results;
+
+  if (src->filename == NULL || src->filename[0] == '\0')
+    goto no_filename;
+
+  GST_INFO_OBJECT (src, "opening file %s", src->filename);
+
+  /* open the file */
+  src->fd = file_open (src->filename, O_RDONLY | O_BINARY, 0);
+
+  if (src->fd < 0)
+    goto open_failed;
+
+  /* check if it is a regular file, otherwise bail out */
+  if (fstat (src->fd, &stat_results) < 0)
+    goto no_stat;
+
+  if (S_ISDIR (stat_results.st_mode))
+    goto was_directory;
+
+  if (S_ISSOCK (stat_results.st_mode))
+    goto was_socket;
+
+  src->read_position = 0;
+
+  /* record if it's a regular (hence seekable and lengthable) file */
+  if (S_ISREG (stat_results.st_mode))
+    src->is_regular = TRUE;
+
+  {
+    /* we need to check if the underlying file is seekable. */
+    off_t res = lseek (src->fd, 0, SEEK_END);
+
+    if (res < 0) {
+      GST_LOG_OBJECT (src, "disabling seeking, not in mmap mode and lseek "
+          "failed: %s", g_strerror (errno));
+      src->seekable = FALSE;
+    } else {
+      src->seekable = TRUE;
+    }
+    lseek (src->fd, 0, SEEK_SET);
+  }
+
+  /* We can only really do seeking on regular files - for other file types, we
+   * don't know their length, so seeking isn't useful/meaningful */
+  src->seekable = src->seekable && src->is_regular;
+  GST_LOG ("OUT");
+
+  return TRUE;
+
+  /* ERROR */
+no_filename:
+  {
+    GST_ERROR_OBJECT (src, "No file name specified for reading...");
+    GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
+        ("No file name specified for reading."), (NULL));
+    return FALSE;
+  }
+open_failed:
+  {
+    switch (errno) {
+      case ENOENT:
+        GST_ERROR_OBJECT (src, "File could not be found");
+        GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
+            ("No such file \"\""));
+        break;
+      default:
+        GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
+            ("Could not open file for reading."),
+            GST_ERROR_SYSTEM);
+        break;
+    }
+    return FALSE;
+  }
+no_stat:
+  {
+    GST_ERROR_OBJECT (src, "Could not get stat info...");
+    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
+        ("Could not get info on \"\"."),  (NULL));
+    close (src->fd);
+    return FALSE;
+  }
+was_directory:
+  {
+    GST_ERROR_OBJECT (src, "Is a Directory");
+    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
+        ("\"\" is a directory."), (NULL));
+    close (src->fd);
+    return FALSE;
+  }
+was_socket:
+  {
+   GST_ERROR_OBJECT (src, "Is a Socket");
+    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
+        ("File \"\" is a socket."), (NULL));
+    close (src->fd);
+    return FALSE;
+  }
+}
+
+/* unmap and close the file */
+static gboolean
+gst_pd_pushsrc_stop (GstBaseSrc * basesrc)
+{
+  GST_LOG ("IN");
+
+  GstPDPushSrc *src = GST_PD_PUSHSRC (basesrc);
+
+  /* close the file */
+  close (src->fd);
+
+  /* zero out a lot of our state */
+  src->fd = 0;
+  src->is_regular = FALSE;
+
+  GST_LOG ("OUT");
+
+  return TRUE;
+}
+
+/*** GSTURIHANDLER INTERFACE *************************************************/
+
+static GstURIType
+gst_pd_pushsrc_uri_get_type (GType type)
+{
+  GST_LOG ("IN");
+  GST_LOG ("OUT");
+
+  return GST_URI_SRC;
+}
+
+static const gchar * const*
+gst_pd_pushsrc_uri_get_protocols (GType type)
+{
+  GST_LOG ("IN");
+  static const gchar *protocols[] = { "file", NULL };
+  GST_LOG ("OUT");
+
+  return protocols;
+}
+
+static gchar *
+gst_pd_pushsrc_uri_get_uri (GstURIHandler * handler)
+{
+  GST_LOG ("IN");
+  GstPDPushSrc *src = GST_PD_PUSHSRC (handler);
+  GST_LOG ("OUT");
+
+  return g_strdup(src->uri);
+}
+
+static gboolean
+gst_pd_pushsrc_uri_set_uri (GstURIHandler * handler, const gchar * uri, GError ** error)
+{
+  GST_LOG ("IN");
+
+  gchar *location, *hostname = NULL;
+  gboolean ret = FALSE;
+  GstPDPushSrc *src = GST_PD_PUSHSRC (handler);
+
+  if (strcmp (uri, "file://") == 0) {
+    /* Special case for "file://" as this is used by some applications
+     *  to test with gst_element_make_from_uri if there's an element
+     *  that supports the URI protocol. */
+    gst_pd_pushsrc_set_location (src, NULL);
+    return TRUE;
+  }
+
+  location = g_filename_from_uri (uri, &hostname, error);
+
+  if (!location || *error) {
+    if (*error) {
+      GST_WARNING_OBJECT (src, "Invalid URI '%s' for filesrc: %s", uri,
+          (*error)->message);
+    } else {
+      GST_WARNING_OBJECT (src, "Invalid URI '%s' for filesrc", uri);
+    }
+    goto beach;
+  }
+
+  if ((hostname) && (strcmp (hostname, "localhost"))) {
+    /* Only 'localhost' is permitted */
+    GST_WARNING_OBJECT (src, "Invalid hostname '%s' for filesrc", hostname);
+    goto beach;
+  }
+#ifdef G_OS_WIN32
+  /* Unfortunately, g_filename_from_uri() doesn't handle some UNC paths
+   * correctly on windows, it leaves them with an extra backslash
+   * at the start if they're of the mozilla-style file://///host/path/file
+   * form. Correct this.
+   */
+  if (location[0] == '\\' && location[1] == '\\' && location[2] == '\\')
+    g_memmove (location, location + 1, strlen (location + 1) + 1);
+#endif
+
+  ret = gst_pd_pushsrc_set_location (src, location);
+
+  GST_LOG ("OUT");
+
+beach:
+  if (location)
+    g_free (location);
+  if (hostname)
+    g_free (hostname);
+
+  return ret;
+}
+
+static gboolean
+gst_pd_pushsrc_unlock (GstBaseSrc *basesrc)
+{
+  GstPDPushSrc *pdpushsrc = GST_PD_PUSHSRC (basesrc);
+  GST_DEBUG_OBJECT (pdpushsrc, "try to stop loop");
+  pdpushsrc->is_stop = TRUE;
+  return TRUE;
+}
+
+static void
+gst_pd_pushsrc_uri_handler_init (gpointer g_iface, gpointer iface_data)
+{
+  GST_LOG ("IN");
+  GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
+
+  iface->get_type = gst_pd_pushsrc_uri_get_type;
+  iface->get_protocols = gst_pd_pushsrc_uri_get_protocols;
+  iface->get_uri = gst_pd_pushsrc_uri_get_uri;
+  iface->set_uri = gst_pd_pushsrc_uri_set_uri;
+  GST_LOG ("OUT");
+}
+
+static gboolean
+gst_pd_pushsrc_plugin_init (GstPlugin *plugin)
+{
+    if (!gst_element_register (plugin, "pdpushsrc", GST_RANK_NONE, gst_pd_pushsrc_get_type()))
+    {
+        return FALSE;
+    }
+    return TRUE;
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+                   GST_VERSION_MINOR,
+                   pdpushsrc,
+                   "PD push source",
+                   gst_pd_pushsrc_plugin_init,
+                   VERSION,
+                   "LGPL",
+                   "Samsung Electronics Co",
+                   "http://www.samsung.com")
+
+
diff --git a/pdpushsrc/src/gstpdpushsrc.h b/pdpushsrc/src/gstpdpushsrc.h
new file mode 100755 (executable)
index 0000000..9670ac8
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * pdpushsrc
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Seungbae Shin <seungbae.shin@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifndef __GST_PD_PUSHSRC_H__
+#define __GST_PD_PUSHSRC_H__
+
+#include <sys/types.h>
+#include <gst/gst.h>
+#include <gst/base/gstbasesrc.h>
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_PD_PUSHSRC                (gst_pd_pushsrc_get_type())
+#define GST_PD_PUSHSRC(obj)                  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PD_PUSHSRC,GstPDPushSrc))
+#define GST_PD_PUSHSRC_CLASS(klass)   (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PD_PUSHSRC,GstPDPushSrcClass))
+#define GST_IS_PD_PUSHSRC(obj)                  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PD_PUSHSRC))
+#define GST_IS_PD_PUSHSRC_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PD_PUSHSRC))
+#define GST_PD_PUSHSRC_CAST(obj) ((GstPDPushSrc*) obj)
+
+typedef struct _GstPDPushSrc GstPDPushSrc;
+typedef struct _GstPDPushSrcClass GstPDPushSrcClass;
+
+/**
+ * GstFileSrc:
+ *
+ * Opaque #GstPDPushSrc structure.
+ */
+struct _GstPDPushSrc {
+  GstBaseSrc element;
+  GstPad *srcpad;
+
+  gchar *filename;                     /* filename */
+  gchar *uri;                          /* caching the URI */
+  gint fd;                             /* open file descriptor */
+  guint64 read_position;               /* position of fd */
+
+  gboolean seekable;                    /* whether the file is seekable */
+  gboolean is_regular;                  /* whether it's a (symlink to a)                                          regular file */
+
+  gboolean is_eos;
+  gboolean is_stop;
+
+};
+
+struct _GstPDPushSrcClass {
+  GstBaseSrcClass parent_class;
+};
+
+GType gst_pd_pushsrc_get_type (void);
+
+G_END_DECLS
+
+#endif /* __GST_FILE_SRC_H__ */
diff --git a/toggle/Makefile.am b/toggle/Makefile.am
new file mode 100755 (executable)
index 0000000..308a09c
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src\r
diff --git a/toggle/src/Makefile.am b/toggle/src/Makefile.am
new file mode 100755 (executable)
index 0000000..4d761d7
--- /dev/null
@@ -0,0 +1,30 @@
+# plugindir is set in configure\r
+\r
+##############################################################################\r
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #\r
+##############################################################################\r
+plugin_LTLIBRARIES = libgsttoggle.la\r
+\r
+##############################################################################\r
+# for the next set of variables, rename the prefix if you renamed the .la,   #\r
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #\r
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #\r
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #\r
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #\r
+##############################################################################\r
+\r
+# sources used to compile this plug-in\r
+libgsttoggle_la_SOURCES = gsttoggle.c\r
+                                 \r
+                                 \r
+\r
+# flags used to compile this plugin\r
+# add other _CFLAGS and _LIBS as needed\r
+libgsttoggle_la_CFLAGS = $(GST_CFLAGS) \r
+libgsttoggle_la_LIBADD = $(GST_LIBS)  $(GST_BASE_LIBS)  \r
+#libgsttoggle_la_LIBADD = $(GST_BASE_LIBS)  \r
+libgsttoggle_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)\r
+\r
+# headers we need but don't want installed\r
+noinst_HEADERS = gsttoggle.h\r
+\r
diff --git a/toggle/src/gsttoggle.c b/toggle/src/gsttoggle.c
new file mode 100755 (executable)
index 0000000..0363dda
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ * toggle
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#include <stdlib.h>
+
+#include "gsttoggle.h"
+
+static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
+    GST_PAD_SINK,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS_ANY);
+
+static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS_ANY);
+
+GST_DEBUG_CATEGORY_STATIC (gst_mytoggle_debug);
+#define GST_CAT_DEFAULT gst_mytoggle_debug
+
+enum
+{
+  LAST_SIGNAL
+};
+
+
+#define DEFAULT_BLOCK_DATA        FALSE
+
+enum
+{
+  PROP_0,
+  PROP_BLOCK_DATA
+};
+
+
+#define _do_init(bla) \
+    GST_DEBUG_CATEGORY_INIT (gst_mytoggle_debug, "toggle", 0, "toggle element");
+
+G_DEFINE_TYPE_WITH_CODE (GstMytoggle, gst_mytoggle,
+    GST_TYPE_BASE_TRANSFORM, _do_init(G_TYPE_INVALID));
+
+static void gst_mytoggle_finalize (GObject * object);
+static void gst_mytoggle_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void gst_mytoggle_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+
+static GstFlowReturn gst_mytoggle_transform_ip (GstBaseTransform * trans,
+    GstBuffer * buf);
+static gboolean gst_mytoggle_start (GstBaseTransform * trans);
+static gboolean gst_mytoggle_stop (GstBaseTransform * trans);
+
+static void
+gst_mytoggle_base_init (gpointer g_class)
+{
+}
+
+static void
+gst_mytoggle_finalize (GObject * object)
+{
+  GstMytoggle *mytoggle;
+
+  G_OBJECT_CLASS (gst_mytoggle_parent_class)->finalize (object);
+}
+
+static void
+gst_mytoggle_class_init (GstMytoggleClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstBaseTransformClass *gstbasetrans_class;
+  GstElementClass *gstelement_class;
+
+  gobject_class = G_OBJECT_CLASS (klass);
+  gstbasetrans_class = GST_BASE_TRANSFORM_CLASS (klass);
+  gstelement_class = GST_ELEMENT_CLASS (klass);
+
+  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_mytoggle_set_property);
+  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_mytoggle_get_property);
+
+  g_object_class_install_property (gobject_class,
+      PROP_BLOCK_DATA, g_param_spec_boolean ("block_data",
+          "Data Block",
+          "Data Block", 
+          DEFAULT_BLOCK_DATA, G_PARAM_READWRITE));
+    
+  gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_mytoggle_finalize);
+
+  gst_element_class_set_details_simple (gstelement_class,
+      "toggle",
+      "Generic",
+      "Pass data without modification", "Rahul Mittal <mittal.rahul@samsung.com>");
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&srctemplate));
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&sinktemplate));
+
+  gstbasetrans_class->transform_ip =
+      GST_DEBUG_FUNCPTR (gst_mytoggle_transform_ip);
+  gstbasetrans_class->start = GST_DEBUG_FUNCPTR (gst_mytoggle_start);
+  gstbasetrans_class->stop = GST_DEBUG_FUNCPTR (gst_mytoggle_stop);
+}
+
+static void
+gst_mytoggle_init (GstMytoggle * mytoggle)
+{
+  gst_base_transform_set_passthrough (GST_BASE_TRANSFORM (mytoggle), TRUE);
+
+  mytoggle->block_data = DEFAULT_BLOCK_DATA;
+
+}
+
+static GstFlowReturn
+gst_mytoggle_transform_ip (GstBaseTransform * trans, GstBuffer * buf)
+{
+  GstMytoggle *mytoggle = GST_MYTOGGLE (trans);
+  if (mytoggle->block_data ==TRUE) 
+      return GST_BASE_TRANSFORM_FLOW_DROPPED;
+
+  return GST_FLOW_OK;
+}
+
+static void
+gst_mytoggle_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  GstMytoggle *mytoggle;
+
+  mytoggle = GST_MYTOGGLE (object);
+
+  switch (prop_id) {
+  
+    case PROP_BLOCK_DATA:
+      mytoggle->block_data = g_value_get_boolean (value);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_mytoggle_get_property (GObject * object, guint prop_id, GValue * value,
+    GParamSpec * pspec)
+{
+  GstMytoggle *mytoggle;
+
+  mytoggle = GST_MYTOGGLE (object);
+
+  switch (prop_id) {
+      case PROP_BLOCK_DATA:
+      g_value_set_boolean (value, mytoggle->block_data);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static gboolean
+gst_mytoggle_start (GstBaseTransform * trans)
+{
+  return TRUE;
+}
+
+static gboolean
+gst_mytoggle_stop (GstBaseTransform * trans)
+{
+  return TRUE;
+}
+
+
+static gboolean plugin_init(GstPlugin *plugin)
+{
+
+       GST_DEBUG_CATEGORY_INIT (gst_mytoggle_debug, "toggle",0, "toggle");
+       return gst_element_register (plugin, "toggle",  GST_RANK_NONE, GST_TYPE_MYTOGGLE);
+}
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+       GST_VERSION_MINOR,
+       toggle,
+       "Base transform plugin template",
+       plugin_init, VERSION, "LGPL", "Samsung Electronics Co", "http://www.samsung.com/")
+       
+
diff --git a/toggle/src/gsttoggle.h b/toggle/src/gsttoggle.h
new file mode 100755 (executable)
index 0000000..0090a6b
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * toggle
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#ifndef __GST_MYTOGGLE_H__
+#define __GST_MYTOGGLE_H__
+
+
+#include <gst/gst.h>
+#include <gst/base/gstbasetransform.h>
+
+G_BEGIN_DECLS
+
+
+#define GST_TYPE_MYTOGGLE \
+  (gst_mytoggle_get_type())
+#define GST_MYTOGGLE(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_MYTOGGLE,GstMytoggle))
+#define GST_MYTOGGLE_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_MYTOGGLE,GstMytoggleClass))
+#define GST_IS_MYTOGGLE(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_MYTOGGLE))
+#define GST_IS_MYTOGGLE_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_MYTOGGLE))
+
+typedef struct _GstMytoggle GstMytoggle;
+typedef struct _GstMytoggleClass GstMytoggleClass;
+
+struct _GstMytoggle {
+  GstBaseTransform      element;
+  gboolean block_data;  
+};
+
+struct _GstMytoggleClass {
+  GstBaseTransformClass parent_class;
+};
+
+GType gst_mytoggle_get_type(void);
+
+G_END_DECLS
+
+#endif /* __GST_MYTOGGLE_H__ */
diff --git a/wfdmanager/Makefile.am b/wfdmanager/Makefile.am
new file mode 100755 (executable)
index 0000000..6ae2ad1
--- /dev/null
@@ -0,0 +1,24 @@
+SUBDIRS = wfdbase
+
+plugin_LTLIBRARIES = libgstwfdmanager.la
+
+noinst_HEADERS = wfdrtpbuffer/wfdrtpbuffer.h \
+               wfdrtpbuffer/gstwfdrtpbuffer.h \
+               wfdrtpbuffer/rtpstats.h \
+               wfdsrc/gstwfdsrc.h
+
+libgstwfdmanager_la_SOURCES = gstwfdmanager.c \
+                       wfdsrc/gstwfdsrc.c \
+                       wfdrtpbuffer/wfdrtpbuffer.c \
+                       wfdrtpbuffer/gstwfdrtpbuffer.c \
+                       wfdrtpbuffer/rtpstats.c
+
+libgstwfdmanager_la_CFLAGS = $(GST_PLUGINS_BASE_CFLAGS) $(GST_CFLAGS)
+
+libgstwfdmanager_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS) $(GST_BASE_LIBS) \
+               -lgstrtp-@GST_API_VERSION@ -lgstrtsp-@GST_API_VERSION@ \
+               $(top_builddir)/wfdmanager/wfdbase/libgstwfdbase.la
+
+libgstwfdmanager_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+libgstwfdmanager_la_LIBTOOLFLAGS = --tag=disable-static
+
diff --git a/wfdmanager/gstwfdmanager.c b/wfdmanager/gstwfdmanager.c
new file mode 100755 (executable)
index 0000000..7968af6
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * This library is licensed under 2 different licenses and you
+ * can choose to use it under the terms of either one of them. The
+ * two licenses are the MPL 1.1 and the LGPL.
+ *
+ * MPL:
+ *
+ * The contents of this file are subject to the Mozilla Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/.
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * LGPL:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "wfdsrc/gstwfdsrc.h"
+#include "wfdrtpbuffer/gstwfdrtpbuffer.h"
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+
+  if (!gst_element_register (plugin, "wfdsrc", GST_RANK_NONE, GST_TYPE_WFD_SRC))
+    return FALSE;
+  if (!gst_element_register (plugin, "wfdrtpbuffer", GST_RANK_NONE, GST_TYPE_WFD_RTP_BUFFER))
+    return FALSE;
+
+  return TRUE;
+}
+
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+    GST_VERSION_MINOR,
+    wfdmanager,
+    "Wi-Fi Display management plugin library",
+    plugin_init,
+    VERSION,
+    "LGPL",
+    "Samsung Electronics Co",
+    "http://www.samsung.com")
diff --git a/wfdmanager/wfdbase/Makefile.am b/wfdmanager/wfdbase/Makefile.am
new file mode 100755 (executable)
index 0000000..c5a77cd
--- /dev/null
@@ -0,0 +1,21 @@
+lib_LTLIBRARIES = libgstwfdbase.la
+
+#libgstwfdbase_includedir =            \
+#      $(includedir)/gstreamer-@GST_API_VERSION@/gst/wfd
+
+#libgstwfdbase_include_HEADERS =       \
+#      gstwfdbasesrc.h
+
+noinst_HEADERS = gstwfdbasesrc.h gstwfdsinkmessage.h
+
+libgstwfdbase_la_SOURCES = gstwfdbasesrc.c \
+                       gstwfdsinkmessage.c
+
+libgstwfdbase_la_CFLAGS = $(GST_PLUGINS_BASE_CFLAGS) $(GST_CFLAGS)
+
+libgstwfdbase_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS) $(GST_BASE_LIBS) \
+               -lgstrtp-@GST_API_VERSION@ -lgstrtsp-@GST_API_VERSION@
+
+libgstwfdbase_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+libgstwfdbase_la_LIBTOOLFLAGS = --tag=disable-static
+
diff --git a/wfdmanager/wfdbase/gstwfdbasesrc.c b/wfdmanager/wfdbase/gstwfdbasesrc.c
new file mode 100644 (file)
index 0000000..ead8d81
--- /dev/null
@@ -0,0 +1,4101 @@
+/*
+ * wfdbasesrc
+ *
+ * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.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.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/**
+* SECTION:element-wfdbasesrc
+*
+* Makes a connection to an RTSP server and read the data.
+* Device recognition is through wifi direct.
+* wfdbasesrc strictly follows Wifi display specification.
+*
+* RTSP supports transport over TCP or UDP in unicast or multicast mode. By
+* default wfdbasesrc will negotiate a connection in the following order:
+* UDP unicast/UDP multicast/TCP. The order cannot be changed but the allowed
+* protocols can be controlled with the #GstWFDBaseSrc:protocols property.
+*
+* wfdbasesrc currently understands WFD capability negotiation messages
+*
+* wfdbasesrc will internally instantiate an RTP session manager element
+* that will handle the RTCP messages to and from the server, jitter removal,
+* packet reordering along with providing a clock for the pipeline.
+* This feature is implemented using the gstrtpbin element.
+*
+* wfdbasesrc acts like a live source and will therefore only generate data in the
+* PLAYING state.
+*
+* <refsect2>
+* <title>Example launch line</title>
+* |[
+* gst-launch wfdbasesrc location=rtsp://some.server/url ! fakesink
+* ]| Establish a connection to an RTSP server and send the raw RTP packets to a
+* fakesink.
+* </refsect2>
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif /* HAVE_UNISTD_H */
+#include <stdlib.h>
+#include <string.h>
+#include <locale.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <arpa/inet.h>
+#include <dlfcn.h>
+
+#include "gstwfdbasesrc.h"
+
+#ifdef G_OS_WIN32
+#include <winsock2.h>
+#endif
+
+GST_DEBUG_CATEGORY_STATIC (wfdbasesrc_debug);
+#define GST_CAT_DEFAULT (wfdbasesrc_debug)
+
+#define GST_WFD_BASE_TASK_GET_LOCK(wfd)    (GST_WFD_BASE_SRC_CAST(wfd)->priv->task_rec_lock)
+#define GST_WFD_BASE_TASK_LOCK(wfd)        (g_rec_mutex_lock (&(GST_WFD_BASE_TASK_GET_LOCK(wfd))))
+#define GST_WFD_BASE_TASK_UNLOCK(wfd)      (g_rec_mutex_unlock(&(GST_WFD_BASE_TASK_GET_LOCK(wfd))))
+
+static GstStaticPadTemplate gst_wfd_base_src_src_template =
+GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("application/x-rtp, "
+        "media = (string) \"video\", "
+        "clock-rate = (int) 90000, "
+        "payload = (int) 33"));
+
+/* signals and args */
+enum
+{
+  SIGNAL_UPDATE_MEDIA_INFO,
+  SIGNAL_AV_FORMAT_CHANGE,
+  SIGNAL_PAUSE,
+  SIGNAL_RESUME,
+  SIGNAL_CLOSE,
+  SIGNAL_SET_STANDBY,
+  LAST_SIGNAL
+};
+
+/* properties default values */
+#define DEFAULT_LOCATION      NULL
+#define DEFAULT_DEBUG            FALSE
+#define DEFAULT_RETRY            50
+#define DEFAULT_TCP_TIMEOUT      20000000
+#define DEFAULT_PROXY            NULL
+#define DEFAULT_RTP_BLOCKSIZE    0
+#define DEFAULT_USER_ID          NULL
+#define DEFAULT_USER_PW          NULL
+#define DEFAULT_PORT_RANGE       NULL
+#define DEFAULT_USER_AGENT       "TIZEN-WFD-SINK"
+
+enum
+{
+  PROP_0,
+  PROP_LOCATION,
+  PROP_DEBUG,
+  PROP_RETRY,
+  PROP_TCP_TIMEOUT,
+  PROP_RTP_BLOCKSIZE,
+  PROP_USER_AGENT,
+  PROP_AUDIO_PARAM,
+  PROP_VIDEO_PARAM,
+  PROP_HDCP_PARAM,
+  PROP_ENABLE_PAD_PROBE,
+  PROP_LAST
+};
+
+/* commands we send to out loop to notify it of events */
+#define WFD_CMD_OPEN   (1 << 0)
+#define WFD_CMD_PLAY   (1 << 1)
+#define WFD_CMD_PAUSE  (1 << 2)
+#define WFD_CMD_CLOSE  (1 << 3)
+#define WFD_CMD_WAIT   (1 << 4)
+#define WFD_CMD_REQUEST        (1 << 6)
+#define WFD_CMD_LOOP   (1 << 7)
+#define WFD_CMD_ALL         ((WFD_CMD_LOOP << 1) - 1)
+
+#define GST_ELEMENT_PROGRESS(el, type, code, text)      \
+G_STMT_START {                                          \
+  gchar *__txt = _gst_element_error_printf text;        \
+  gst_element_post_message (GST_ELEMENT_CAST (el),      \
+      gst_message_new_progress (GST_OBJECT_CAST (el),   \
+          GST_PROGRESS_TYPE_ ##type, code, __txt));     \
+  g_free (__txt);                                       \
+} G_STMT_END
+
+
+typedef struct _GstWFDConnInfo {
+  gchar              *location;
+  GstRTSPUrl         *url;
+  gchar              *url_str;
+  GstRTSPConnection  *connection;
+  gboolean            connected;
+}GstWFDConnInfo;
+
+#define GST_WFD_BASE_SRC_GET_PRIVATE(obj)  \
+   (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_WFD_BASE_SRC, GstWFDBaseSrcPrivate))
+
+struct _GstWFDBaseSrcPrivate
+{
+  /* state */
+  GstRTSPState       state;
+
+  /* supported RTSP methods */
+  gint               methods;
+
+  /* task and mutex */
+  GstTask         *task;
+  GRecMutex task_rec_lock;
+  gint             pending_cmd;
+  gint             busy_cmd;
+  gboolean do_stop;
+
+  /* properties */
+  gboolean          debug;
+  guint             retry;
+  GTimeVal          tcp_timeout;
+  GTimeVal         *ptcp_timeout;
+  guint             rtp_blocksize;
+  GstStructure *audio_param;
+  GstStructure *video_param;
+  GstStructure *hdcp_param;
+  gchar *user_agent;
+
+  /* Set RTP port */
+  gint primary_rtpport;
+
+  GstWFDConnInfo  conninfo;
+  GstRTSPTransport transport;
+
+  /* RTP Info */
+  guint32       seqbase;
+  guint64       timebase;
+
+  /* stream info */
+  guint video_height;
+  guint video_width;
+  guint video_framerate;
+  gchar * audio_format;
+  guint audio_channels;
+  guint audio_bitwidth;
+  guint audio_frequency;
+};
+
+/* object */
+static void gst_wfd_base_src_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void gst_wfd_base_src_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+
+/* element */
+static GstStateChangeReturn gst_wfd_base_src_change_state (GstElement * element,
+    GstStateChange transition);
+static gboolean gst_wfd_base_src_send_event (GstElement * element, GstEvent * event);
+
+/* bin */
+static void gst_wfd_base_src_handle_message (GstBin * bin, GstMessage * message);
+
+/* pad */
+static gboolean gst_wfd_base_src_handle_src_event (GstPad * pad, GstObject *parent, GstEvent * event);
+static gboolean gst_wfd_base_src_handle_src_query(GstPad * pad, GstObject *parent, GstQuery * query);
+
+/* fundemental functions */
+static GstRTSPResult gst_wfd_base_src_open (GstWFDBaseSrc * src);
+static gboolean gst_wfd_base_src_setup (GstWFDBaseSrc * src);
+static GstRTSPResult gst_wfd_base_src_play (GstWFDBaseSrc * src);
+static GstRTSPResult gst_wfd_base_src_pause (GstWFDBaseSrc * src);
+static GstRTSPResult gst_wfd_base_src_close (GstWFDBaseSrc * src, gboolean only_close);
+static void gst_wfd_base_src_send_pause_cmd (GstWFDBaseSrc * src);
+static void gst_wfd_base_src_send_play_cmd (GstWFDBaseSrc * src);
+static void gst_wfd_base_src_send_close_cmd (GstWFDBaseSrc * src);
+static void gst_wfd_base_src_set_standby (GstWFDBaseSrc * src);
+
+/* URI interface */
+static void gst_wfd_base_src_uri_handler_init (gpointer g_iface,
+    gpointer iface_data);
+static gboolean gst_wfd_base_src_uri_set_uri (GstURIHandler * handler,
+    const gchar * uri, GError **error);
+
+/* task */
+static GstRTSPResult gst_wfd_base_src_loop (GstWFDBaseSrc * src);
+static gboolean gst_wfd_base_src_loop_send_cmd (GstWFDBaseSrc * src, gint cmd,
+    gint mask);
+
+static gboolean gst_wfd_base_src_push_event (GstWFDBaseSrc * src, GstEvent * event);
+static void gst_wfd_base_src_set_tcp_timeout (GstWFDBaseSrc * src, guint64 timeout);
+
+
+static GstRTSPResult
+gst_wfd_base_src_send (GstWFDBaseSrc * src, GstRTSPMessage * request, GstRTSPMessage * response,
+    GstRTSPStatusCode * code);
+
+static GstRTSPResult gst_wfd_base_src_get_video_parameter(GstWFDBaseSrc * src, GstWFDMessage *msg);
+static GstRTSPResult gst_wfd_base_src_get_audio_parameter(GstWFDBaseSrc * src, GstWFDMessage *msg);
+
+/* util */
+static GstRTSPResult _rtsp_message_dump (GstRTSPMessage * msg);
+static const char *_cmd_to_string (guint cmd);
+
+static guint gst_wfd_base_src_signals[LAST_SIGNAL] = { 0 };
+
+static GstBinClass *parent_class = NULL;
+
+static void gst_wfd_base_src_class_init (GstWFDBaseSrcClass * klass);
+static void gst_wfd_base_src_init (GstWFDBaseSrc * src, gpointer g_class);
+static void gst_wfd_base_src_finalize (GObject * object);
+
+GType
+gst_wfd_base_src_get_type (void)
+{
+  static volatile gsize wfd_base_src_type = 0;
+
+  static const GInterfaceInfo urihandler_info = {
+    gst_wfd_base_src_uri_handler_init,
+    NULL,
+    NULL
+  };
+
+  if (g_once_init_enter (&wfd_base_src_type)) {
+    GType object_type;
+    static const GTypeInfo wfd_base_src_info = {
+      sizeof (GstWFDBaseSrcClass),
+      NULL,
+      NULL,
+      (GClassInitFunc) gst_wfd_base_src_class_init,
+      NULL,
+      NULL,
+      sizeof (GstWFDBaseSrc),
+      0,
+      (GInstanceInitFunc) gst_wfd_base_src_init,
+    };
+
+    object_type = g_type_register_static (GST_TYPE_BIN,
+        "GstWFDBaseSrc", &wfd_base_src_info, G_TYPE_FLAG_ABSTRACT);
+
+    g_type_add_interface_static (object_type, GST_TYPE_URI_HANDLER,
+        &urihandler_info);
+
+    g_once_init_leave (&wfd_base_src_type, object_type);
+  }
+  return wfd_base_src_type;
+}
+
+
+static void
+gst_wfd_base_src_class_init (GstWFDBaseSrcClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstElementClass *gstelement_class;
+  GstBinClass *gstbin_class;
+
+  gobject_class = (GObjectClass *) klass;
+  gstelement_class = (GstElementClass *) klass;
+  gstbin_class = (GstBinClass *) klass;
+
+  GST_DEBUG_CATEGORY_INIT (wfdbasesrc_debug, "wfdbasesrc", 0, "Wi-Fi Display Sink Base Source");
+
+  g_type_class_add_private (klass, sizeof (GstWFDBaseSrcPrivate));
+
+  parent_class = g_type_class_peek_parent (klass);
+
+  gobject_class->set_property = gst_wfd_base_src_set_property;
+  gobject_class->get_property = gst_wfd_base_src_get_property;
+  gobject_class->finalize = gst_wfd_base_src_finalize;
+
+  g_object_class_install_property (gobject_class, PROP_LOCATION,
+      g_param_spec_string ("location", "RTSP Location",
+          "Location of the RTSP url to read",
+          DEFAULT_LOCATION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_DEBUG,
+      g_param_spec_boolean ("debug", "Debug",
+          "Dump request and response messages to stdout",
+          DEFAULT_DEBUG, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_RETRY,
+      g_param_spec_uint ("retry", "Retry",
+          "Max number of retries when connecting Wi-Fi Display source",
+          0, G_MAXUINT16, DEFAULT_RETRY,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_TCP_TIMEOUT,
+      g_param_spec_uint64 ("tcp-timeout", "TCP Timeout",
+          "Fail after timeout microseconds on TCP connections (0 = disabled)",
+          0, G_MAXUINT64, DEFAULT_TCP_TIMEOUT,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_RTP_BLOCKSIZE,
+      g_param_spec_uint ("rtp-blocksize", "RTP Blocksize",
+          "RTP package size to suggest to server (0 = disabled)",
+          0, 65536, DEFAULT_RTP_BLOCKSIZE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+   g_object_class_install_property (gobject_class, PROP_USER_AGENT,
+      g_param_spec_string ("user-agent", "User Agent",
+          "User agent specified string", DEFAULT_USER_AGENT,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_AUDIO_PARAM,
+      g_param_spec_boxed ("audio-param", "audio parameters",
+          "A GstStructure mapped for wfd audio parameters, "
+          "See all attributes in WFD specification(wfd-audio-codecs)."
+          "\n                  audio_codec: LPCM:0x01, AAC:0x02, AC3:0x04"
+          "\n                  audio_latency: an integer"
+          "\n                  audio_channels: 2:0x01, 4:0x02, 6:0x04 8:0x08"
+          "\n                  audio_sampling_frequency: 44.1khz:1, 48khz:2\n",
+          GST_TYPE_STRUCTURE, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_VIDEO_PARAM,
+      g_param_spec_boxed ("video-param", "video parameters",
+          "A GstStructure mapped for wfd video parameters, "
+          "See all attributes in WFD specification(wfd-video-formats).\n",
+          GST_TYPE_STRUCTURE, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_HDCP_PARAM,
+      g_param_spec_boxed ("hdcp-param", "HDCP parameters",
+          "A GstStructure mapped for WFD HDCP parameters."
+          "\n                  hdcp_version: none:0, 2.0:1, 2.1:2"
+          "\n                  hdcp_port_no: an integer\n",
+          GST_TYPE_STRUCTURE, G_PARAM_READWRITE));
+
+  g_object_class_install_property (gobject_class, PROP_ENABLE_PAD_PROBE,
+          g_param_spec_boolean ("enable-pad-probe", "Enable Pad Probe",
+              "Enable pad probe for debugging",
+              FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  gst_wfd_base_src_signals[SIGNAL_UPDATE_MEDIA_INFO] =
+      g_signal_new ("update-media-info", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstWFDBaseSrcClass, update_media_info),
+      NULL, NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_STRUCTURE);
+
+  gst_wfd_base_src_signals[SIGNAL_AV_FORMAT_CHANGE] =
+      g_signal_new ("change-av-format", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstWFDBaseSrcClass, change_av_format),
+      NULL, NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER);
+
+  gst_wfd_base_src_signals[SIGNAL_PAUSE] =
+      g_signal_new ("pause", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
+      G_STRUCT_OFFSET (GstWFDBaseSrcClass, pause), NULL, NULL,
+      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  gst_wfd_base_src_signals[SIGNAL_RESUME] =
+      g_signal_new ("resume", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
+      G_STRUCT_OFFSET (GstWFDBaseSrcClass, resume), NULL, NULL,
+      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  gst_wfd_base_src_signals[SIGNAL_CLOSE] =
+      g_signal_new ("close", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
+      G_STRUCT_OFFSET (GstWFDBaseSrcClass, close), NULL, NULL,
+      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  gst_wfd_base_src_signals[SIGNAL_SET_STANDBY] =
+      g_signal_new ("set-standby", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
+      G_STRUCT_OFFSET (GstWFDBaseSrcClass, set_standby), NULL, NULL,
+      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  gstelement_class->send_event =
+      GST_DEBUG_FUNCPTR(gst_wfd_base_src_send_event);
+  gstelement_class->change_state =
+      GST_DEBUG_FUNCPTR(gst_wfd_base_src_change_state);
+
+  gstbin_class->handle_message =
+      GST_DEBUG_FUNCPTR(gst_wfd_base_src_handle_message);
+
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&gst_wfd_base_src_src_template));
+
+  klass->pause = GST_DEBUG_FUNCPTR (gst_wfd_base_src_send_pause_cmd);
+  klass->resume = GST_DEBUG_FUNCPTR (gst_wfd_base_src_send_play_cmd);
+  klass->close = GST_DEBUG_FUNCPTR (gst_wfd_base_src_send_close_cmd);
+  klass->set_standby = GST_DEBUG_FUNCPTR (gst_wfd_base_src_set_standby);
+
+  klass->push_event = GST_DEBUG_FUNCPTR (gst_wfd_base_src_push_event);
+}
+
+static GstStructure *
+gst_wfd_rtsp_set_default_audio_param ()
+{
+  GstStructure *param = NULL;
+  param = gst_structure_new ("audio_param",
+        "audio_codec", G_TYPE_UINT, 0x3,
+        "audio_latency", G_TYPE_UINT, 0x0,
+        "audio_channels", G_TYPE_UINT, 0x3,
+        "audio_sampling_frequency", G_TYPE_UINT, 0x1,
+        NULL);
+
+  return param;
+}
+
+static GstStructure *
+gst_wfd_rtsp_set_default_video_param ()
+{
+  GstStructure *param = NULL;
+  param = gst_structure_new ("video_param",
+        "video_codec", G_TYPE_UINT, 0x1,
+        "video_native_resolution", G_TYPE_UINT, 0x20,
+        "video_cea_support", G_TYPE_UINT, 0x194ab,
+        "video_vesa_support", G_TYPE_UINT, 0x15555555,
+        "video_hh_support", G_TYPE_UINT, 0x555,
+        "video_profile", G_TYPE_UINT, 0x1,
+        "video_level", G_TYPE_UINT, 0x2,
+        "video_latency", G_TYPE_UINT, 0x0,
+        "video_vertical_resolution", G_TYPE_INT, 1200,
+        "video_horizontal_resolution", G_TYPE_INT, 1920,
+        "video_minimum_slicing", G_TYPE_INT, 0,
+        "video_slice_enc_param", G_TYPE_INT, 200,
+        "video_framerate_control_support", G_TYPE_INT, 11,
+        NULL);
+
+  return param;
+}
+
+static void
+gst_wfd_base_src_init (GstWFDBaseSrc * src, gpointer g_class)
+{
+  GstPadTemplate *template = NULL;
+
+#ifdef G_OS_WIN32
+  WSADATA wsa_data;
+
+  if (WSAStartup (MAKEWORD (2, 2), &wsa_data) != 0) {
+    GST_ERROR_OBJECT (src, "WSAStartup failed: 0x%08x", WSAGetLastError ());
+  }
+#endif
+  src->priv = GST_WFD_BASE_SRC_GET_PRIVATE (src);
+
+  g_return_if_fail (src->priv != NULL);
+
+  src->is_ipv6 = FALSE;
+  src->srcpad = NULL;
+
+  src->priv->conninfo.location = g_strdup (DEFAULT_LOCATION);
+  src->priv->conninfo.url_str = NULL;
+  src->priv->debug = DEFAULT_DEBUG;
+  src->priv->retry = DEFAULT_RETRY;
+  gst_wfd_base_src_set_tcp_timeout (src, DEFAULT_TCP_TIMEOUT);
+  src->priv->rtp_blocksize = DEFAULT_RTP_BLOCKSIZE;
+  src->priv->user_agent = g_strdup (DEFAULT_USER_AGENT);
+  src->priv->hdcp_param = NULL;
+  src->priv->audio_param = gst_wfd_rtsp_set_default_audio_param ();
+  src->priv->video_param = gst_wfd_rtsp_set_default_video_param ();
+  src->priv->timebase = -1;
+  src->priv->seqbase = -1;
+  gst_rtsp_transport_init(&src->priv->transport);
+
+  src->enable_pad_probe = FALSE;
+  src->request_param.type = WFD_PARAM_NONE;
+
+  g_rec_mutex_init (&(src->state_rec_lock));
+  g_rec_mutex_init (&(src->priv->task_rec_lock));
+
+  /* create ghost pad for using src pad */
+  template = gst_static_pad_template_get (&gst_wfd_base_src_src_template);
+  src->srcpad = gst_ghost_pad_new_no_target_from_template ("src", template);
+  gst_element_add_pad (GST_ELEMENT_CAST (src), src->srcpad);
+  gst_object_unref (template);
+
+  gst_pad_set_event_function (src->srcpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_base_src_handle_src_event));
+  gst_pad_set_query_function (src->srcpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_base_src_handle_src_query));
+
+  src->caps = gst_static_pad_template_get_caps (&gst_wfd_base_src_src_template);
+  gst_pad_set_caps (src->srcpad, src->caps);
+
+  src->priv->do_stop = FALSE;
+  src->priv->state = GST_RTSP_STATE_INVALID;
+
+  GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_SOURCE);
+}
+
+static void
+gst_wfd_base_src_finalize (GObject * object)
+{
+  GstWFDBaseSrc *src;
+
+  src = GST_WFD_BASE_SRC (object);
+
+  gst_rtsp_url_free (src->priv->conninfo.url);
+  if (src->priv->conninfo.location)
+    g_free (src->priv->conninfo.location);
+  src->priv->conninfo.location = NULL;
+  if (src->priv->conninfo.url_str)
+    g_free (src->priv->conninfo.url_str);
+  src->priv->conninfo.url_str = NULL;
+  if (src->priv->conninfo.location)
+    g_free (src->priv->conninfo.location);
+  src->priv->conninfo.location = NULL;
+  if (src->priv->conninfo.url_str)
+    g_free (src->priv->conninfo.url_str);
+  src->priv->conninfo.url_str = NULL;
+  if (src->priv->user_agent)
+    g_free (src->priv->user_agent);
+  src->priv->user_agent = NULL;
+  if(src->priv->audio_param)
+    gst_structure_free(src->priv->audio_param);
+  src->priv->audio_param = NULL;
+  if(src->priv->video_param)
+    gst_structure_free(src->priv->video_param);
+  src->priv->video_param = NULL;
+  if(src->priv->hdcp_param)
+    gst_structure_free(src->priv->hdcp_param);
+  src->priv->hdcp_param = NULL;
+
+  /* free locks */
+  g_rec_mutex_clear (&(src->state_rec_lock));
+  g_rec_mutex_clear (&(src->priv->task_rec_lock));
+
+#ifdef G_OS_WIN32
+  WSACleanup ();
+#endif
+
+  G_OBJECT_CLASS (parent_class)->finalize (object);
+}
+
+static void
+gst_wfd_base_src_set_tcp_timeout (GstWFDBaseSrc * src, guint64 timeout)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+
+  priv->tcp_timeout.tv_sec = timeout / G_USEC_PER_SEC;
+  priv->tcp_timeout.tv_usec = timeout % G_USEC_PER_SEC;
+
+  if (timeout != 0)
+    priv->ptcp_timeout = &priv->tcp_timeout;
+  else
+    priv->ptcp_timeout = NULL;
+}
+
+static void
+gst_wfd_base_src_set_property (GObject * object, guint prop_id, const GValue * value,
+    GParamSpec * pspec)
+{
+  GstWFDBaseSrc *src = GST_WFD_BASE_SRC (object);
+  GError *err = NULL;
+
+  switch (prop_id) {
+    case PROP_LOCATION:
+      gst_wfd_base_src_uri_set_uri (GST_URI_HANDLER (src),
+          g_value_get_string (value), &err);
+      break;
+    case PROP_DEBUG:
+      src->priv->debug = g_value_get_boolean (value);
+      break;
+    case PROP_RETRY:
+      src->priv->retry = g_value_get_uint (value);
+      break;
+    case PROP_TCP_TIMEOUT:
+      gst_wfd_base_src_set_tcp_timeout (src, g_value_get_uint64 (value));
+      break;
+    case PROP_RTP_BLOCKSIZE:
+      src->priv->rtp_blocksize = g_value_get_uint (value);
+      break;
+    case PROP_USER_AGENT:
+      if (src->priv->user_agent)
+        g_free(src->priv->user_agent);
+      src->priv->user_agent = g_value_dup_string (value);
+      break;
+    case PROP_AUDIO_PARAM:
+    {
+      const GstStructure *s = gst_value_get_structure (value);
+      if (src->priv->audio_param)
+        gst_structure_free (src->priv->audio_param);
+      if (s)
+        src->priv->audio_param = gst_structure_copy (s);
+      else
+        src->priv->audio_param = NULL;
+      break;
+    }
+    case PROP_VIDEO_PARAM:
+    {
+      const GstStructure *s = gst_value_get_structure (value);
+      if (src->priv->video_param)
+        gst_structure_free (src->priv->video_param);
+      if (s)
+        src->priv->video_param = gst_structure_copy (s);
+      else
+        src->priv->video_param = NULL;
+      break;
+    }
+    case PROP_HDCP_PARAM:
+    {
+      const GstStructure *s = gst_value_get_structure (value);
+      if (src->priv->hdcp_param)
+        gst_structure_free (src->priv->hdcp_param);
+      if (s)
+        src->priv->hdcp_param = gst_structure_copy (s);
+      else
+        src->priv->hdcp_param = NULL;
+      break;
+    }
+    case PROP_ENABLE_PAD_PROBE:
+      src->enable_pad_probe = g_value_get_boolean (value);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_wfd_base_src_get_property (GObject * object, guint prop_id, GValue * value,
+    GParamSpec * pspec)
+{
+  GstWFDBaseSrc *src = GST_WFD_BASE_SRC (object);
+
+  switch (prop_id) {
+    case PROP_LOCATION:
+      g_value_set_string (value, src->priv->conninfo.location);
+      break;
+    case PROP_DEBUG:
+      g_value_set_boolean (value, src->priv->debug);
+      break;
+    case PROP_RETRY:
+      g_value_set_uint (value, src->priv->retry);
+      break;
+    case PROP_TCP_TIMEOUT:
+    {
+      guint64 timeout;
+
+      timeout = src->priv->tcp_timeout.tv_sec * (guint64)G_USEC_PER_SEC +
+          src->priv->tcp_timeout.tv_usec;
+      g_value_set_uint64 (value, timeout);
+      break;
+    }
+    case PROP_RTP_BLOCKSIZE:
+      g_value_set_uint (value, src->priv->rtp_blocksize);
+      break;
+    case PROP_USER_AGENT:
+      g_value_set_string (value, src->priv->user_agent);
+      break;
+    case PROP_AUDIO_PARAM:
+      gst_value_set_structure (value, src->priv->audio_param);
+      break;
+    case PROP_VIDEO_PARAM:
+      gst_value_set_structure (value, src->priv->video_param);
+      break;
+    case PROP_HDCP_PARAM:
+      gst_value_set_structure (value, src->priv->hdcp_param);
+      break;
+    case PROP_ENABLE_PAD_PROBE:
+      g_value_set_boolean (value, src->enable_pad_probe);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_wfd_base_src_cleanup (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcClass *klass = NULL;
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (src->caps)
+    gst_caps_unref (src->caps);
+  src->caps = NULL;
+
+  if (klass->cleanup)
+       klass->cleanup(src);
+}
+
+static void
+gst_wfd_base_src_flush (GstWFDBaseSrc * src, gboolean flush)
+{
+  GstWFDBaseSrcClass *klass;
+  GstEvent *event;
+  GstState state;
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (flush) {
+    event = gst_event_new_flush_start ();
+    GST_DEBUG_OBJECT (src, "start flush");
+    state = GST_STATE_PAUSED;
+  } else {
+    event = gst_event_new_flush_stop (FALSE);
+    GST_DEBUG_OBJECT (src, "stop flush");
+    state = GST_STATE_PLAYING;
+  }
+
+  if (klass->push_event)
+    klass->push_event(src, event);
+
+  if (klass->set_state)
+    klass->set_state (src, state);
+}
+
+static GstRTSPResult
+gst_wfd_base_src_connection_send (GstWFDBaseSrc * src,
+    GstRTSPMessage * message, GTimeVal * timeout)
+{
+  GstRTSPResult ret = GST_RTSP_OK;
+
+  if (src->priv->debug)
+    _rtsp_message_dump (message);
+
+  if (src->priv->conninfo.connection)
+    ret = gst_rtsp_connection_send (src->priv->conninfo.connection, message, timeout);
+  else
+    ret = GST_RTSP_ERROR;
+
+  return ret;
+}
+
+static GstRTSPResult
+gst_wfd_base_src_connection_receive (GstWFDBaseSrc * src,
+    GstRTSPMessage * message, GTimeVal * timeout)
+{
+  GstRTSPResult ret;
+
+  if (src->priv->conninfo.connection)
+    ret = gst_rtsp_connection_receive (src->priv->conninfo.connection, message, timeout);
+  else
+    ret = GST_RTSP_ERROR;
+
+  if (src->priv->debug)
+    _rtsp_message_dump (message);
+
+  return ret;
+}
+
+static GstRTSPResult
+gst_wfd_base_src_send_request (GstWFDBaseSrc * src)
+{
+  GstWFDRequestParam request_param = {0};
+  GstRTSPMessage request = { 0 };
+  GstRTSPMessage response = { 0 };
+  GstRTSPResult res = GST_RTSP_OK;
+  GstWFDResult wfd_res = GST_WFD_OK;
+  GstWFDMessage *wfd_msg= NULL;
+  gchar *rtsp_body = NULL;
+  guint rtsp_body_length = 0;
+  GString *rtsp_body_length_str = NULL;
+
+  GST_OBJECT_LOCK(src);
+  if (src->request_param.type==WFD_PARAM_NONE) {
+    GST_DEBUG_OBJECT(src, "nothing to request...");
+    GST_OBJECT_UNLOCK(src);
+    return GST_RTSP_EINVAL;
+  }
+  request_param = src->request_param;
+  memset (&src->request_param, 0, sizeof(GstWFDRequestParam));
+  GST_OBJECT_UNLOCK(src);
+
+  GST_DEBUG_OBJECT (src, "need to send request message with %d parameter", request_param.type);
+
+  res = gst_rtsp_message_init_request (&request, GST_RTSP_SET_PARAMETER,
+    src->priv->conninfo.url_str);
+  if (res < 0)
+    goto error;
+
+  /* Create set_parameter body to be sent in the request */
+  wfd_res = gst_wfd_message_new (&wfd_msg);
+  if(wfd_res != GST_WFD_OK)
+    goto error;
+  wfd_res = gst_wfd_message_init (wfd_msg);
+  if(wfd_res != GST_WFD_OK)
+    goto error;
+
+  switch(request_param.type) {
+    case WFD_ROUTE:
+     /* Note : RTSP M10  :
+      *   Send RTSP SET_PARAMETER with wfd-route to change the WFD sink at which audio is rendered.
+      *   Applies only when both a primary and secondary sinks are in WFD session with a WFD source.
+      */
+      wfd_res = gst_wfd_message_set_audio_sink_type (wfd_msg, request_param.route_setting.type);
+      if(wfd_res != GST_WFD_OK)
+        goto error;
+      break;
+
+    case WFD_CONNECTOR_TYPE:
+     /* Note : RTSP M11  :
+      *   Send RTSP SET_PARAMETER with wfd-connector-type to indicate change of active connector type,
+      *     when the WFD source and WFD sink support content protection.
+      */
+      wfd_res = gst_wfd_message_set_connector_type (wfd_msg, request_param.connector_setting.type);
+      if(wfd_res != GST_WFD_OK)
+        goto error;
+      break;
+
+    case WFD_STANDBY:
+     /* Note : RTSP M12  :
+      *   Send RTSP SET_PARAMETER with wfd-standby to indicate that the sender is entering WFD standby mode.
+      */
+      wfd_res = gst_wfd_message_set_standby (wfd_msg, TRUE);
+      if(wfd_res != GST_WFD_OK)
+        goto error;
+      break;
+
+    case WFD_IDR_REQUEST:
+     /* Note : RTSP M13  :
+      *   Send RTSP SET_PARAMETER with wfd-idr-request to request IDR refresh.
+      */
+      wfd_res = gst_wfd_message_set_idr_request (wfd_msg);
+      if(wfd_res != GST_WFD_OK)
+        goto error;
+      break;
+
+    default:
+      GST_ERROR_OBJECT (src, "Unhandled WFD message type...");
+      goto error;
+      break;
+  }
+
+  //gst_wfd_message_dump (wfd_msg);
+  rtsp_body = gst_wfd_message_as_text (wfd_msg);
+  if (rtsp_body == NULL) {
+    GST_ERROR ("gst_wfd_message_as_text is failed");
+    goto error;
+  }
+
+  rtsp_body_length = strlen(rtsp_body);
+  rtsp_body_length_str = g_string_new ("");
+  g_string_append_printf (rtsp_body_length_str,"%d",rtsp_body_length);
+
+  GST_DEBUG ("WFD message body: %s", rtsp_body);
+
+  /* add content-length type */
+  gst_rtsp_message_add_header (&request, GST_RTSP_HDR_CONTENT_LENGTH, g_string_free (rtsp_body_length_str, FALSE));
+
+  /* adding wfdrtsp data to request */
+  res = gst_rtsp_message_set_body (&request,(guint8 *)rtsp_body, rtsp_body_length);
+  if (res != GST_RTSP_OK) {
+    GST_ERROR_OBJECT (src, "Failed to set body to rtsp request...");
+    goto error;
+  }
+
+  gst_wfd_message_free (wfd_msg);
+
+  /* send request message  */
+  GST_DEBUG_OBJECT (src, "send reuest...");
+  if ((res = gst_wfd_base_src_send (src, &request, &response,
+      NULL)) < 0)
+    goto error;
+
+  return res;
+
+/* ERRORS */
+error:
+ {
+    if(wfd_msg)
+      gst_wfd_message_free(wfd_msg);
+    gst_rtsp_message_unset (&request);
+    gst_rtsp_message_unset (&response);
+    if(wfd_res != GST_WFD_OK) {
+      GST_ERROR_OBJECT(src, "Message config error : %d", wfd_res);
+      return GST_RTSP_ERROR;
+    }
+    return res;
+ }
+}
+
+static gboolean
+gst_wfd_base_src_handle_src_event (GstPad * pad, GstObject *parent, GstEvent * event)
+{
+  GstWFDBaseSrc *src;
+  gboolean res = TRUE;
+  gboolean forward = FALSE;
+  const GstStructure *s;
+
+  src = GST_WFD_BASE_SRC_CAST (parent);
+  if(src == NULL)  {
+    GST_ERROR_OBJECT (src, "src is NULL.");
+    return FALSE;
+  }
+
+  //GST_DEBUG_OBJECT (src, "pad %s:%s received event %s",
+  //    GST_DEBUG_PAD_NAME (pad), GST_EVENT_TYPE_NAME (event));
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_QOS:
+    case GST_EVENT_NAVIGATION:
+    case GST_EVENT_LATENCY:
+      break;
+    case GST_EVENT_CUSTOM_UPSTREAM:
+      s = gst_event_get_structure (event);
+      if (gst_structure_has_name (s, "GstWFDIDRRequest")) {
+        /* Send IDR request */
+        GST_OBJECT_LOCK(src);
+        src->request_param.type = WFD_IDR_REQUEST;
+        GST_OBJECT_UNLOCK(src);
+        gst_wfd_base_src_loop_send_cmd(src, WFD_CMD_REQUEST, WFD_CMD_LOOP);
+      }
+      break;
+    default:
+      forward = TRUE;
+      break;
+  }
+
+  if (forward) {
+    GstPad *target;
+
+    if ((target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad)))) {
+      res = gst_pad_send_event (target, event);
+      gst_object_unref (target);
+    } else {
+      gst_event_unref (event);
+    }
+  } else {
+    gst_event_unref (event);
+  }
+
+  return res;
+}
+
+/* this query is executed on the ghost source pad exposed on manager. */
+static gboolean
+gst_wfd_base_src_handle_src_query (GstPad * pad, GstObject *parent, GstQuery * query)
+{
+  GstWFDBaseSrc *src = NULL;
+  gboolean res = FALSE;
+
+  src = GST_WFD_BASE_SRC_CAST (parent);
+  if(src == NULL)
+  {
+    GST_ERROR_OBJECT (src, "src is NULL.");
+    return res;
+  }
+
+  //GST_DEBUG_OBJECT (src, "pad %s:%s received query %s",
+  //    GST_DEBUG_PAD_NAME (pad), GST_QUERY_TYPE_NAME (query));
+
+  switch (GST_QUERY_TYPE (query)) {
+    case GST_QUERY_URI:
+    {
+      if (src->priv->conninfo.location == NULL) {
+        res = FALSE;
+      } else {
+        gst_query_set_uri( query, src->priv->conninfo.location);
+        res = TRUE;
+      }
+      break;
+    }
+    default:
+    {
+      GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (pad));
+
+      /* forward the query to the proxy target pad */
+      if (target) {
+        res = gst_pad_query (target, query);
+        gst_object_unref (target);
+      }
+      break;
+    }
+  }
+
+  return res;
+}
+
+static void
+gst_wfd_base_src_configure_caps (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstCaps *caps;
+  GstStructure *structure;
+
+  GST_DEBUG_OBJECT (src, "configuring caps");
+
+  if ((caps = src->caps)) {
+    caps = gst_caps_make_writable (caps);
+    structure = gst_caps_get_structure (caps, 0);
+    /* update caps */
+    if (priv->timebase != -1)
+      gst_caps_set_simple (caps, "clock-base", G_TYPE_UINT,
+          (guint) priv->timebase, NULL);
+    if (priv->seqbase != -1)
+      gst_caps_set_simple (caps, "seqnum-base", G_TYPE_UINT,
+          (guint) priv->seqbase, NULL);
+    gst_structure_set (structure, "height", G_TYPE_INT, priv->video_height, NULL);
+    gst_structure_set (structure, "width", G_TYPE_INT, priv->video_width, NULL);
+    gst_structure_set (structure, "video-framerate", G_TYPE_INT, priv->video_framerate, NULL);
+
+    src->caps = caps;
+  }
+
+  if (src->srcpad) {
+    GST_DEBUG_OBJECT (src, "set caps for srcpad");
+    gst_pad_set_caps(src->srcpad, src->caps);
+  }
+}
+
+static gboolean
+gst_wfd_base_src_push_event (GstWFDBaseSrc * src, GstEvent * event)
+{
+  gboolean res = TRUE;
+
+  g_return_val_if_fail(GST_IS_EVENT(event), FALSE);
+
+  if (src ->srcpad) {
+    gst_event_ref (event);
+    res = gst_pad_push_event (src ->srcpad, event);
+  }
+
+  gst_event_unref (event);
+
+  return res;
+}
+
+static GstRTSPResult
+gst_wfd_base_src_conninfo_connect (GstWFDBaseSrc * src, GstWFDConnInfo * info)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPResult res;
+
+  if (info->connection == NULL) {
+    if (info->url == NULL) {
+      GST_DEBUG_OBJECT (src, "parsing uri (%s)...", info->location);
+      if ((res = gst_rtsp_url_parse (info->location, &info->url)) < 0)
+        goto parse_error;
+    }
+
+    /* create connection */
+    GST_DEBUG_OBJECT (src, "creating connection (%s)...", info->location);
+    if ((res = gst_rtsp_connection_create (info->url, &info->connection)) < 0)
+      goto could_not_create;
+
+    if (info->url_str)
+      g_free (info->url_str);
+    info->url_str = gst_rtsp_url_get_request_uri (info->url);
+
+    GST_DEBUG_OBJECT (src, "sanitized uri %s", info->url_str);
+  }
+
+  if (!info->connected) {
+    /* connect */
+    GST_DEBUG_OBJECT (src, "connecting (%s)...", info->location);
+    int retry = 0;
+connect_retry:
+    if (priv->do_stop) {
+      GST_ERROR_OBJECT (src, "stop connecting....");
+      return GST_RTSP_EINTR;
+    }
+
+    if ((res =
+            gst_rtsp_connection_connect (info->connection,
+                priv->ptcp_timeout)) < 0) {
+      if (retry < priv->retry) {
+        GST_ERROR_OBJECT(src, "Connection failed... Try again...");
+        usleep(100000);
+        retry++;
+        goto connect_retry;
+      } else {
+        goto could_not_connect;
+      }
+    } else {
+      GST_INFO_OBJECT(src, "Connection success");
+    }
+
+    info->connected = TRUE;
+  }
+  return GST_RTSP_OK;
+
+  /* ERRORS */
+parse_error:
+  {
+    GST_ERROR_OBJECT (src, "No valid RTSP URL was provided");
+    return res;
+  }
+could_not_create:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+    GST_ERROR_OBJECT (src, "Could not create connection. (%s)", str);
+    g_free (str);
+    return res;
+  }
+could_not_connect:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+    GST_ERROR_OBJECT (src, "Could not connect to server. (%s)", str);
+    g_free (str);
+    return res;
+  }
+}
+
+static GstRTSPResult
+gst_wfd_base_src_conninfo_close (GstWFDBaseSrc * src, GstWFDConnInfo * info,
+    gboolean free)
+{
+  g_return_val_if_fail (info, GST_RTSP_EINVAL);
+
+  GST_WFD_BASE_STATE_LOCK (src);
+  if (info->connected) {
+    GST_DEBUG_OBJECT (src, "closing connection...");
+    gst_rtsp_connection_close (info->connection);
+    info->connected = FALSE;
+  }
+  if (free && info->connection) {
+    /* free connection */
+    GST_DEBUG_OBJECT (src, "freeing connection...");
+    gst_rtsp_connection_free (info->connection);
+    info->connection = NULL;
+  }
+  GST_WFD_BASE_STATE_UNLOCK (src);
+  return GST_RTSP_OK;
+}
+
+static void
+gst_wfd_base_src_connection_flush (GstWFDBaseSrc * src, gboolean flush)
+{
+  GST_DEBUG_OBJECT (src, "set flushing %d", flush);
+  GST_WFD_BASE_STATE_LOCK (src);
+  if (src->priv->conninfo.connection) {
+    GST_DEBUG_OBJECT (src, "connection flush %d", flush);
+    gst_rtsp_connection_flush (src->priv->conninfo.connection, flush);
+  }
+  GST_WFD_BASE_STATE_UNLOCK (src);
+}
+
+static GstRTSPResult
+gst_wfd_base_src_handle_request (GstWFDBaseSrc * src, GstRTSPMessage * request)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDBaseSrcClass *klass = NULL;
+  GstRTSPMethod method = GST_RTSP_INVALID;
+  GstRTSPVersion version = GST_RTSP_VERSION_INVALID;
+  GstRTSPMessage response = { 0 };
+  GstRTSPResult res = GST_RTSP_OK;
+  GstWFDResult wfd_res = GST_WFD_OK;
+  const gchar *uristr;
+  guint8 *data = NULL;
+  guint size = 0;
+  GstWFDMessage *wfd_msg = NULL;
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  res = gst_rtsp_message_parse_request (request, &method, &uristr, &version);
+  if (res < 0)
+    goto send_error;
+
+  if (version != GST_RTSP_VERSION_1_0) {
+    /* we can only handle 1.0 requests */
+    res = GST_RTSP_ENOTIMPL;
+    goto send_error;
+  }
+
+  GST_DEBUG_OBJECT (src, "got %s request", gst_rtsp_method_as_text(method));
+
+  switch(method) {
+    case GST_RTSP_OPTIONS:
+    {
+      /* Note : RTSP M1 :
+       *   A WFD source shall send an RTSP M1 request to a WFD sink to begin the RTSP procedures and a WFD Capability Negotiation.
+       *   A WFD sink shall respond with an RTSP M1 response message which contains an RTSP OPTIONS.
+       */
+      gchar *options_str = NULL;
+      GstRTSPMethod options = 0;
+      gchar *str = NULL;
+
+      options = GST_RTSP_GET_PARAMETER | GST_RTSP_SET_PARAMETER | GST_RTSP_TEARDOWN | GST_RTSP_OPTIONS
+      | GST_RTSP_PLAY | GST_RTSP_PAUSE | GST_RTSP_SETUP;
+
+      str = gst_rtsp_options_as_text (options);
+      if (!str) {
+        GST_ERROR ("Failed to make options string, str is NULL.");
+        res = GST_RTSP_ENOMEM;
+        goto send_error;
+      }
+
+      options_str = g_strconcat ((const gchar*)str, ", org.wfa.wfd1.0", NULL);
+      if (!options_str) {
+       GST_ERROR ("Failed to make options string.");
+       res = GST_RTSP_ENOMEM;
+       g_free(str);
+       goto send_error;
+      }
+      g_free(str);
+
+      res = gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK,
+         gst_rtsp_status_as_text (GST_RTSP_STS_OK), request);
+      if(res < 0) {
+       g_free (options_str);
+       goto send_error;
+      }
+      gst_rtsp_message_add_header (&response, GST_RTSP_HDR_PUBLIC, options_str);
+      gst_rtsp_message_add_header (&response, GST_RTSP_HDR_USER_AGENT, (const gchar*)priv->user_agent);
+      g_free (options_str);
+
+      break;
+    }
+
+    case GST_RTSP_GET_PARAMETER:
+    {
+      gchar *rtsp_body = NULL;
+      guint rtsp_body_length = 0;
+      GString *rtsp_body_length_str = NULL;
+
+      res = gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, gst_rtsp_status_as_text (GST_RTSP_STS_OK), request);
+      if (res < 0)
+        goto send_error;
+
+      gst_rtsp_message_add_header (&response, GST_RTSP_HDR_CONTENT_TYPE, "text/parameters");
+
+      res = gst_rtsp_message_get_body (request, &data, &size);
+      if (res < 0)
+        goto send_error;
+
+      if (size==0) {
+        /* Note : RTSP M16 : WFD keep-alive :
+         *   The WFD keep-alive function is used to periodically ensure the status of WFD sesion.
+         *   A WFD source indicates the timeout value via the "Session:" line in the RTSP M6 response.
+         *   A WFD sink shall respond with an RTSP M16 request message upon successful receiving the RTSP M16 request message.
+         */
+        res = gst_rtsp_connection_reset_timeout (priv->conninfo.connection);
+        if (res < 0)
+          goto send_error;
+        break;
+      }
+      wfd_res = gst_wfd_message_new (&wfd_msg);
+      if (wfd_res != GST_WFD_OK) {
+        GST_ERROR ("gst_wfd_message_new is failed");
+        goto message_config_error;
+      }
+      wfd_res = gst_wfd_message_init (wfd_msg);
+      if (wfd_res != GST_WFD_OK) {
+        GST_ERROR ("gst_wfd_message_init is failed");
+        goto message_config_error;
+      }
+      wfd_res = gst_wfd_message_parse_buffer (data, size, wfd_msg);
+      if (wfd_res != GST_WFD_OK) {
+        GST_ERROR ("gst_wfd_message_parse_buffer is failed");
+        goto message_config_error;
+      }
+      //gst_wfd_message_dump (wfd_msg);
+
+      if (!wfd_msg)
+        goto message_config_error;
+
+      /* Note : RTSP M3 :
+       *   The WFD source shall send RTSP M3 request to the WFD sink to query the WFD sink's attributes and capabilities.
+       *   A WFD sink shall respond with an RTSP M3 response message which contains the values of the requested parameters.
+       *   The WFD source may query all parameters at once with a single RTSP M3 request message or may send separate RTSP M3 request message.
+       *   The WFD sink shall only response with formats and settings that it can accept in the following RTSP M4 message exchnage.
+       */
+      /* Note : wfd-audio-codecs :
+       *    The wfd-audio-codecs parameter specifies the audio formats supported in the WFD session.
+       *    Valid audio codecs are LPCM, AAC, AC3.
+       *    Primary sink should support one of audio codecs.
+       */
+      if(wfd_msg->audio_codecs) {
+        guint audio_codec = 0;
+        guint audio_sampling_frequency = 0;
+        guint audio_channels = 0;
+        guint audio_latency = 0;
+
+        if(priv->audio_param != NULL) {
+          GstStructure *audio_param = priv->audio_param;
+          if (gst_structure_has_field (audio_param, "audio_codec"))
+            gst_structure_get_uint (audio_param, "audio_codec", &audio_codec);
+          if (gst_structure_has_field (audio_param, "audio_latency"))
+            gst_structure_get_uint (audio_param, "audio_latency", &audio_latency);
+          if (gst_structure_has_field (audio_param, "audio_channels"))
+            gst_structure_get_uint (audio_param, "audio_channels", &audio_channels);
+          if (gst_structure_has_field (audio_param, "audio_sampling_frequency"))
+            gst_structure_get_uint (audio_param, "audio_sampling_frequency", &audio_sampling_frequency);
+        }
+
+        wfd_res = gst_wfd_message_set_supported_audio_format (wfd_msg,
+          audio_codec,
+          audio_sampling_frequency,
+          audio_channels,
+          16,
+          audio_latency);
+        if (wfd_res != GST_WFD_OK) {
+          GST_ERROR ("gst_wfd_message_set_supported_audio_format is failed");
+          goto message_config_error;
+        }
+      }
+
+      /* Note : wfd-video-formats :
+       *    The wfd-video-formats parameter specifies the supported video resolutions,
+       *    H.644 codec profile, level, decoder latency,  minimum slice size, slice encoding parameters
+       *      and support for video frame rate control (including explicit frame rate change and implicit video frame skipping.
+       */
+      if(wfd_msg->video_formats) {
+        guint video_codec = 0;
+        guint video_native_resolution = 0;
+        guint video_cea_support = 0;
+        guint video_vesa_support = 0;
+        guint video_hh_support = 0;
+        guint video_profile = 0;
+        guint video_level = 0;
+        guint video_latency = 0;
+        gint video_vertical_resolution = 0;
+        gint video_horizontal_resolution = 0;
+        gint video_minimum_slicing = 0;
+        gint video_slice_enc_param = 0;
+        gint video_framerate_control_support = 0;
+
+        if (priv->video_param != NULL) {
+          GstStructure *video_param = priv->video_param;
+
+          if (gst_structure_has_field (video_param, "video_codec"))
+            gst_structure_get_uint (video_param, "video_codec", &video_codec);
+          if (gst_structure_has_field (video_param, "video_native_resolution"))
+            gst_structure_get_uint (video_param, "video_native_resolution", &video_native_resolution);
+          if (gst_structure_has_field (video_param, "video_cea_support"))
+            gst_structure_get_uint (video_param, "video_cea_support", &video_cea_support);
+          if (gst_structure_has_field (video_param, "video_vesa_support"))
+            gst_structure_get_uint (video_param, "video_vesa_support", &video_vesa_support);
+          if (gst_structure_has_field (video_param, "video_hh_support"))
+            gst_structure_get_uint (video_param, "video_hh_support", &video_hh_support);
+          if (gst_structure_has_field (video_param, "video_profile"))
+            gst_structure_get_uint (video_param, "video_profile", &video_profile);
+          if (gst_structure_has_field (video_param, "video_level"))
+            gst_structure_get_uint (video_param, "video_level", &video_level);
+          if (gst_structure_has_field (video_param, "video_latency"))
+            gst_structure_get_uint (video_param, "video_latency", &video_latency);
+          if (gst_structure_has_field (video_param, "video_vertical_resolution"))
+            gst_structure_get_int (video_param, "video_vertical_resolution", &video_vertical_resolution);
+          if (gst_structure_has_field (video_param, "video_horizontal_resolution"))
+            gst_structure_get_int (video_param, "video_horizontal_resolution", &video_horizontal_resolution);
+          if (gst_structure_has_field (video_param, "video_minimum_slicing"))
+            gst_structure_get_int (video_param, "video_minimum_slicing", &video_minimum_slicing);
+          if (gst_structure_has_field (video_param, "video_slice_enc_param"))
+            gst_structure_get_int (video_param, "video_slice_enc_param", &video_slice_enc_param);
+          if (gst_structure_has_field (video_param, "video_framerate_control_support"))
+            gst_structure_get_int (video_param, "video_framerate_control_support", &video_framerate_control_support);
+        }
+
+        wfd_res = gst_wfd_message_set_supported_video_format (wfd_msg,
+            video_codec,
+            GST_WFD_VIDEO_CEA_RESOLUTION,
+            video_native_resolution,
+            video_cea_support,
+            video_vesa_support,
+            video_hh_support,
+            video_profile,
+            video_level,
+            video_latency,
+            video_vertical_resolution,
+            video_horizontal_resolution,
+            video_minimum_slicing,
+            video_slice_enc_param,
+            video_framerate_control_support,
+            GST_WFD_PREFERRED_DISPLAY_MODE_NOT_SUPPORTED);
+        if (wfd_res != GST_WFD_OK) {
+          GST_ERROR ("gst_wfd_message_set_supported_video_format is failed");
+          goto message_config_error;
+        }
+      }
+
+      /* Note : wfd-3d-formats :
+       *    The wfd-3d-formats parameter specifies the support for stereoscopic video capabilities.
+       */
+      if(wfd_msg->video_3d_formats) {
+        /* TODO : Set preferred video_3d_formats */
+        wfd_res = GST_WFD_OK;
+      }
+
+      /* Note : wfd-content-protection :
+       *   The wfd-content-protection parameter specifies whether the WFD sink supports the HDCP system 2.0/2.1 for content protection.
+       */
+     if(wfd_msg->content_protection) {
+        gint hdcp_version = 0;
+        gint hdcp_port_no = 0;
+
+        if (priv->hdcp_param != NULL) {
+          GstStructure *hdcp_param = priv->hdcp_param;
+
+          if (gst_structure_has_field (hdcp_param, "hdcp_version"))
+            gst_structure_get_int (hdcp_param, "hdcp_version", &hdcp_version);
+          if (gst_structure_has_field (hdcp_param, "hdcp_port_no"))
+            gst_structure_get_int (hdcp_param, "hdcp_port_no", &hdcp_port_no);
+        }
+
+        wfd_res = gst_wfd_message_set_contentprotection_type (wfd_msg,
+          hdcp_version,
+          (guint32)hdcp_port_no);
+        if (wfd_res != GST_WFD_OK) {
+          GST_ERROR ("gst_wfd_message_set_contentprotection_type is failed");
+          goto message_config_error;
+        }
+      }
+
+      /* Note : wfd-display-edid :
+       *   The wfd-display-edid parameter specifies the EDID of the display on which the content will be rendered.
+       *   EDID data comes in multiples of 128-byte blocks of EDID data depending on the EDID structure that it supports.
+       *   If a WFD sink reports wfd-connector-type as HDMI or DP or UDI, the WFD sink should return the EDID of the display that renders the streamed video.
+       *   The WFD sink dongle without an integrated display or with an integrated display that is not being used to render streamed video
+       *     shall not set the edid filed of the wfd-display-edid paramter to "none" regardless of whether an external display devices is attached or not.
+       */
+      if(wfd_msg->display_edid) {
+        /* TODO: Set preferred display_edid */
+        wfd_res = gst_wfd_message_set_display_EDID (wfd_msg,
+                     FALSE,
+                     0,
+                     NULL);
+        if (wfd_res != GST_WFD_OK) {
+          GST_ERROR ("gst_wfd_message_set_display_EDID is failed");
+          goto message_config_error;
+        }
+      }
+
+      /* Note : wfd-coupled-sink :
+       *   The wfd-coupled-sink parameter is used by a WFD sink to convey its coupled status
+       *     and if coupled to another WFD sink, the coupled WFD sink's MAC address
+       */
+      if(wfd_msg->coupled_sink) {
+        /* To test with dummy coupled sink address */
+        wfd_res = gst_wfd_message_set_coupled_sink (wfd_msg,
+          GST_WFD_SINK_COUPLED,
+          (gchar *)"1.0.0.1:435");
+        if (wfd_res != GST_WFD_OK) {
+          GST_ERROR ("gst_wfd_message_set_coupled_sink is failed");
+          goto message_config_error;
+        }
+      }
+
+      /* Note : wfd-client-rtp-ports :
+       *   The wfd-coupled-sink parameter is used by a WFD sink to convey the RTP port(s) that the WFD sink is listening on
+       *     and by the a WFD source to indicate how audio, video or both audio and video payload will be encapsulated in the MPEG2-TS stream
+       *     transmitted from the WFD source to the WFD sink.
+       */
+      if(wfd_msg->client_rtp_ports) {
+        /* Hardcoded as of now. This is to comply with dongle port settings.
+        This should be derived from gst_wfd_base_src_alloc_udp_ports */
+        priv->primary_rtpport = 19000;
+        wfd_res = gst_wfd_message_set_prefered_RTP_ports (wfd_msg,
+          GST_WFD_RTSP_TRANS_RTP,
+          GST_WFD_RTSP_PROFILE_AVP,
+          GST_WFD_RTSP_LOWER_TRANS_UDP,
+          priv->primary_rtpport,
+          0);
+        if (wfd_res != GST_WFD_OK) {
+          GST_ERROR ("gst_wfd_message_set_prefered_RTP_ports is failed");
+          goto message_config_error;
+        }
+      }
+
+      /* Note : wfd-I2C :
+       *   The wfd-I2C parameter is used by a WFD source to inquire whether a WFD sink supports remote I2C read/write function or not.
+       *   If the WFD sink supports remote I2C read/write function, it shall set the value of this parameter to the TCP port number
+       *     to be used by the WFD source to exchange remote I2C read/write messaging transactions with the WFD sink.
+       */
+      if(wfd_msg->I2C) {
+        /* TODO */
+        wfd_res = GST_WFD_OK;
+      }
+
+      /* Note : wfd-connector-type :
+       *   The WFD source may send wfd-connector-type parameter to inquire about the connector type that is currently active in the WFD sink.
+       *   The WFD sink shall not send wfd-connector-type parameter unless the WFD source support this parameter.
+       *   The WFD sink dongle that is not connected to an external display and it is not acting as a WFD sink with embedded display
+       *     (to render streamed content) shall return a value of "none". Otherwise, the WFD sink shall choose a non-reserved value.
+       */
+      if(wfd_msg->connector_type) {
+        /* TODO */
+        wfd_res = GST_WFD_OK;
+      }
+
+      /* Note : wfd-standby-resume-capability :
+       *   The wfd-standby-resume-capability parameter describes support of both standby control using
+       *     a wfd-standby parameter and resume control using PLAY and using triggered-method setting PLAY.
+       */
+      if(wfd_msg->standby_resume_capability) {
+        /* TODO */
+        wfd_res = GST_WFD_OK;
+      }
+
+      rtsp_body = gst_wfd_message_as_text (wfd_msg);
+      if (rtsp_body == NULL) {
+        GST_ERROR ("gst_wfd_message_as_text is failed");
+        goto message_config_error;
+      }
+      rtsp_body_length = strlen(rtsp_body);
+      rtsp_body_length_str = g_string_new ("");
+      g_string_append_printf (rtsp_body_length_str,"%d", rtsp_body_length);
+
+      gst_rtsp_message_add_header (&response, GST_RTSP_HDR_CONTENT_LENGTH, g_string_free (rtsp_body_length_str, FALSE));
+
+      res = gst_rtsp_message_set_body (&response, (guint8*)rtsp_body, rtsp_body_length);
+      if (res < 0)
+        goto send_error;
+
+      if (klass->handle_get_parameter) {
+        GST_DEBUG_OBJECT(src, "try to handle more GET_PARAMETER parameter");
+        res = klass->handle_get_parameter(src, request, &response);
+        if (res < 0)
+          goto send_error;
+      }
+      break;
+    }
+
+    case GST_RTSP_SET_PARAMETER:
+    {
+      res = gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, gst_rtsp_status_as_text (GST_RTSP_STS_OK), request);
+      if (res < 0)
+        goto send_error;
+
+      res = gst_rtsp_message_get_body (request, &data, &size);
+      if (res < 0)
+        goto send_error;
+
+      wfd_res = gst_wfd_message_new (&wfd_msg);
+      if (wfd_res != GST_WFD_OK)
+        goto message_config_error;    
+      wfd_res = gst_wfd_message_init (wfd_msg);
+      if (wfd_res != GST_WFD_OK)
+        goto message_config_error; 
+      wfd_res = gst_wfd_message_parse_buffer (data, size, wfd_msg);
+      if (wfd_res != GST_WFD_OK)
+        goto message_config_error;
+      //gst_wfd_message_dump (wfd_msg);
+
+      if (!wfd_msg)
+        goto message_config_error;
+
+     /* Note : RTSP M4 :
+       */
+      /* Note : wfd-trigger-method :
+       *   The wfd-trigger-method parameter is used by a WFD source to trigger the WFD sink to initiate an operation with the WFD source.
+       */
+      if (wfd_msg->trigger_method) {
+        GstWFDTrigger trigger = GST_WFD_TRIGGER_UNKNOWN;
+
+        wfd_res = gst_wfd_message_get_trigger_type (wfd_msg, &trigger);
+        if (wfd_res != GST_WFD_OK)
+          goto message_config_error;
+
+        res = gst_wfd_base_src_connection_send (src, &response, NULL);
+        if (res < 0)
+          goto send_error;
+
+        GST_DEBUG_OBJECT (src, "got trigger method for %s", GST_STR_NULL(wfd_msg->trigger_method->wfd_trigger_method));
+        switch(trigger) {
+          case GST_WFD_TRIGGER_PAUSE:
+            gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_PAUSE, WFD_CMD_LOOP);
+            break;
+          case GST_WFD_TRIGGER_PLAY:
+            gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_PLAY, WFD_CMD_LOOP);
+            break;
+          case GST_WFD_TRIGGER_TEARDOWN:
+            gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_CLOSE, WFD_CMD_ALL);
+            break;
+          case GST_WFD_TRIGGER_SETUP:
+            if (!gst_wfd_base_src_setup (src))
+              goto setup_failed;
+            break;
+          default:
+            break;
+        }
+        goto done;
+      }
+
+      if (wfd_msg->audio_codecs || wfd_msg->video_formats || wfd_msg->video_3d_formats) {
+        GstStructure *stream_info = gst_structure_new ("WFDStreamInfo", NULL, NULL);
+
+        if(wfd_msg->audio_codecs) {
+          res = gst_wfd_base_src_get_audio_parameter(src, wfd_msg);
+          if(res != GST_RTSP_OK) {
+            goto message_config_error;
+          }
+
+          gst_structure_set (stream_info,
+              "audio_format", G_TYPE_STRING, priv->audio_format,
+              "audio_channels", G_TYPE_INT, priv->audio_channels,
+              "audio_rate", G_TYPE_INT, priv->audio_frequency,
+              "audio_bitwidth", G_TYPE_INT, priv->audio_bitwidth/16,
+              NULL);
+        }
+
+        if(wfd_msg->video_formats) {
+          res = gst_wfd_base_src_get_video_parameter(src, wfd_msg);
+          if(res != GST_RTSP_OK) {
+            goto message_config_error;
+          }
+
+          gst_structure_set (stream_info,
+              "video_format", G_TYPE_STRING, "H264",
+              "video_width", G_TYPE_INT, priv->video_width,
+              "video_height", G_TYPE_INT, priv->video_height,
+              "video_framerate", G_TYPE_INT, priv->video_framerate,
+              NULL);
+        }
+
+        if(wfd_msg->video_3d_formats) {
+        /* TO DO */
+        }
+        g_signal_emit (src, gst_wfd_base_src_signals[SIGNAL_UPDATE_MEDIA_INFO], 0, stream_info);
+      }
+
+      /* Note : wfd-presentation-url :
+       *   The wfd-presentation-url parameter describes the Universial Resource Identified (URI)
+       *     to be used in the RTSP Setup (RTSP M6) request message in order to setup the WFD session from the WFD sink to the WFD source.
+       */
+      if(wfd_msg->presentation_url) {
+        gchar *url0 = NULL, *url1 = NULL;
+
+        wfd_res = gst_wfd_message_get_presentation_url (wfd_msg, &url0, &url1);
+        if(wfd_res != GST_WFD_OK) {
+          goto message_config_error;
+        }
+
+        g_free (priv->conninfo.location);
+        priv->conninfo.location = g_strdup (url0);
+        /* url1 is ignored as of now */
+      }
+
+      /* Note : wfd-client-rtp-ports :
+       *   The wfd-coupled-sink parameter is used by a WFD sink to convey the RTP port(s) that the WFD sink is listening on
+       *     and by the a WFD source to indicate how audio, video or both audio and video payload will be encapsulated in the MPEG2-TS stream
+       *     transmitted from the WFD source to the WFD sink.
+       */
+      if(wfd_msg->client_rtp_ports) {
+        GstWFDRTSPTransMode trans = GST_WFD_RTSP_TRANS_UNKNOWN;
+        GstWFDRTSPProfile profile = GST_WFD_RTSP_PROFILE_UNKNOWN;
+        GstWFDRTSPLowerTrans lowertrans = GST_WFD_RTSP_LOWER_TRANS_UNKNOWN;
+        guint32 rtp_port0 =0, rtp_port1 =0;
+
+        wfd_res = gst_wfd_message_get_prefered_RTP_ports (wfd_msg, &trans, &profile, &lowertrans, &rtp_port0, &rtp_port1);
+        if(wfd_res != GST_WFD_OK) {
+          goto message_config_error;
+        }
+        priv->transport.trans = trans;
+        priv->transport.profile = profile;
+        priv->transport.lower_transport = lowertrans;
+        priv->transport.client_port.min = rtp_port0;
+        priv->transport.client_port.max = rtp_port0+1;
+      }
+
+      /* Note : wfd-preferred-display-mode :
+       *   The wfd-preferred-display-mode-supported field in a wfd-video-formats and/or in a wfd-3d-formats parameter in an RTSP M3 response message
+       *      indicates whether a WFD sink supports the prefered display mod operation or not.
+       */
+      if(wfd_msg->preferred_display_mode) {
+      }
+
+      /* Note : wfd-av-format-change-timing :
+       *   The wfd-av-format-change-timing parameter is used to signal the actual AV format change timing of the streaming data to the WFD sink.
+       *   It shall be included in an RTSP M4 request message for WFD capability re-nogotiation after a WFD session has been established.
+       */
+      if (wfd_msg->av_format_change_timing) {
+        guint64 pts=0LL, dts=0LL;
+        gboolean need_to_flush = FALSE;
+
+        wfd_res = gst_wfd_message_get_av_format_change_timing (wfd_msg, &pts, &dts);
+        if(wfd_res != GST_WFD_OK) {
+          goto message_config_error;
+        }
+
+        if (priv->state == GST_RTSP_STATE_PLAYING) {
+          GST_DEBUG_OBJECT(src, "change format with PTS[%lld] and DTS[%lld]", pts, dts);
+
+          g_signal_emit (src, gst_wfd_base_src_signals[SIGNAL_AV_FORMAT_CHANGE], 0, (gpointer)&need_to_flush);
+
+          if (need_to_flush) {
+            gst_wfd_base_src_flush(src,TRUE);
+            gst_wfd_base_src_flush(src, FALSE);
+          }
+        }
+      }
+
+      /* Note : RTSP M10 :
+       */
+      /* Note : wfd-route :
+       *   The wfd-route parameter provides a mechanism to specify the destination to which the audio stream is to be routed.
+       */
+      if(wfd_msg->route) {
+        /* TO DO*/
+      }
+
+      /* Note : RTSP M12 :
+       */
+      /* Note : wfd-standby :
+       *   The wfd-standby parameter is used to indicate that the sender is entering WFD standby mode.
+       */
+      if(wfd_msg->standby) {
+        gboolean standby_enable = FALSE;
+
+        wfd_res = gst_wfd_message_get_standby (wfd_msg, &standby_enable);
+        if(wfd_res != GST_WFD_OK) {
+          goto message_config_error;
+        }
+
+        GST_DEBUG_OBJECT (src, "wfd source is entering standby mode");
+      }
+
+      if (klass->handle_set_parameter) {
+        GST_DEBUG_OBJECT(src, "try to handle more SET_PARAMETER parameter");
+        res = klass->handle_set_parameter(src, request, &response);
+        if (res < 0)
+          goto send_error;
+      }
+      break;
+    }
+
+    default:
+    {
+      res = gst_rtsp_message_init_response (&response, GST_RTSP_STS_OK, gst_rtsp_status_as_text (GST_RTSP_STS_OK), request);
+      if (res < 0)
+        goto send_error;
+
+      break;
+    }
+  }
+
+  res = gst_wfd_base_src_connection_send (src, &response, priv->ptcp_timeout);
+  if (res < 0)
+    goto send_error;
+
+done:
+  gst_rtsp_message_unset (request);
+  gst_rtsp_message_unset (&response);
+  gst_wfd_message_free (wfd_msg);
+
+  return GST_RTSP_OK;
+
+  /* ERRORS */
+setup_failed:
+  {
+    GST_ERROR_OBJECT(src, "Could not setup(error)");
+    gst_rtsp_message_unset (request);
+    gst_rtsp_message_unset (&response);
+    gst_wfd_message_free (wfd_msg);
+    return GST_RTSP_ERROR;
+  }
+message_config_error:
+  {
+    GST_ERROR_OBJECT(src, "Message config error (%d)", wfd_res);
+    gst_rtsp_message_unset (request);
+    gst_rtsp_message_unset (&response);
+    gst_wfd_message_free (wfd_msg);
+    return GST_RTSP_ERROR;
+  }
+send_error:
+  {
+    GST_ERROR_OBJECT(src, "Could not send message");
+    gst_rtsp_message_unset (request);
+    gst_rtsp_message_unset (&response);
+    gst_wfd_message_free (wfd_msg);
+    return res;
+  }
+}
+
+static void
+gst_wfd_base_src_loop_start_cmd (GstWFDBaseSrc * src, gint cmd)
+{
+  GST_DEBUG_OBJECT (src, "start cmd %s", _cmd_to_string(cmd));
+
+  switch (cmd) {
+    case WFD_CMD_OPEN:
+      GST_ELEMENT_PROGRESS (src, START, "open", ("Opening Stream"));
+      break;
+    case WFD_CMD_PLAY:
+      GST_ELEMENT_PROGRESS (src, START, "play", ("Sending PLAY request"));
+      break;
+    case WFD_CMD_PAUSE:
+      GST_ELEMENT_PROGRESS (src, START, "pause", ("Sending PAUSE request"));
+      break;
+    case WFD_CMD_CLOSE:
+      GST_ELEMENT_PROGRESS (src, START, "close", ("Closing Stream"));
+      break;
+    default:
+      break;
+  }
+}
+
+static void
+gst_wfd_base_src_loop_complete_cmd (GstWFDBaseSrc * src, gint cmd)
+{
+  GST_DEBUG_OBJECT (src, "complete cmd %s", _cmd_to_string(cmd));
+
+  switch (cmd) {
+    case WFD_CMD_OPEN:
+      GST_ELEMENT_PROGRESS (src, COMPLETE, "open", ("Opened Stream"));
+      break;
+    case WFD_CMD_PLAY:
+      GST_ELEMENT_PROGRESS (src, COMPLETE, "play", ("Sent PLAY request"));
+      break;
+    case WFD_CMD_PAUSE:
+      GST_ELEMENT_PROGRESS (src, COMPLETE, "pause", ("Sent PAUSE request"));
+      break;
+    case WFD_CMD_CLOSE:
+      GST_ELEMENT_PROGRESS (src, COMPLETE, "close", ("Closed Stream"));
+      break;
+    default:
+      break;
+  }
+}
+
+static void
+gst_wfd_base_src_loop_cancel_cmd (GstWFDBaseSrc * src, gint cmd)
+{
+  GST_DEBUG_OBJECT (src, "cancel cmd %s", _cmd_to_string(cmd));
+
+  switch (cmd) {
+    case WFD_CMD_OPEN:
+      GST_ELEMENT_PROGRESS (src, CANCELED, "open", ("Open canceled"));
+      break;
+    case WFD_CMD_PLAY:
+      GST_ELEMENT_PROGRESS (src, CANCELED, "play", ("PLAY canceled"));
+      break;
+    case WFD_CMD_PAUSE:
+      GST_ELEMENT_PROGRESS (src, CANCELED, "pause", ("PAUSE canceled"));
+      break;
+    case WFD_CMD_CLOSE:
+      GST_ELEMENT_PROGRESS (src, CANCELED, "close", ("Close canceled"));
+      break;
+    default:
+      break;
+  }
+}
+
+static void
+gst_wfd_base_src_loop_error_cmd (GstWFDBaseSrc * src, gint cmd)
+{
+  GST_DEBUG_OBJECT (src, "error cmd %s", _cmd_to_string(cmd));
+
+  switch (cmd) {
+    case WFD_CMD_OPEN:
+      GST_ELEMENT_PROGRESS (src, ERROR, "open", ("Open failed"));
+      break;
+    case WFD_CMD_PLAY:
+      GST_ELEMENT_PROGRESS (src, ERROR, "play", ("PLAY failed"));
+      break;
+    case WFD_CMD_PAUSE:
+      GST_ELEMENT_PROGRESS (src, ERROR, "pause", ("PAUSE failed"));
+      break;
+    case WFD_CMD_CLOSE:
+      GST_ELEMENT_PROGRESS (src, ERROR, "close", ("Close failed"));
+      break;
+    default:
+      break;
+  }
+}
+
+static void
+gst_wfd_base_src_loop_end_cmd (GstWFDBaseSrc * src, gint cmd, GstRTSPResult ret)
+{
+  GST_DEBUG_OBJECT (src, "end cmd %s", _cmd_to_string(cmd));
+
+  if (ret == GST_RTSP_OK)
+    gst_wfd_base_src_loop_complete_cmd (src, cmd);
+  else if (ret == GST_RTSP_EINTR)
+    gst_wfd_base_src_loop_cancel_cmd (src, cmd);
+  else
+    gst_wfd_base_src_loop_error_cmd (src, cmd);
+}
+
+static gboolean
+gst_wfd_base_src_loop_send_cmd (GstWFDBaseSrc * src, gint cmd, gint mask)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  gboolean flushed = FALSE;
+  gint old;
+
+  /* start new request */
+  gst_wfd_base_src_loop_start_cmd (src, cmd);
+
+  GST_DEBUG_OBJECT (src, "sending cmd %s", _cmd_to_string(cmd));
+
+  GST_OBJECT_LOCK (src);
+  old = priv->pending_cmd;
+  if (old != WFD_CMD_WAIT) {
+    priv->pending_cmd = WFD_CMD_WAIT;
+    GST_OBJECT_UNLOCK (src);
+    /* cancel previous request */
+    GST_DEBUG_OBJECT (src, "cancel previous request %s", _cmd_to_string (old));
+    gst_wfd_base_src_loop_cancel_cmd (src, old);
+    GST_OBJECT_LOCK (src);
+  }
+  priv->pending_cmd = cmd;
+  /* interrupt if allowed */
+  if (priv->busy_cmd & mask) {
+    GST_DEBUG_OBJECT (src, "connection flush busy %s",
+        _cmd_to_string (priv->busy_cmd));
+    gst_wfd_base_src_connection_flush (src, TRUE);
+    flushed = TRUE;
+  } else {
+    GST_DEBUG_OBJECT (src, "not interrupting busy cmd %s",
+        _cmd_to_string (priv->busy_cmd));
+  }
+
+  if (priv->task)
+    gst_task_start (priv->task);
+  GST_OBJECT_UNLOCK (src);
+
+  return flushed;
+}
+
+static GstRTSPResult
+gst_wfd_base_src_loop (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPResult res = GST_RTSP_OK;
+  GstRTSPMessage message = { 0 };
+
+  if (!priv->conninfo.connection || !priv->conninfo.connected)
+    goto no_connection;
+
+  while (TRUE) {
+    GTimeVal tv_timeout;
+
+    /* get the next timeout interval */
+    gst_rtsp_connection_next_timeout (priv->conninfo.connection, &tv_timeout);
+
+    GST_DEBUG_OBJECT (src, "doing receive with timeout %d seconds",
+        (gint) tv_timeout.tv_sec);
+
+    gst_rtsp_message_unset (&message);
+
+    /* we should continue reading the TCP socket because the server might
+     * send us requests. */
+    res = gst_wfd_base_src_connection_receive (src, &message, &tv_timeout);
+
+    switch (res) {
+      case GST_RTSP_OK:
+        GST_DEBUG_OBJECT (src, "we received a server message");
+        break;
+      case GST_RTSP_EINTR:
+        /* we got interrupted, see what we have to do */
+        goto interrupt;
+      case GST_RTSP_ETIMEOUT:
+        /* timeout */
+        break;
+      case GST_RTSP_EEOF:
+        /* server closed the connection.*/
+        GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
+            ("The server closed the connection."));
+        goto connect_error;
+      default:
+        goto receive_error;
+    }
+
+    switch (message.type) {
+      case GST_RTSP_MESSAGE_REQUEST:
+        /* server sends us a request message, handle it */
+        res = gst_wfd_base_src_handle_request(src, &message);
+        if (res == GST_RTSP_EEOF)
+          goto server_eof;
+        else if (res < 0)
+          goto handle_request_failed;
+        break;
+      case GST_RTSP_MESSAGE_RESPONSE:
+        /* we ignore response and data messages */
+        GST_DEBUG_OBJECT (src, "ignoring response message");
+        break;
+      case GST_RTSP_MESSAGE_DATA:
+        /* we ignore response and data messages */
+        GST_DEBUG_OBJECT (src, "ignoring data message");
+        break;
+      default:
+        GST_WARNING_OBJECT (src, "ignoring unknown message type %d",
+            message.type);
+        break;
+    }
+  }
+  g_assert_not_reached ();
+
+  return res;
+
+no_connection:
+  {
+    res = GST_RTSP_ERROR;
+    GST_ERROR_OBJECT (src, "we are not connected");
+    goto pause;
+  }
+interrupt:
+  {
+    /* we get here when the connection got interrupted */
+    gst_rtsp_message_unset (&message);
+    GST_DEBUG_OBJECT (src, "got interrupted");
+    goto pause;
+  }
+connect_error:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    priv->conninfo.connected = FALSE;
+    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
+        ("Could not connect to server. (%s)", str));
+    g_free (str);
+
+    goto pause;
+  }
+receive_error:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
+        ("Could not receive message. (%s)", str));
+    g_free (str);
+
+    goto pause;
+  }
+handle_request_failed:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    gst_rtsp_message_unset (&message);
+    if (res != GST_RTSP_EINTR)
+      GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+          ("Could not handle server message. (%s)", str));
+    g_free (str);
+
+    goto pause;
+  }
+server_eof:
+  {
+    GST_DEBUG_OBJECT (src, "we got an eof from the server");
+    GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
+        ("The server closed the connection."));
+    priv->conninfo.connected = FALSE;
+    gst_rtsp_message_unset (&message);
+
+    goto pause;
+  }
+pause:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+    GstWFDBaseSrcClass *klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+    if (res == GST_RTSP_EEOF) {
+      /* perform EOS logic */
+      if (klass->push_event)
+        klass->push_event(src, gst_event_new_eos ());
+    } else if (res == GST_RTSP_EINTR) {
+      GST_DEBUG_OBJECT (src, "interupted");
+    } else if (res < GST_RTSP_OK) {
+      /* for fatal errors we post an error message, post the error before the
+       * EOS so the app knows about the error first. */
+      GST_ELEMENT_ERROR (src, STREAM, FAILED,
+          ("Internal data flow error."),
+          ("streaming task paused, reason %s (%d)", str, res));
+      if (klass->push_event)
+        klass->push_event(src, gst_event_new_eos ());
+    }
+
+    if (res != GST_RTSP_EINTR) {
+      GST_DEBUG_OBJECT (src, "pausing task, reason %s", str);
+      gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_WAIT, WFD_CMD_LOOP);
+    }
+
+    g_free (str);
+
+    return res;
+  }
+}
+
+static GstRTSPResult
+gst_wfd_base_src_try_send (GstWFDBaseSrc * src, GstRTSPMessage * request,
+    GstRTSPMessage * response, GstRTSPStatusCode * code)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPResult res = GST_RTSP_OK;
+  GstRTSPStatusCode thecode = GST_RTSP_STS_OK;
+
+  res = gst_wfd_base_src_connection_send (src, request, priv->ptcp_timeout);
+  if (res < 0)
+    goto send_error;
+
+  gst_rtsp_connection_reset_timeout (priv->conninfo.connection);
+
+next:
+  res = gst_wfd_base_src_connection_receive (src, response, priv->ptcp_timeout);
+  if (res < 0)
+    goto receive_error;
+
+  switch (response->type) {
+    case GST_RTSP_MESSAGE_REQUEST:
+      res = gst_wfd_base_src_handle_request(src, response);
+      if (res == GST_RTSP_EEOF)
+        goto server_eof;
+      else if (res < 0)
+        goto handle_request_failed;
+      goto next;
+    case GST_RTSP_MESSAGE_RESPONSE:
+      /* ok, a response is good */
+      GST_DEBUG_OBJECT (src, "received response message");
+      break;
+    default:
+    case GST_RTSP_MESSAGE_DATA:
+      /* get next response */
+      GST_DEBUG_OBJECT (src, "ignoring data response message");
+      goto next;
+  }
+
+  thecode = response->type_data.response.code;
+
+  GST_DEBUG_OBJECT (src, "got response message %d", thecode);
+
+  /* if the caller wanted the result code, we store it. */
+  if (code)
+    *code = thecode;
+
+  /* If the request didn't succeed, bail out before doing any more */
+  if (thecode != GST_RTSP_STS_OK)
+    return GST_RTSP_OK;
+
+  return GST_RTSP_OK;
+
+  /* ERRORS */
+send_error:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+        ("Could not send message. (%s)", str));
+    g_free (str);
+    return res;
+  }
+receive_error:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
+        ("Could not receive message. (%s)", str));
+    g_free (str);
+    return res;
+  }
+handle_request_failed:
+  {
+    /* ERROR was posted */
+    gst_rtsp_message_unset (response);
+    return res;
+  }
+server_eof:
+  {
+    GST_DEBUG_OBJECT (src, "we got an eof from the server");
+    GST_ELEMENT_WARNING (src, RESOURCE, READ, (NULL),
+        ("The server closed the connection."));
+    gst_rtsp_message_unset (response);
+    return res;
+  }
+}
+
+/**
+ * gst_wfd_base_src_send:
+ * @src: the rtsp source
+ * @conn: the connection to send on
+ * @request: must point to a valid request
+ * @response: must point to an empty #GstRTSPMessage
+ * @code: an optional code result
+ *
+ * send @request and retrieve the response in @response. optionally @code can be
+ * non-NULL in which case it will contain the status code of the response.
+ *
+ * If This function returns #GST_RTSP_OK, @response will contain a valid response
+ * message that should be cleaned with gst_rtsp_message_unset() after usage.
+ *
+ * If @code is NULL, this function will return #GST_RTSP_ERROR (with an invalid
+ * @response message) if the response code was not 200 (OK).
+ *
+ * Returns: #GST_RTSP_OK if the processing was successful.
+ */
+
+static GstRTSPResult
+gst_wfd_base_src_send (GstWFDBaseSrc * src, GstRTSPMessage * request,
+    GstRTSPMessage * response, GstRTSPStatusCode * code)
+{
+  GstRTSPStatusCode int_code = GST_RTSP_STS_OK;
+  GstRTSPResult res = GST_RTSP_ERROR;
+  GstRTSPMethod method = GST_RTSP_INVALID;
+
+  /* save method so we can disable it when the server complains */
+  method = request->type_data.request.method;
+
+  if ((res =
+          gst_wfd_base_src_try_send (src, request, response, &int_code)) < 0)
+    goto error;
+
+  /* If the user requested the code, let them handle errors, otherwise
+   * post an error below */
+  if (code != NULL)
+    *code = int_code;
+  else if (int_code != GST_RTSP_STS_OK)
+    goto error_response;
+
+  return res;
+
+  /* ERRORS */
+error:
+  {
+    GST_DEBUG_OBJECT (src, "got error %d", res);
+    return res;
+  }
+error_response:
+  {
+    res = GST_RTSP_ERROR;
+
+    switch (response->type_data.response.code) {
+      case GST_RTSP_STS_NOT_FOUND:
+        GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), ("%s",
+                response->type_data.response.reason));
+        break;
+      case GST_RTSP_STS_NOT_ACCEPTABLE:
+      case GST_RTSP_STS_NOT_IMPLEMENTED:
+      case GST_RTSP_STS_METHOD_NOT_ALLOWED:
+        GST_ERROR_OBJECT (src, "got NOT IMPLEMENTED, disable method %s",
+            gst_rtsp_method_as_text (method));
+        src->priv->methods &= ~method;
+        res = GST_RTSP_OK;
+        break;
+      default:
+        GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
+            ("Got error response: %d (%s).", response->type_data.response.code,
+                response->type_data.response.reason));
+        break;
+    }
+    /* if we return ERROR we should unset the response ourselves */
+    if (res == GST_RTSP_ERROR)
+      gst_rtsp_message_unset (response);
+
+    return res;
+  }
+}
+
+
+/* parse the response and collect all the supported methods. We need this
+ * information so that we don't try to send an unsupported request to the
+ * server.
+ */
+static gboolean
+gst_wfd_base_src_parse_methods (GstWFDBaseSrc * src, GstRTSPMessage * response)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPHeaderField field;
+  gchar *respoptions;
+  gchar **options;
+  gint indx = 0;
+  gint i;
+
+  /* reset supported methods */
+  priv->methods = 0;
+
+  /* Try Allow Header first */
+  field = GST_RTSP_HDR_ALLOW;
+  while (TRUE) {
+    respoptions = NULL;
+    gst_rtsp_message_get_header (response, field, &respoptions, indx);
+    if (indx == 0 && !respoptions) {
+      /* if no Allow header was found then try the Public header... */
+      field = GST_RTSP_HDR_PUBLIC;
+      gst_rtsp_message_get_header (response, field, &respoptions, indx);
+    }
+    if (!respoptions)
+      break;
+
+    /* If we get here, the server gave a list of supported methods, parse
+     * them here. The string is like:
+     *
+     * OPTIONS, DESCRIBE, ANNOUNCE, PLAY, SETUP, ...
+     */
+    options = g_strsplit (respoptions, ",", 0);
+
+    for (i = 0; options[i]; i++) {
+      gchar *stripped;
+      gint method;
+
+      stripped = g_strstrip (options[i]);
+      method = gst_rtsp_find_method (stripped);
+
+      /* keep bitfield of supported methods */
+      if (method != GST_RTSP_INVALID)
+        priv->methods |= method;
+    }
+    g_strfreev (options);
+
+    indx++;
+  }
+
+  if (priv->methods == 0) {
+    /* neither Allow nor Public are required, assume the server supports
+     * at least DESCRIBE, SETUP, we always assume it supports PLAY as
+     * well. */
+    GST_DEBUG_OBJECT (src, "could not get OPTIONS");
+    priv->methods = GST_RTSP_SETUP;
+  }
+  /* always assume PLAY, FIXME, extensions should be able to override
+   * this */
+  priv->methods |= GST_RTSP_PLAY;
+
+  if (!(priv->methods & GST_RTSP_SETUP))
+    goto no_setup;
+
+  return TRUE;
+
+no_setup:
+  {
+    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
+        ("Server does not support SETUP."));
+    return FALSE;
+  }
+}
+
+static GstRTSPResult
+gst_wfd_base_src_create_transports_string (GstWFDBaseSrc * src,
+    gchar ** transports)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GString *result;
+  GstRTSPProfile profile = priv->transport.profile;
+  GstRTSPLowerTrans protocols = priv->transport.lower_transport;
+
+  *transports = NULL;
+
+
+  /* the default RTSP transports */
+  result = g_string_new ("RTP");
+
+  switch (profile) {
+    case GST_RTSP_PROFILE_AVP:
+      g_string_append (result, "/AVP");
+      break;
+    case GST_RTSP_PROFILE_SAVP:
+      g_string_append (result, "/SAVP");
+      break;
+    case GST_RTSP_PROFILE_AVPF:
+      g_string_append (result, "/AVPF");
+      break;
+    case GST_RTSP_PROFILE_SAVPF:
+      g_string_append (result, "/SAVPF");
+      break;
+    default:
+      break;
+  }
+
+  if (protocols & GST_RTSP_LOWER_TRANS_UDP) {
+    GST_DEBUG_OBJECT (src, "adding UDP unicast");
+    g_string_append (result, "/UDP");
+    g_string_append (result, ";unicast;client_port=");
+    g_string_append_printf (result, "%d", priv->transport.client_port.min);
+    g_string_append (result, "-");
+    g_string_append_printf (result, "%d", priv->transport.client_port.max);
+  } else if (protocols & GST_RTSP_LOWER_TRANS_TCP) {
+    GST_DEBUG_OBJECT (src, "adding TCP");
+    g_string_append (result, "/TCP;unicast;client_port=");
+    g_string_append_printf (result, "%d", priv->transport.client_port.min);
+    g_string_append (result, "-");
+    g_string_append_printf (result, "%d", priv->transport.client_port.max);
+  }
+  *transports = g_string_free (result, FALSE);
+
+  GST_DEBUG_OBJECT (src, "prepared transports %s", GST_STR_NULL (*transports));
+
+  return GST_RTSP_OK;
+}
+
+gboolean
+gst_wfd_base_src_activate (GstWFDBaseSrc *src)
+{
+  GST_DEBUG_OBJECT (src, "activating streams");
+
+  if (src->srcpad) {
+    GST_DEBUG_OBJECT (src, "setting caps");
+    gst_pad_set_caps (src->srcpad, src->caps);
+
+    GST_DEBUG_OBJECT (src, "activating srcpad");
+    gst_pad_set_active (src->srcpad, TRUE);
+  }
+
+  return TRUE;
+}
+
+void
+gst_wfd_base_src_get_transport_info (GstWFDBaseSrc *src,
+    GstRTSPTransport * transport, const gchar ** destination, gint * min, gint * max)
+{
+  g_return_if_fail (transport);
+  g_return_if_fail (transport->lower_transport == GST_RTSP_LOWER_TRANS_UDP);
+
+  if (destination) {
+    /* first take the source, then the endpoint to figure out where to send
+     * the RTCP. */
+    if (!(*destination = transport->source)) {
+      if (src->priv->conninfo.connection)
+        *destination =
+            gst_rtsp_connection_get_ip (src->priv->conninfo.connection);
+    }
+  }
+  if (min && max) {
+    /* for unicast we only expect the ports here */
+    *min = transport->server_port.min;
+    *max = transport->server_port.max;
+  }
+}
+
+/* Perform the SETUP request for all the streams.
+ *
+ * We ask the server for a specific transport, which initially includes all the
+ * ones we can support (UDP/TCP/MULTICAST). For the UDP transport we allocate
+ * two local UDP ports that we send to the server.
+ *
+ * Once the server replied with a transport, we configure the other streams
+ * with the same transport.
+ *
+ * This function will also configure the manager for the selected transport,
+ * which basically means creating the pipeline.
+ */
+static gboolean
+gst_wfd_base_src_setup (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDBaseSrcClass * klass;
+  GstRTSPResult res = GST_RTSP_OK;
+  GstRTSPMessage request = { 0 };
+  GstRTSPMessage response = { 0 };
+  GstRTSPLowerTrans protocols = GST_RTSP_LOWER_TRANS_UNKNOWN;
+  GstRTSPStatusCode code = GST_RTSP_STS_OK;
+  gchar *resptrans = NULL;
+  GstRTSPTransport transport = { 0 };
+  gchar *transports = NULL;
+  GstRTSPUrl *url;
+  gchar *hval;
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (G_UNLIKELY (!klass->prepare_transport))
+    goto no_function;
+  if (G_UNLIKELY (!klass->configure_transport))
+    goto no_function;
+
+  if (!priv->conninfo.connection || !priv->conninfo.connected)
+    goto no_connection;
+
+  url = gst_rtsp_connection_get_url (priv->conninfo.connection);
+  protocols = url->transports;
+  if (protocols == 0)
+    goto no_protocols;
+
+  GST_DEBUG_OBJECT (src, "doing setup of with %s", GST_STR_NULL(priv->conninfo.location));
+
+  GST_DEBUG_OBJECT (src, "protocols = 0x%x", protocols);
+  /* create a string with first transport in line */
+  res = gst_wfd_base_src_create_transports_string (src, &transports);
+  if (res < 0 || transports == NULL)
+    goto setup_transport_failed;
+
+  if (strlen (transports) == 0) {
+    g_free (transports);
+    GST_DEBUG_OBJECT (src, "no transports found");
+    goto setup_transport_failed;
+  }
+
+  /* now prepare with the selected transport */
+  res = klass->prepare_transport(src, priv->transport.client_port.min, priv->transport.client_port.max);
+  if (res < 0)
+    goto setup_failed;
+
+  /* create SETUP request */
+  res =
+      gst_rtsp_message_init_request (&request, GST_RTSP_SETUP, priv->conninfo.location);
+  if (res < 0) {
+    g_free (transports);
+    goto create_request_failed;
+  }
+
+  gst_rtsp_message_add_header (&request, GST_RTSP_HDR_TRANSPORT, transports);
+  g_free (transports);
+
+  /* if the user wants a non default RTP packet size we add the blocksize
+   * parameter */
+  if (priv->rtp_blocksize > 0) {
+    hval = g_strdup_printf ("%d", priv->rtp_blocksize);
+    gst_rtsp_message_add_header (&request, GST_RTSP_HDR_BLOCKSIZE, hval);
+    g_free (hval);
+  }
+
+  /* handle the code ourselves */
+  if ((res = gst_wfd_base_src_send (src, &request, &response, &code) < 0))
+    goto send_error;
+
+  switch (code) {
+    case GST_RTSP_STS_OK:
+      break;
+    case GST_RTSP_STS_UNSUPPORTED_TRANSPORT:
+      gst_rtsp_message_unset (&request);
+      gst_rtsp_message_unset (&response);
+      goto no_protocols;
+      break;
+    default:
+      goto response_error;
+  }
+
+  /* parse response transport */
+  gst_rtsp_message_get_header (&response, GST_RTSP_HDR_TRANSPORT,
+      &resptrans, 0);
+  if (!resptrans)
+    goto no_transport;
+
+  /* parse transport, go to next manager on parse error */
+  if (gst_rtsp_transport_parse (resptrans, &transport) != GST_RTSP_OK) {
+    GST_ERROR_OBJECT (src, "failed to parse transport %s", resptrans);
+    goto setup_failed;
+  }
+
+  /* now configure the manager with the selected transport */
+  res = klass->configure_transport(src, &transport);
+  if (res < 0)
+    goto setup_failed;
+
+  /* clean up our transport struct */
+  gst_rtsp_transport_init (&transport);
+  /* clean up used RTSP messages */
+  gst_rtsp_message_unset (&request);
+  gst_rtsp_message_unset (&response);
+
+  priv->state = GST_RTSP_STATE_READY;
+
+  return TRUE;
+
+  /* ERRORS */
+no_function:
+  {
+    GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
+        ("No prepare or configure function."));
+    return FALSE;
+  }
+no_connection:
+  {
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
+        ("Could not connct to server, no connection."));
+    return FALSE;
+  }
+no_protocols:
+  {
+    /* no transport possible, post an error and stop */
+    GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
+        ("Could not connect to server, no protocols left"));
+    return FALSE;
+  }
+create_request_failed:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
+        ("Could not create request. (%s)", str));
+    g_free (str);
+    goto cleanup_error;
+  }
+setup_transport_failed:
+  {
+    GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
+        ("Could not setup transport."));
+    goto cleanup_error;
+  }
+response_error:
+  {
+    const gchar *str = gst_rtsp_status_as_text (code);
+
+    GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+        ("Error (%d): %s", code, GST_STR_NULL (str)));
+    goto cleanup_error;
+  }
+send_error:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+        ("Could not send message. (%s)", str));
+    g_free (str);
+    goto cleanup_error;
+  }
+no_transport:
+  {
+    GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
+        ("Server did not select transport."));
+    goto cleanup_error;
+  }
+setup_failed:
+  {
+    GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
+        ("Could not setup."));
+    goto cleanup_error;
+  }
+cleanup_error:
+  {
+    gst_rtsp_message_unset (&request);
+    gst_rtsp_message_unset (&response);
+    return FALSE;
+  }
+}
+
+/* Note : RTSP M1~M6 :
+ *   WFD session capability negotiation
+ */
+static GstRTSPResult
+gst_wfd_base_src_open (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPResult res = GST_RTSP_OK;
+  GstRTSPMessage request = { 0 };
+  GstRTSPMessage response = { 0 };
+  GstRTSPMessage message = { 0 };
+  GstRTSPMethod method = { 0 };
+  gchar *str = NULL;
+
+  /* can't continue without a valid url */
+  if (G_UNLIKELY (priv->conninfo.url == NULL))
+    goto no_url;
+
+  if ((res = gst_wfd_base_src_conninfo_connect (src, &priv->conninfo)) < 0)
+    goto connect_failed;
+
+  res = gst_wfd_base_src_connection_receive (src, &message, priv->ptcp_timeout);
+  if(res != GST_RTSP_OK)
+    goto connect_failed;
+
+  if(message.type == GST_RTSP_MESSAGE_REQUEST) {
+    method = message.type_data.request.method;
+    if(method == GST_RTSP_OPTIONS) {
+      res = gst_wfd_base_src_handle_request(src, &message);
+      if (res < GST_RTSP_OK)
+        goto connect_failed;
+    } else
+      goto methods_error;
+  } else {
+    GST_ERROR_OBJECT (src, "failed to receive options...");
+    goto methods_error;
+  }
+
+  /* create OPTIONS */
+  GST_DEBUG_OBJECT (src, "create options...");
+  res = gst_rtsp_message_init_request (&request, GST_RTSP_OPTIONS,"*");
+  if (res < 0)
+    goto create_request_failed;
+
+  gst_rtsp_message_add_header (&request, GST_RTSP_HDR_REQUIRE, "org.wfa.wfd1.0");
+  gst_rtsp_message_add_header (&request, GST_RTSP_HDR_USER_AGENT, (const gchar*)src->priv->user_agent);
+
+  /* send OPTIONS */
+  GST_DEBUG_OBJECT (src, "send options...");
+  if ((res = gst_wfd_base_src_send (src, &request, &response,
+          NULL)) < 0)
+    goto send_error;
+
+  /* parse OPTIONS */
+  if (!gst_wfd_base_src_parse_methods (src, &response))
+    goto methods_error;
+
+ /* Receive request message from source */
+receive_request_message:
+  res = gst_wfd_base_src_connection_receive (src, &message,
+    priv->ptcp_timeout);
+  if(res != GST_RTSP_OK)
+    goto connect_failed;
+
+  if(message.type == GST_RTSP_MESSAGE_REQUEST) {
+    method = message.type_data.request.method;
+    if(method == GST_RTSP_GET_PARAMETER ||method == GST_RTSP_SET_PARAMETER) {
+      res = gst_wfd_base_src_handle_request(src, &message);
+      if (res < GST_RTSP_OK)
+        goto handle_request_failed;
+    } else
+      goto methods_error;
+
+    if (priv->state != GST_RTSP_STATE_READY)
+      goto receive_request_message;
+  }
+
+  /* clean up any messages */
+  gst_rtsp_message_unset (&request);
+  gst_rtsp_message_unset (&response);
+
+  return res;
+
+  /* ERRORS */
+no_url:
+  {
+    GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
+        ("No valid RTSP URL was provided"));
+    goto cleanup_error;
+  }
+connect_failed:
+  {
+    str = NULL;
+    str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
+        ("Failed to connect. (%s)", str));
+    g_free (str);
+    goto cleanup_error;
+  }
+create_request_failed:
+  {
+    str = NULL;
+    str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
+        ("Could not create request. (%s)", str));
+    g_free (str);
+    goto cleanup_error;
+  }
+send_error:
+  {
+    GST_ERROR_OBJECT (src, "send errors");
+    /* Don't post a message - the rtsp_send method will have
+     * taken care of it because we passed NULL for the response code */
+    goto cleanup_error;
+  }
+methods_error:
+  {
+    GST_ERROR_OBJECT (src, "method errors");
+    /* error was posted */
+    goto cleanup_error;
+  }
+handle_request_failed:
+  {
+    GST_ERROR_OBJECT (src, "failed to handle request");
+    /* error was posted */
+    goto cleanup_error;
+  }
+cleanup_error:
+  {
+    GST_ERROR_OBJECT (src, "failed to open");
+
+    if (priv->conninfo.connection) {
+      GST_ERROR_OBJECT (src, "free connection");
+      gst_wfd_base_src_conninfo_close (src, &priv->conninfo, TRUE);
+    }
+    gst_rtsp_message_unset (&request);
+    gst_rtsp_message_unset (&response);
+    return res;
+  }
+}
+
+static void
+gst_wfd_base_src_send_close_cmd (GstWFDBaseSrc * src)
+{
+  gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_CLOSE, WFD_CMD_ALL);
+}
+
+/* Note : RTSP M8 :
+ *   Send TEARDOWN request to WFD source.
+ */
+static GstRTSPResult
+gst_wfd_base_src_close (GstWFDBaseSrc * src, gboolean only_close)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDBaseSrcClass *klass;
+  GstRTSPMessage request = { 0 };
+  GstRTSPMessage response = { 0 };
+  GstRTSPResult res = GST_RTSP_OK;
+
+  GST_DEBUG_OBJECT (src, "TEARDOWN...");
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (klass->set_state)
+    klass->set_state (src, GST_STATE_READY);
+
+  if (priv->state < GST_RTSP_STATE_READY) {
+    GST_DEBUG_OBJECT (src, "not ready, doing cleanup");
+    goto close;
+  }
+
+  if (only_close)
+    goto close;
+
+  if (!priv->conninfo.connection || !priv->conninfo.connected)
+    goto close;
+
+  if (!(priv->methods & (GST_RTSP_PLAY | GST_RTSP_TEARDOWN)))
+    goto not_supported;
+
+  /* do TEARDOWN */
+  res =
+      gst_rtsp_message_init_request (&request, GST_RTSP_TEARDOWN, priv->conninfo.url_str);
+  if (res < 0)
+    goto create_request_failed;
+
+  if ((res =
+          gst_wfd_base_src_send (src, &request, &response,
+              NULL)) < 0)
+    goto send_error;
+
+  /* FIXME, parse result? */
+  gst_rtsp_message_unset (&request);
+  gst_rtsp_message_unset (&response);
+
+close:
+  /* close connections */
+  GST_DEBUG_OBJECT (src, "closing connection...");
+  gst_wfd_base_src_conninfo_close (src, &priv->conninfo, TRUE);
+
+  priv->state = GST_RTSP_STATE_INVALID;
+
+  return res;
+
+  /* ERRORS */
+create_request_failed:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
+        ("Could not create request. (%s)", str));
+    g_free (str);
+    goto close;
+  }
+send_error:
+  {
+    gchar *str = gst_rtsp_strresult (res);
+
+    gst_rtsp_message_unset (&request);
+    if (res != GST_RTSP_EINTR) {
+      GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+          ("Could not send message. (%s)", str));
+    } else {
+      GST_ERROR_OBJECT (src, "TEARDOWN interrupted");
+    }
+    g_free (str);
+    goto close;
+  }
+not_supported:
+  {
+    GST_ERROR_OBJECT (src,
+        "TEARDOWN and PLAY not supported, can't do TEARDOWN");
+    goto close;
+  }
+}
+
+/* RTP-Info is of the format:
+ *
+ * url=<URL>;[seq=<seqbase>;rtptime=<timebase>] [, url=...]
+ *
+ * rtptime corresponds to the timestamp for the NPT time given in the header
+ * seqbase corresponds to the next sequence number we received. This number
+ * indicates the first seqnum after the seek and should be used to discard
+ * packets that are from before the seek.
+ */
+static gboolean
+gst_wfd_base_src_parse_rtpinfo (GstWFDBaseSrc * src, gchar * rtpinfo)
+{
+  gchar **infos;
+  gint i, j;
+
+  GST_DEBUG_OBJECT (src, "parsing RTP-Info %s", rtpinfo);
+
+  infos = g_strsplit (rtpinfo, ",", 0);
+  for (i = 0; infos[i]; i++) {
+    gchar **fields;
+    gint32 seqbase;
+    gint64 timebase;
+
+    GST_DEBUG_OBJECT (src, "parsing info %s", infos[i]);
+
+    /* init values, types of seqbase and timebase are bigger than needed so we
+     * can store -1 as uninitialized values */
+    seqbase = -1;
+    timebase = -1;
+
+    /* parse url, find manager for url.
+     * parse seq and rtptime. The seq number should be configured in the rtp
+     * depayloader or session manager to detect gaps. Same for the rtptime, it
+     * should be used to create an initial time newsegment. */
+    fields = g_strsplit (infos[i], ";", 0);
+    for (j = 0; fields[j]; j++) {
+      GST_DEBUG_OBJECT (src, "parsing field %s", fields[j]);
+      /* remove leading whitespace */
+      fields[j] = g_strchug (fields[j]);
+      if (g_str_has_prefix (fields[j], "url=")) {
+        /* get the url and the manager */
+      } else if (g_str_has_prefix (fields[j], "seq=")) {
+        seqbase = atoi (fields[j] + 4);
+      } else if (g_str_has_prefix (fields[j], "rtptime=")) {
+        timebase = g_ascii_strtoll (fields[j] + 8, NULL, 10);
+      }
+    }
+    g_strfreev (fields);
+    /* now we need to store the values for the caps */
+    GST_DEBUG_OBJECT (src,
+        "setting: seqbase %d, timebase %" G_GINT64_FORMAT,
+        seqbase, timebase);
+
+    /* we have a stream, configure detected params */
+    src->priv->seqbase = seqbase;
+    src->priv->timebase = timebase;
+  }
+  g_strfreev (infos);
+
+  return TRUE;
+}
+
+static void
+gst_wfd_base_src_send_play_cmd (GstWFDBaseSrc * src)
+{
+  gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_PLAY, WFD_CMD_LOOP);
+}
+
+/* Note : RTSP M7 :
+ *   Send PLAY request to WFD source. WFD source begins audio and/or video streaming.
+ */
+static GstRTSPResult
+gst_wfd_base_src_play (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDBaseSrcClass *klass;
+  GstRTSPMessage request = { 0 };
+  GstRTSPMessage response = { 0 };
+  GstRTSPResult res = GST_RTSP_OK;
+  gchar *hval;
+  gint hval_idx;
+
+  GST_DEBUG_OBJECT (src, "PLAY...");
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (!priv->conninfo.connection || !priv->conninfo.connected)
+    goto done;
+
+  if (!(priv->methods & GST_RTSP_PLAY))
+    goto not_supported;
+
+  if (priv->state == GST_RTSP_STATE_PLAYING)
+    goto was_playing;
+
+  /* do play */
+  res = gst_rtsp_message_init_request (&request, GST_RTSP_PLAY, priv->conninfo.url_str);
+  if (res < 0)
+    goto create_request_failed;
+
+  if ((res = gst_wfd_base_src_send (src, &request, &response, NULL)) < 0)
+    goto send_error;
+
+  gst_rtsp_message_unset (&request);
+
+  /* parse the RTP-Info header field (if ANY) to get the base seqnum and timestamp
+   * for the RTP packets. If this is not present, we assume all starts from 0...
+   * This is info for the RTP session manager that we pass to it in caps. */
+  hval_idx = 0;
+  while (gst_rtsp_message_get_header (&response, GST_RTSP_HDR_RTP_INFO,
+          &hval, hval_idx++) == GST_RTSP_OK)
+    gst_wfd_base_src_parse_rtpinfo (src, hval);
+
+  gst_rtsp_message_unset (&response);
+
+  /* configure the caps of the streams after we parsed all headers. */
+  gst_wfd_base_src_configure_caps (src);
+
+  /* set to PLAYING after we have configured the caps, otherwise we
+   * might end up calling request_key (with SRTP) while caps are still
+   * being configured. */
+  if (klass->set_state)
+    klass->set_state (src, GST_STATE_PLAYING);
+
+  priv->state = GST_RTSP_STATE_PLAYING;
+
+done:
+  return res;
+
+  /* ERRORS */
+not_supported:
+  {
+    GST_ERROR_OBJECT (src, "PLAY is not supported");
+    goto done;
+  }
+was_playing:
+  {
+    GST_DEBUG_OBJECT (src, "we were already PLAYING");
+    goto done;
+  }
+create_request_failed:
+  {
+    GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
+        ("Could not create request."));
+    return FALSE;
+  }
+send_error:
+  {
+    gst_rtsp_message_unset (&request);
+    GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+        ("Could not send message."));
+    return FALSE;
+  }
+}
+
+static void
+gst_wfd_base_src_send_pause_cmd (GstWFDBaseSrc * src)
+{
+  gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_PAUSE, WFD_CMD_LOOP);
+}
+
+/* Note : RTSP M9  :
+ *   Send PAUSE request to WFD source. WFD source pauses the audio video stream(s).
+ */
+static GstRTSPResult
+gst_wfd_base_src_pause (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPResult res = GST_RTSP_OK;
+  GstRTSPMessage request = { 0 };
+  GstRTSPMessage response = { 0 };
+  GstWFDBaseSrcClass * klass;
+
+  GST_DEBUG_OBJECT (src, "PAUSE...");
+
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (!priv->conninfo.connection || !priv->conninfo.connected)
+    goto no_connection;
+
+  if (!(priv->methods & GST_RTSP_PAUSE))
+    goto not_supported;
+
+  if (priv->state == GST_RTSP_STATE_READY)
+    goto was_paused;
+
+  if (gst_rtsp_message_init_request (&request, GST_RTSP_PAUSE, priv->conninfo.url_str) < 0)
+    goto create_request_failed;
+
+  if ((res = gst_wfd_base_src_send (src, &request, &response, NULL)) < 0)
+    goto send_error;
+
+  gst_rtsp_message_unset (&request);
+  gst_rtsp_message_unset (&response);
+
+  if (klass->set_state)
+    klass->set_state (src, GST_STATE_PAUSED);
+
+no_connection:
+  priv->state = GST_RTSP_STATE_READY;
+
+done:
+  return res;
+
+  /* ERRORS */
+not_supported:
+  {
+    GST_ERROR_OBJECT (src, "PAUSE is not supported");
+    goto done;
+  }
+was_paused:
+  {
+    GST_DEBUG_OBJECT (src, "we were already PAUSED");
+    goto done;
+  }
+create_request_failed:
+  {
+    GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL),
+        ("Could not create request."));
+    goto done;
+  }
+send_error:
+  {
+    gst_rtsp_message_unset (&request);
+    GST_ELEMENT_ERROR (src, RESOURCE, WRITE, (NULL),
+        ("Could not send message."));
+    goto done;
+  }
+}
+
+static void
+gst_wfd_base_src_handle_message (GstBin * bin, GstMessage * message)
+{
+  GstWFDBaseSrc *src = GST_WFD_BASE_SRC (bin);
+
+  GST_DEBUG_OBJECT (src, "got %s message from %s",
+      GST_MESSAGE_TYPE_NAME (message), GST_MESSAGE_SRC_NAME (message));
+
+  switch (GST_MESSAGE_TYPE (message)) {
+    case GST_MESSAGE_EOS:
+      gst_message_unref (message);
+      break;
+    case GST_MESSAGE_ELEMENT:
+    {
+      const GstStructure *s = gst_message_get_structure (message);
+      if (gst_structure_has_name (s, "GstUDPSrcTimeout"))
+        GST_DEBUG_OBJECT (bin, "timeout on UDP port");
+
+      GST_BIN_CLASS (parent_class)->handle_message (bin, message);
+      break;
+    }
+    case GST_MESSAGE_ERROR:
+    {
+      gchar* debug = NULL;
+      GError* error = NULL;
+
+      gst_message_parse_error (message, &error, &debug);
+      GST_ERROR_OBJECT (src, "error : %s", error->message);
+      GST_ERROR_OBJECT (src, "debug : %s", debug);
+      g_free (debug);
+      g_error_free (error);
+
+      /* fatal but not our message, forward */
+      GST_BIN_CLASS (parent_class)->handle_message (bin, message);
+      break;
+    }
+    default:
+    {
+      GST_BIN_CLASS (parent_class)->handle_message (bin, message);
+      break;
+    }
+  }
+}
+
+/* the thread where everything happens */
+static void
+gst_wfd_base_src_thread (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstRTSPResult res = GST_RTSP_OK;
+  gint cmd;
+
+  GST_OBJECT_LOCK (src);
+  cmd = priv->pending_cmd;
+  if (cmd == WFD_CMD_PLAY || cmd == WFD_CMD_PAUSE || cmd == WFD_CMD_REQUEST
+      || cmd == WFD_CMD_LOOP || cmd == WFD_CMD_OPEN)
+    priv->pending_cmd = WFD_CMD_LOOP;
+  else
+    priv->pending_cmd = WFD_CMD_WAIT;
+
+  GST_DEBUG_OBJECT (src, "got command %s", _cmd_to_string (cmd));
+
+  /* we got the message command, so ensure communication is possible again */
+  gst_wfd_base_src_connection_flush (src, FALSE);
+
+  priv->busy_cmd = cmd;
+  GST_OBJECT_UNLOCK (src);
+
+  switch (cmd) {
+    case WFD_CMD_OPEN:
+      res = gst_wfd_base_src_open (src);
+      break;
+    case WFD_CMD_PLAY:
+      res = gst_wfd_base_src_play (src);
+      break;
+    case WFD_CMD_PAUSE:
+      res = gst_wfd_base_src_pause (src);
+      break;
+    case WFD_CMD_CLOSE:
+      res = gst_wfd_base_src_close (src, FALSE);
+      break;
+    case WFD_CMD_LOOP:
+      res = gst_wfd_base_src_loop (src);
+      break;
+    case WFD_CMD_REQUEST:
+      res = gst_wfd_base_src_send_request (src);
+      break;
+    default:
+      break;
+  }
+
+  GST_OBJECT_LOCK (src);
+  /* and go back to sleep */
+  if (priv->pending_cmd == WFD_CMD_WAIT) {
+    if (priv->task)
+      gst_task_pause (priv->task);
+  }
+  /* reset waiting */
+  priv->busy_cmd = WFD_CMD_WAIT;
+  GST_OBJECT_UNLOCK (src);
+
+  if (cmd == WFD_CMD_PLAY || cmd == WFD_CMD_PAUSE
+      || cmd == WFD_CMD_CLOSE || cmd == WFD_CMD_OPEN)
+    gst_wfd_base_src_loop_end_cmd (src, cmd, res);
+}
+
+static gboolean
+gst_wfd_base_src_start (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+
+  GST_DEBUG_OBJECT (src, "starting");
+
+  GST_OBJECT_LOCK (src);
+
+  priv->state = GST_RTSP_STATE_INIT;
+
+  priv->pending_cmd = WFD_CMD_WAIT;
+
+  if (priv->task == NULL) {
+    priv->task = gst_task_new ((GstTaskFunction) gst_wfd_base_src_thread, src, NULL);
+    if (priv->task == NULL)
+      goto task_error;
+
+    gst_task_set_lock (priv->task, &(GST_WFD_BASE_TASK_GET_LOCK (src)));
+  }
+  GST_OBJECT_UNLOCK (src);
+
+  return TRUE;
+
+  /* ERRORS */
+task_error:
+  {
+    GST_OBJECT_UNLOCK (src);
+    GST_ERROR_OBJECT (src, "failed to create task");
+    return FALSE;
+  }
+}
+
+static gboolean
+gst_wfd_base_src_stop (GstWFDBaseSrc * src)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstTask *task;
+
+  GST_DEBUG_OBJECT (src, "stopping");
+
+  GST_OBJECT_LOCK (src);
+  priv->do_stop = TRUE;
+  GST_OBJECT_UNLOCK (src);
+
+  /* also cancels pending task */
+  gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_WAIT, WFD_CMD_ALL);
+
+  GST_OBJECT_LOCK (src);
+  if ((task = priv->task)) {
+    priv->task = NULL;
+    GST_OBJECT_UNLOCK (src);
+
+    gst_task_stop (task);
+
+    /* make sure it is not running */
+    GST_WFD_BASE_TASK_LOCK (src);
+    GST_WFD_BASE_TASK_UNLOCK (src);
+
+    /* now wait for the task to finish */
+    gst_task_join (task);
+
+    /* and free the task */
+    gst_object_unref (GST_OBJECT (task));
+    GST_OBJECT_LOCK (src);
+  }
+  GST_OBJECT_UNLOCK (src);
+
+  /* ensure synchronously all is closed */
+  gst_wfd_base_src_close (src, TRUE);
+
+  /* cleanup */
+  gst_wfd_base_src_cleanup (src);
+
+  return TRUE;
+}
+
+
+static GstStateChangeReturn
+gst_wfd_base_src_change_state (GstElement * element, GstStateChange transition)
+{
+  GstWFDBaseSrc *src;
+  GstStateChangeReturn ret;
+
+  src = GST_WFD_BASE_SRC (element);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_NULL_TO_READY:
+      GST_DEBUG_OBJECT (src, "NULL->READY");
+      if (!gst_wfd_base_src_start (src))
+        goto start_failed;
+      break;
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      GST_DEBUG_OBJECT (src, "READY->PAUSED");
+      gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_OPEN, 0);
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      GST_DEBUG_OBJECT(src, "PAUSED->PLAYING");
+      break;
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+      GST_DEBUG_OBJECT(src, "PLAYING->PAUSED");
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      GST_DEBUG_OBJECT(src, "PAUSED->READY");
+      break;
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      GST_DEBUG_OBJECT (src, "READY->NULL");
+      break;
+    default:
+      break;
+  }
+
+  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
+  if (ret == GST_STATE_CHANGE_FAILURE)
+    goto done;
+
+  switch (transition) {
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      gst_wfd_base_src_loop_send_cmd (src, WFD_CMD_PLAY, WFD_CMD_LOOP);
+      break;
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      ret = GST_STATE_CHANGE_NO_PREROLL;
+      break;
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      gst_wfd_base_src_stop (src);
+      break;
+    default:
+      break;
+  }
+
+done:
+  return ret;
+
+start_failed:
+  {
+    GST_ERROR_OBJECT (src, "start failed");
+    return GST_STATE_CHANGE_FAILURE;
+  }
+}
+
+static gboolean
+gst_wfd_base_src_send_event (GstElement * element, GstEvent * event)
+{
+  gboolean res = FALSE;
+  GstWFDBaseSrc *src;
+  GstWFDBaseSrcClass *klass;
+
+  src = GST_WFD_BASE_SRC (element);
+  klass = GST_WFD_BASE_SRC_GET_CLASS (src);
+
+  if (GST_EVENT_IS_DOWNSTREAM (event)) {
+    if (klass->push_event)
+      res = klass->push_event(src, event);
+  } else {
+    res = GST_ELEMENT_CLASS (parent_class)->send_event (element, event);
+  }
+
+  return res;
+}
+
+static void
+gst_wfd_base_src_set_standby (GstWFDBaseSrc * src)
+{
+  GST_OBJECT_LOCK(src);
+  memset (&src->request_param, 0, sizeof(GstWFDRequestParam));
+  src->request_param.type = WFD_STANDBY;
+  GST_OBJECT_UNLOCK(src);
+
+  gst_wfd_base_src_loop_send_cmd(src, WFD_CMD_REQUEST, WFD_CMD_LOOP);
+}
+
+gboolean
+gst_wfd_base_src_set_target (GstWFDBaseSrc * src, GstPad *target)
+{
+  gboolean ret;
+
+  ret = gst_ghost_pad_set_target (GST_GHOST_PAD (src->srcpad), target);
+
+  return ret;
+}
+
+GstRTSPTransport gst_wfd_base_src_get_transport (GstWFDBaseSrc *src)
+{
+  GstRTSPTransport transport;
+
+  GST_OBJECT_LOCK(src);
+  transport = src->priv->transport;
+  GST_OBJECT_UNLOCK(src);
+
+  return transport;
+}
+
+
+/*** GSTURIHANDLER INTERFACE *************************************************/
+static GstURIType
+gst_wfd_base_src_uri_get_type (GType type)
+{
+  return GST_URI_SRC;
+}
+
+static const gchar * const *
+gst_wfd_base_src_uri_get_protocols (GType type)
+{
+  static const gchar *protocols[] =
+      { "rtsp", NULL };
+
+  return protocols;
+}
+
+static gchar *
+gst_wfd_base_src_uri_get_uri (GstURIHandler * handler)
+{
+  GstWFDBaseSrc *src = GST_WFD_BASE_SRC (handler);
+
+  /* should not dup */
+  return src->priv->conninfo.location;
+}
+
+static gboolean
+gst_wfd_base_src_uri_set_uri (GstURIHandler * handler, const gchar * uri, GError **error)
+{
+  GstWFDBaseSrc *src;
+  GstRTSPResult res;
+  GstRTSPUrl *newurl = NULL;
+
+  src = GST_WFD_BASE_SRC (handler);
+
+  /* same URI, we're fine */
+  if (src->priv->conninfo.location && uri && !strcmp (uri, src->priv->conninfo.location))
+    goto was_ok;
+
+    /* try to parse */
+    GST_DEBUG_OBJECT (src, "parsing URI");
+    if ((res = gst_rtsp_url_parse (uri, &newurl)) < 0)
+      goto parse_error;
+
+
+  /* if worked, free previous and store new url object along with the original
+   * location. */
+  GST_DEBUG_OBJECT (src, "configuring URI");
+  g_free (src->priv->conninfo.location);
+  src->priv->conninfo.location = g_strdup (uri);
+  gst_rtsp_url_free (src->priv->conninfo.url);
+  src->priv->conninfo.url = newurl;
+  g_free (src->priv->conninfo.url_str);
+  if (newurl)
+    src->priv->conninfo.url_str = gst_rtsp_url_get_request_uri (src->priv->conninfo.url);
+  else
+    src->priv->conninfo.url_str = NULL;
+
+  GST_DEBUG_OBJECT (src, "set uri: %s", GST_STR_NULL (uri));
+  GST_DEBUG_OBJECT (src, "request uri is: %s",
+      GST_STR_NULL (src->priv->conninfo.url_str));
+
+  return TRUE;
+
+  /* Special cases */
+was_ok:
+  {
+    GST_DEBUG_OBJECT (src, "URI was ok: '%s'", GST_STR_NULL (uri));
+    return TRUE;
+  }
+parse_error:
+  {
+    GST_ERROR_OBJECT (src, "Not a valid RTSP url '%s' (%d)",
+        GST_STR_NULL (uri), res);
+    return FALSE;
+  }
+}
+
+static void
+gst_wfd_base_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
+{
+  GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
+
+  iface->get_type = gst_wfd_base_src_uri_get_type;
+  iface->get_protocols = gst_wfd_base_src_uri_get_protocols;
+  iface->get_uri = gst_wfd_base_src_uri_get_uri;
+  iface->set_uri = gst_wfd_base_src_uri_set_uri;
+}
+
+static GstRTSPResult _get_cea_resolution_and_set_to_src(GstWFDBaseSrc *src, GstWFDVideoCEAResolution Resolution)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDVideoCEAResolution CEARes = Resolution;
+
+  switch(CEARes)
+  {
+    case GST_WFD_CEA_UNKNOWN:
+      break;
+    case GST_WFD_CEA_640x480P60:
+      priv->video_width=640;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_CEA_720x480P60:
+      priv->video_width=720;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_CEA_720x480I60:
+      priv->video_width=720;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_CEA_720x576P50:
+      priv->video_width=720;
+      priv->video_height=576;
+      priv->video_framerate=50;
+      break;
+    case GST_WFD_CEA_720x576I50:
+       priv->video_width=720;
+      priv->video_height=576;
+      priv->video_framerate=50;
+      break;
+    case GST_WFD_CEA_1280x720P30:
+      priv->video_width=1280;
+      priv->video_height=720;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_CEA_1280x720P60:
+      priv->video_width=1280;
+      priv->video_height=720;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_CEA_1920x1080P30:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_CEA_1920x1080P60:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_CEA_1920x1080I60:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_CEA_1280x720P25:
+      priv->video_width=1280;
+      priv->video_height=720;
+      priv->video_framerate=25;
+      break;
+    case GST_WFD_CEA_1280x720P50:
+      priv->video_width=1280;
+      priv->video_height=720;
+      priv->video_framerate=50;
+      break;
+    case GST_WFD_CEA_1920x1080P25:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=25;
+      break;
+    case GST_WFD_CEA_1920x1080P50:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=50;
+      break;
+    case GST_WFD_CEA_1920x1080I50:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=50;
+      break;
+    case GST_WFD_CEA_1280x720P24:
+      priv->video_width=1280;
+      priv->video_height=720;
+      priv->video_framerate=24;
+      break;
+    case GST_WFD_CEA_1920x1080P24:
+      priv->video_width=1920;
+      priv->video_height=1080;
+      priv->video_framerate=24;
+      break;
+    default:
+      break;
+  }
+  return GST_RTSP_OK;
+}
+
+static GstRTSPResult _get_vesa_resolution_and_set_to_src(GstWFDBaseSrc *src, GstWFDVideoVESAResolution Resolution)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDVideoVESAResolution VESARes = Resolution;
+
+  switch(VESARes)
+  {
+    case GST_WFD_VESA_UNKNOWN:
+      break;
+    case GST_WFD_VESA_800x600P30:
+      priv->video_width=800;
+      priv->video_height=600;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_800x600P60:
+      priv->video_width=800;
+      priv->video_height=600;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1024x768P30:
+      priv->video_width=1024;
+      priv->video_height=768;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1024x768P60:
+      priv->video_width=1024;
+      priv->video_height=768;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1152x864P30:
+      priv->video_width=1152;
+      priv->video_height=864;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1152x864P60:
+      priv->video_width=1152;
+      priv->video_height=864;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1280x768P30:
+      priv->video_width=1280;
+      priv->video_height=768;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1280x768P60:
+      priv->video_width=1280;
+      priv->video_height=768;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1280x800P30:
+      priv->video_width=1280;
+      priv->video_height=800;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1280x800P60:
+      priv->video_width=1280;
+      priv->video_height=800;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1360x768P30:
+      priv->video_width=1360;
+      priv->video_height=768;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1360x768P60:
+      priv->video_width=1360;
+      priv->video_height=768;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1366x768P30:
+      priv->video_width=1366;
+      priv->video_height=768;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1366x768P60:
+      priv->video_width=1366;
+      priv->video_height=768;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1280x1024P30:
+      priv->video_width=1280;
+      priv->video_height=1024;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1280x1024P60:
+      priv->video_width=1280;
+      priv->video_height=1024;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1400x1050P30:
+      priv->video_width=1400;
+      priv->video_height=1050;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1400x1050P60:
+      priv->video_width=1400;
+      priv->video_height=1050;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1440x900P30:
+      priv->video_width=1440;
+      priv->video_height=900;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1440x900P60:
+      priv->video_width=1440;
+      priv->video_height=900;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1600x900P30:
+      priv->video_width=1600;
+      priv->video_height=900;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1600x900P60:
+      priv->video_width=1600;
+      priv->video_height=900;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1600x1200P30:
+      priv->video_width=1600;
+      priv->video_height=1200;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1600x1200P60:
+      priv->video_width=1600;
+      priv->video_height=1200;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1680x1024P30:
+      priv->video_width=1680;
+      priv->video_height=1024;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1680x1024P60:
+      priv->video_width=1680;
+      priv->video_height=1024;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1680x1050P30:
+      priv->video_width=1680;
+      priv->video_height=1050;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1680x1050P60:
+      priv->video_width=1680;
+      priv->video_height=1050;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_VESA_1920x1200P30:
+      priv->video_width=1920;
+      priv->video_height=1200;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_VESA_1920x1200P60:
+      priv->video_width=1920;
+      priv->video_height=1200;
+      priv->video_framerate=60;
+      break;
+    default:
+      break;
+  }
+  return GST_RTSP_OK;
+}
+
+static GstRTSPResult _get_hh_resolution_and_set_to_src(GstWFDBaseSrc *src, GstWFDVideoHHResolution Resolution)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDVideoHHResolution HHRes = Resolution;
+
+  switch(HHRes)
+  {
+    case GST_WFD_HH_UNKNOWN:
+      break;
+    case GST_WFD_HH_800x480P30:
+      priv->video_width=800;
+      priv->video_height=480;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_HH_800x480P60:
+      priv->video_width=800;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_HH_854x480P30:
+      priv->video_width=854;
+      priv->video_height=480;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_HH_854x480P60:
+      priv->video_width=854;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_HH_864x480P30:
+      priv->video_width=864;
+      priv->video_height=480;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_HH_864x480P60:
+      priv->video_width=864;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_HH_640x360P30:
+      priv->video_width=640;
+      priv->video_height=360;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_HH_640x360P60:
+      priv->video_width=640;
+      priv->video_height=360;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_HH_960x540P30:
+      priv->video_width=960;
+      priv->video_height=540;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_HH_960x540P60:
+      priv->video_width=960;
+      priv->video_height=540;
+      priv->video_framerate=60;
+      break;
+    case GST_WFD_HH_848x480P30:
+      priv->video_width=848;
+      priv->video_height=480;
+      priv->video_framerate=30;
+      break;
+    case GST_WFD_HH_848x480P60:
+      priv->video_width=848;
+      priv->video_height=480;
+      priv->video_framerate=60;
+      break;
+    default:
+      break;
+  }
+  return GST_RTSP_OK;
+}
+
+static GstRTSPResult
+gst_wfd_base_src_get_audio_parameter(GstWFDBaseSrc * src, GstWFDMessage * msg)
+{
+  GstWFDBaseSrcPrivate *priv = src->priv;
+  GstWFDAudioFormats audio_format = GST_WFD_AUDIO_UNKNOWN;
+  GstWFDAudioChannels audio_channels = GST_WFD_CHANNEL_UNKNOWN;
+  GstWFDAudioFreq audio_frequency = GST_WFD_FREQ_UNKNOWN;
+  guint audio_bitwidth = 0;
+  guint32 audio_latency = 0;
+  GstWFDResult wfd_res = GST_WFD_OK;
+
+  wfd_res = gst_wfd_message_get_prefered_audio_format (msg, &audio_format, &audio_frequency, &audio_channels, &audio_bitwidth, &audio_latency);
+  if(wfd_res != GST_WFD_OK) {
+    GST_ERROR("Failed to get prefered audio format.");
+    return GST_RTSP_ERROR;
+  }
+
+  priv->audio_format = g_strdup(msg->audio_codecs->list->audio_format);
+  if(audio_frequency == GST_WFD_FREQ_48000)
+    audio_frequency = 48000;
+  else if(audio_frequency == GST_WFD_FREQ_44100)
+    audio_frequency = 44100;
+
+  if(audio_channels == GST_WFD_CHANNEL_2)
+    audio_channels = 2;
+  else if(audio_channels == GST_WFD_CHANNEL_4)
+    audio_channels = 4;
+  else if(audio_channels == GST_WFD_CHANNEL_6)
+    audio_channels = 6;
+  else if(audio_channels == GST_WFD_CHANNEL_8)
+    audio_channels = 8;
+
+  priv->audio_channels = audio_channels;
+  priv->audio_frequency = audio_frequency;
+  priv->audio_bitwidth = audio_bitwidth;
+
+  return GST_RTSP_OK;
+}
+
+static GstRTSPResult
+gst_wfd_base_src_get_video_parameter(GstWFDBaseSrc * src, GstWFDMessage * msg)
+{
+  GstWFDVideoCodecs cvCodec = GST_WFD_VIDEO_UNKNOWN;
+  GstWFDVideoNativeResolution cNative = GST_WFD_VIDEO_CEA_RESOLUTION;
+  guint64 cNativeResolution = 0;
+  GstWFDVideoCEAResolution cCEAResolution = GST_WFD_CEA_UNKNOWN;
+  GstWFDVideoVESAResolution cVESAResolution = GST_WFD_VESA_UNKNOWN;
+  GstWFDVideoHHResolution cHHResolution = GST_WFD_HH_UNKNOWN;
+  GstWFDVideoH264Profile cProfile = GST_WFD_H264_UNKNOWN_PROFILE;
+  GstWFDVideoH264Level cLevel = GST_WFD_H264_LEVEL_UNKNOWN;
+  guint32 cMaxHeight = 0;
+  guint32 cMaxWidth = 0;
+  guint32 cmin_slice_size = 0;
+  guint32 cslice_enc_params = 0;
+  guint cframe_rate_control = 0;
+  guint cvLatency = 0;
+  GstWFDResult wfd_res = GST_WFD_OK;
+
+  wfd_res = gst_wfd_message_get_prefered_video_format (msg, &cvCodec, &cNative, &cNativeResolution,
+      &cCEAResolution, &cVESAResolution, &cHHResolution,
+      &cProfile, &cLevel, &cvLatency, &cMaxHeight,
+      &cMaxWidth, &cmin_slice_size, &cslice_enc_params, &cframe_rate_control);
+  if(wfd_res != GST_WFD_OK) {
+      GST_ERROR("Failed to get prefered video format.");
+      return GST_RTSP_ERROR;
+  }
+#if 0
+  switch(cNative)
+  {
+    case GST_WFD_VIDEO_CEA_RESOLUTION:
+      _get_cea_resolution_and_set_to_src(src, cCEAResolution);
+      break;
+    case GST_WFD_VIDEO_VESA_RESOLUTION:
+      _get_vesa_resolution_and_set_to_src(src, cVESAResolution);
+      break;
+    case GST_WFD_VIDEO_HH_RESOLUTION:
+      _get_hh_resolution_and_set_to_src(src, cHHResolution);
+      break;
+    default:
+      break;
+  }
+#endif
+
+  if(cCEAResolution != GST_WFD_CEA_UNKNOWN) {
+    _get_cea_resolution_and_set_to_src(src, cCEAResolution);
+  }
+  else if(cVESAResolution != GST_WFD_VESA_UNKNOWN) {
+    _get_vesa_resolution_and_set_to_src(src, cVESAResolution);
+  }
+   else if(cHHResolution != GST_WFD_HH_UNKNOWN) {
+    _get_hh_resolution_and_set_to_src(src, cHHResolution);
+  }
+
+  return GST_RTSP_OK;
+}
+
+/*rtsp dump code start*/
+typedef struct _RTSPKeyValue
+{
+  GstRTSPHeaderField field;
+  gchar *value;
+  gchar *custom_key;            /* custom header string (field is INVALID then) */
+} RTSPKeyValue;
+
+static void
+_key_value_foreach (GArray * array, GFunc func, gpointer user_data)
+{
+  guint i;
+
+  g_return_if_fail (array != NULL);
+
+  for (i = 0; i < array->len; i++) {
+    (*func) (&g_array_index (array, RTSPKeyValue, i), user_data);
+  }
+}
+
+static void
+_dump_key_value (gpointer data, gpointer user_data G_GNUC_UNUSED)
+{
+  RTSPKeyValue *key_value = (RTSPKeyValue *) data;
+  const gchar *key_string;
+
+  if (key_value->custom_key != NULL)
+    key_string = key_value->custom_key;
+  else
+    key_string = gst_rtsp_header_as_text (key_value->field);
+
+  GST_ERROR ("   key: '%s', value: '%s'", key_string, key_value->value);
+}
+
+static const char *
+_cmd_to_string (guint cmd)
+{
+  switch (cmd) {
+    case WFD_CMD_OPEN:
+      return "OPEN";
+    case WFD_CMD_PLAY:
+      return "PLAY";
+    case WFD_CMD_PAUSE:
+      return "PAUSE";
+    case WFD_CMD_CLOSE:
+      return "CLOSE";
+    case WFD_CMD_WAIT:
+      return "WAIT";
+    case WFD_CMD_LOOP:
+      return "LOOP";
+    case WFD_CMD_REQUEST:
+      return "REQUEST";
+  }
+
+  return "unknown";
+}
+
+static GstRTSPResult
+_rtsp_message_dump (GstRTSPMessage * msg)
+{
+  guint8 *data;
+  guint size;
+
+  g_return_val_if_fail (msg != NULL, GST_RTSP_EINVAL);
+
+  GST_ERROR("------------------------------------------------------");
+  switch (msg->type) {
+    case GST_RTSP_MESSAGE_REQUEST:
+      GST_ERROR ("RTSP request message %p", msg);
+      GST_ERROR (" request line:");
+      GST_ERROR ("   method: '%s'",
+          gst_rtsp_method_as_text (msg->type_data.request.method));
+      GST_ERROR ("   uri:    '%s'", msg->type_data.request.uri);
+      GST_ERROR ("   version: '%s'",
+          gst_rtsp_version_as_text (msg->type_data.request.version));
+      GST_ERROR (" headers:");
+      _key_value_foreach (msg->hdr_fields, _dump_key_value, NULL);
+      GST_ERROR (" body:");
+      gst_rtsp_message_get_body (msg, &data, &size);
+      //gst_util_dump_mem (data, size);
+      if (size > 0) GST_ERROR ("%s(%d)", data, size);
+      break;
+    case GST_RTSP_MESSAGE_RESPONSE:
+      GST_ERROR ("RTSP response message %p", msg);
+      GST_ERROR (" status line:");
+      GST_ERROR ("   code:   '%d'", msg->type_data.response.code);
+      GST_ERROR ("   reason: '%s'", msg->type_data.response.reason);
+      GST_ERROR ("   version: '%s'",
+          gst_rtsp_version_as_text (msg->type_data.response.version));
+      GST_ERROR (" headers:");
+      _key_value_foreach (msg->hdr_fields, _dump_key_value, NULL);
+      gst_rtsp_message_get_body (msg, &data, &size);
+      GST_ERROR (" body: length %d", size);
+      //gst_util_dump_mem (data, size);
+      if (size > 0) GST_ERROR ("%s(%d)", data, size);
+      break;
+    case GST_RTSP_MESSAGE_HTTP_REQUEST:
+      GST_ERROR ("HTTP request message %p", msg);
+      GST_ERROR (" request line:");
+      GST_ERROR ("   method:  '%s'",
+          gst_rtsp_method_as_text (msg->type_data.request.method));
+      GST_ERROR ("   uri:     '%s'", msg->type_data.request.uri);
+      GST_ERROR ("   version: '%s'",
+          gst_rtsp_version_as_text (msg->type_data.request.version));
+      GST_ERROR (" headers:");
+      _key_value_foreach (msg->hdr_fields, _dump_key_value, NULL);
+      GST_ERROR (" body:");
+      gst_rtsp_message_get_body (msg, &data, &size);
+      //gst_util_dump_mem (data, size);
+      if (size > 0) GST_ERROR ("%s(%d)", data, size);
+      break;
+    case GST_RTSP_MESSAGE_HTTP_RESPONSE:
+      GST_ERROR ("HTTP response message %p", msg);
+      GST_ERROR (" status line:");
+      GST_ERROR ("   code:    '%d'", msg->type_data.response.code);
+      GST_ERROR ("   reason:  '%s'", msg->type_data.response.reason);
+      GST_ERROR ("   version: '%s'",
+          gst_rtsp_version_as_text (msg->type_data.response.version));
+      GST_ERROR (" headers:");
+      _key_value_foreach (msg->hdr_fields, _dump_key_value, NULL);
+      gst_rtsp_message_get_body (msg, &data, &size);
+      GST_ERROR (" body: length %d", size);
+      //gst_util_dump_mem (data, size);
+      if (size > 0) GST_ERROR ("%s(%d)", data, size);
+      break;
+    case GST_RTSP_MESSAGE_DATA:
+      GST_ERROR ("RTSP data message %p", msg);
+      GST_ERROR (" channel: '%d'", msg->type_data.data.channel);
+      GST_ERROR (" size:    '%d'", msg->body_size);
+      gst_rtsp_message_get_body (msg, &data, &size);
+      //gst_util_dump_mem (data, size);
+      if (size > 0) GST_ERROR ("%s(%d)", data, size);
+      break;
+    default:
+      GST_ERROR ("unsupported message type %d", msg->type);
+      return GST_RTSP_EINVAL;
+  }
+
+  GST_ERROR("------------------------------------------------------");
+  return GST_RTSP_OK;
+}
+/*rtsp dump code end*/
diff --git a/wfdmanager/wfdbase/gstwfdbasesrc.h b/wfdmanager/wfdbase/gstwfdbasesrc.h
new file mode 100644 (file)
index 0000000..6e377ca
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * wfdbasesrc
+ *
+ * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.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.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+
+
+#ifndef __GST_WFD_BASE_SRC_H__
+#define __GST_WFD_BASE_SRC_H__
+
+#include <gst/gst.h>
+
+G_BEGIN_DECLS
+
+#include <gst/rtsp/rtsp.h>
+#include <sys/ioctl.h>
+#include <netdb.h>
+#include <sys/socket.h>
+#include <fcntl.h>
+#include <netinet/in.h>
+
+#include "gstwfdsinkmessage.h"
+
+#define ENABLE_WFD_MESSAGE
+
+#define GST_TYPE_WFD_BASE_SRC (gst_wfd_base_src_get_type())
+#define GST_WFD_BASE_SRC(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_WFD_BASE_SRC,GstWFDBaseSrc))
+#define GST_WFD_BASE_SRC_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_WFD_BASE_SRC,GstWFDBaseSrcClass))
+#define GST_WFD_BASE_SRC_GET_CLASS(obj)     (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_WFD_BASE_SRC, GstWFDBaseSrcClass))
+#define GST_IS_WFD_BASE_SRC(obj)  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_BASE_SRC))
+#define GST_IS_WFD_BASE_SRC_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_BASE_SRC))
+#define GST_WFD_BASE_SRC_CAST(obj)   ((GstWFDBaseSrc *)(obj))
+
+typedef struct _GstWFDBaseSrc GstWFDBaseSrc;
+typedef struct _GstWFDBaseSrcClass GstWFDBaseSrcClass;
+typedef struct _GstWFDBaseSrcPrivate GstWFDBaseSrcPrivate;
+
+#define GST_WFD_BASE_STATE_GET_LOCK(wfd)   ((GST_WFD_BASE_SRC_CAST(wfd)->state_rec_lock))
+#define GST_WFD_BASE_STATE_LOCK(wfd)       (g_rec_mutex_lock (&(GST_WFD_BASE_STATE_GET_LOCK(wfd))))
+#define GST_WFD_BASE_STATE_UNLOCK(wfd)     (g_rec_mutex_unlock (&(GST_WFD_BASE_STATE_GET_LOCK(wfd))))
+
+typedef enum
+{
+  WFD_PARAM_NONE,
+  WFD_ROUTE,
+  WFD_CONNECTOR_TYPE,
+  WFD_STANDBY,
+  WFD_IDR_REQUEST,
+  WFD_SINK_STATUS
+} GstWFDParam;
+
+typedef struct {
+  GstWFDParam type;
+
+  union {
+    struct {
+      GstWFDSinkType type;
+    }route_setting;
+    struct {
+      GstWFDConnector type;
+    }connector_setting;
+  };
+}GstWFDRequestParam;
+
+struct _GstWFDBaseSrc {
+  GstBin           parent;
+
+  /*< protected >*/
+  GstPad       *srcpad;
+  GstCaps      *caps;
+  gboolean      is_ipv6;
+
+  GstWFDRequestParam request_param;
+  gboolean          enable_pad_probe;
+
+  /* mutex for protecting state changes */
+  GRecMutex        state_rec_lock;
+
+  GstWFDBaseSrcPrivate *priv;
+};
+
+struct _GstWFDBaseSrcClass {
+  GstBinClass parent_class;
+
+  /*< public >*/
+  /* virtual methods for subclasses */
+  GstRTSPResult     (*handle_set_parameter)       (GstWFDBaseSrc *src, GstRTSPMessage * request, GstRTSPMessage * response);
+  GstRTSPResult      (*handle_get_parameter)     (GstWFDBaseSrc *src, GstRTSPMessage * request, GstRTSPMessage * response);
+  GstRTSPResult      (*prepare_transport)     (GstWFDBaseSrc *src, gint rtpport, gint rtcpport);
+  GstRTSPResult      (*configure_transport)    (GstWFDBaseSrc *src, GstRTSPTransport * transport);
+  gboolean      (*push_event)     (GstWFDBaseSrc *src, GstEvent *event);
+  void      (*set_state)     (GstWFDBaseSrc *src, GstState state);
+  void      (*cleanup)     (GstWFDBaseSrc *src);
+
+  /* signals */
+  void     (*update_media_info)       (GstWFDBaseSrc *src, GstStructure * str);
+  void     (*change_av_format)       (GstWFDBaseSrc *src, gpointer *need_to_flush);
+
+  /* actions */
+  void     (*pause)   (GstWFDBaseSrc *src);
+  void     (*resume)   (GstWFDBaseSrc *src);
+  void     (*close)   (GstWFDBaseSrc *src);
+  void     (*set_standby)   (GstWFDBaseSrc *src);
+};
+
+GType gst_wfd_base_src_get_type(void);
+
+gboolean gst_wfd_base_src_set_target (GstWFDBaseSrc * src, GstPad *target);
+gboolean gst_wfd_base_src_activate (GstWFDBaseSrc *src);
+void gst_wfd_base_src_get_transport_info (GstWFDBaseSrc *src,
+    GstRTSPTransport * transport, const gchar ** destination, gint * min, gint * max);
+GstRTSPTransport gst_wfd_base_src_get_transport (GstWFDBaseSrc *src);
+
+G_END_DECLS
+
+#endif /* __GST_WFD_BASE_SRC_H__ */
diff --git a/wfdmanager/wfdbase/gstwfdsinkmessage.c b/wfdmanager/wfdbase/gstwfdsinkmessage.c
new file mode 100755 (executable)
index 0000000..5dc4edf
--- /dev/null
@@ -0,0 +1,1761 @@
+/*
+ * wfdrtsp message
+ *
+ * Copyright (c) 2011 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Taewan Kim<taewan79.kim@samsung.com>, Yejin Cho<cho.yejin@samsung.com>, Sangkyu Park<sk1122.park@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library (COPYING); if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#include <glib.h>               /* for G_OS_WIN32 */
+#include "gstwfdsinkmessage.h"
+#include <gio/gio.h>
+
+/* FIXME, is currently allocated on the stack */
+#define MAX_LINE_LEN    (1024 * 16)
+
+#define FREE_STRING(field)              if (field != NULL) g_free(field); (field) = NULL;
+#define REPLACE_STRING(field, val)      FREE_STRING(field); (field) = g_strdup(val);
+#define EDID_BLOCK_SIZE 128
+#define EDID_BLOCK_COUNT_MAX_SIZE 256
+
+enum {
+  GST_WFD_SESSION,
+  GST_WFD_MEDIA,
+};
+
+typedef struct {
+  guint state;
+  GstWFDMessage *msg;
+} WFDContext;
+
+/**
+* gst_wfd_message_new:
+* @msg: pointer to new #GstWFDMessage
+*
+* Allocate a new GstWFDMessage and store the result in @msg.
+*
+* Returns: a #GstWFDResult.
+*/
+GstWFDResult
+gst_wfd_message_new(GstWFDMessage **msg)
+{
+  GstWFDMessage *newmsg;
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  newmsg = g_new0(GstWFDMessage, 1);
+
+  *msg = newmsg;
+
+  return gst_wfd_message_init(newmsg);
+}
+
+/**
+* gst_wfd_message_init:
+* @msg: a #GstWFDMessage
+*
+* Initialize @msg so that its contents are as if it was freshly allocated
+* with gst_wfd_message_new(). This function is mostly used to initialize a message
+* allocated on the stack. gst_wfd_message_uninit() undoes this operation.
+*
+* When this function is invoked on newly allocated data(with malloc or on the
+* stack), its contents should be set to 0 before calling this function.
+*
+* Returns: a #GstWFDResult.
+*/
+GstWFDResult
+gst_wfd_message_init(GstWFDMessage *msg)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  return GST_WFD_OK;
+}
+
+/**
+* gst_wfd_message_uninit:
+* @msg: a #GstWFDMessage
+*
+* Free all resources allocated in @msg. @msg should not be used anymore after
+* this function. This function should be used when @msg was allocated on the
+* stack and initialized with gst_wfd_message_init().
+*
+* Returns: a #GstWFDResult.
+*/
+GstWFDResult
+gst_wfd_message_uninit(GstWFDMessage *msg)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (msg->audio_codecs) {
+    guint i = 0;
+    if (msg->audio_codecs->list) {
+      for (; i < msg->audio_codecs->count; i++) {
+        FREE_STRING(msg->audio_codecs->list[i].audio_format);
+        msg->audio_codecs->list[i].modes = 0;
+        msg->audio_codecs->list[i].latency = 0;
+      }
+      FREE_STRING(msg->audio_codecs->list);
+    }
+    FREE_STRING(msg->audio_codecs);
+  }
+
+  if (msg->video_formats) {
+    FREE_STRING(msg->video_formats->list);
+    FREE_STRING(msg->video_formats);
+  }
+
+  if (msg->video_3d_formats) {
+    FREE_STRING(msg->video_3d_formats->list);
+    FREE_STRING(msg->video_3d_formats);
+  }
+
+  if (msg->content_protection) {
+    if (msg->content_protection->hdcp2_spec) {
+      FREE_STRING(msg->content_protection->hdcp2_spec->hdcpversion);
+      FREE_STRING(msg->content_protection->hdcp2_spec->TCPPort);
+      FREE_STRING(msg->content_protection->hdcp2_spec);
+    }
+    FREE_STRING(msg->content_protection);
+  }
+
+  if (msg->display_edid) {
+    if (msg->display_edid->edid_payload)
+      FREE_STRING(msg->display_edid->edid_payload);
+    FREE_STRING(msg->display_edid);
+  }
+
+  if (msg->coupled_sink) {
+    if (msg->coupled_sink->coupled_sink_cap) {
+      FREE_STRING(msg->coupled_sink->coupled_sink_cap->sink_address);
+      FREE_STRING(msg->coupled_sink->coupled_sink_cap);
+    }
+    FREE_STRING(msg->coupled_sink);
+  }
+
+  if (msg->trigger_method) {
+    FREE_STRING(msg->trigger_method->wfd_trigger_method);
+    FREE_STRING(msg->trigger_method);
+  }
+
+  if (msg->presentation_url) {
+    FREE_STRING(msg->presentation_url->wfd_url0);
+    FREE_STRING(msg->presentation_url->wfd_url1);
+    FREE_STRING(msg->presentation_url);
+  }
+
+  if (msg->client_rtp_ports) {
+    FREE_STRING(msg->client_rtp_ports->profile);
+    FREE_STRING(msg->client_rtp_ports->mode);
+    FREE_STRING(msg->client_rtp_ports);
+  }
+
+  if (msg->route) {
+    FREE_STRING(msg->route->destination);
+    FREE_STRING(msg->route);
+  }
+
+  if (msg->I2C) {
+    FREE_STRING(msg->I2C);
+  }
+
+  if (msg->av_format_change_timing) {
+    FREE_STRING(msg->av_format_change_timing);
+  }
+
+  if (msg->preferred_display_mode) {
+    FREE_STRING(msg->preferred_display_mode);
+  }
+
+  if (msg->standby_resume_capability) {
+    FREE_STRING(msg->standby_resume_capability);
+  }
+
+  if (msg->standby) {
+    FREE_STRING(msg->standby);
+  }
+
+  if (msg->connector_type) {
+    FREE_STRING(msg->connector_type);
+  }
+
+  if (msg->idr_request) {
+    FREE_STRING(msg->idr_request);
+  }
+
+  return GST_WFD_OK;
+}
+
+/**
+* gst_wfd_message_free:
+* @msg: a #GstWFDMessage
+*
+* Free all resources allocated by @msg. @msg should not be used anymore after
+* this function. This function should be used when @msg was dynamically
+* allocated with gst_wfd_message_new().
+*
+* Returns: a #GstWFDResult.
+*/
+GstWFDResult
+gst_wfd_message_free(GstWFDMessage *msg)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  gst_wfd_message_uninit(msg);
+  g_free(msg);
+
+  return GST_WFD_OK;
+}
+
+/**
+* gst_wfd_message_as_text:
+* @msg: a #GstWFDMessage
+*
+* Convert the contents of @msg to a text string.
+*
+* Returns: A dynamically allocated string representing the WFD description.
+*/
+gchar *
+gst_wfd_message_as_text(const GstWFDMessage *msg)
+{
+  /* change all vars so they match rfc? */
+  GString *lines;
+  g_return_val_if_fail(msg != NULL, NULL);
+
+  lines = g_string_new("");
+
+  /* list of audio codecs */
+  if (msg->audio_codecs) {
+    guint i = 0;
+    g_string_append_printf(lines, GST_STRING_WFD_AUDIO_CODECS);
+    if (msg->audio_codecs->list) {
+      g_string_append_printf(lines, GST_STRING_WFD_COLON);
+      for (; i < msg->audio_codecs->count; i++) {
+        g_string_append_printf(lines, " %s", msg->audio_codecs->list[i].audio_format);
+        g_string_append_printf(lines, " %08x", msg->audio_codecs->list[i].modes);
+        g_string_append_printf(lines, " %02x", msg->audio_codecs->list[i].latency);
+        if ((i + 1) < msg->audio_codecs->count)
+          g_string_append_printf(lines, GST_STRING_WFD_COMMA);
+      }
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  /* list of video codecs */
+  if (msg->video_formats) {
+    g_string_append_printf(lines, GST_STRING_WFD_VIDEO_FORMATS);
+    if (msg->video_formats->list) {
+      g_string_append_printf(lines, GST_STRING_WFD_COLON);
+      g_string_append_printf(lines, " %02x", msg->video_formats->list->native);
+      g_string_append_printf(lines, " %02x", msg->video_formats->list->preferred_display_mode_supported);
+      g_string_append_printf(lines, " %02x", msg->video_formats->list->H264_codec.profile);
+      g_string_append_printf(lines, " %02x", msg->video_formats->list->H264_codec.level);
+      g_string_append_printf(lines, " %08x", msg->video_formats->list->H264_codec.misc_params.CEA_Support);
+      g_string_append_printf(lines, " %08x", msg->video_formats->list->H264_codec.misc_params.VESA_Support);
+      g_string_append_printf(lines, " %08x", msg->video_formats->list->H264_codec.misc_params.HH_Support);
+      g_string_append_printf(lines, " %02x", msg->video_formats->list->H264_codec.misc_params.latency);
+      g_string_append_printf(lines, " %04x", msg->video_formats->list->H264_codec.misc_params.min_slice_size);
+      g_string_append_printf(lines, " %04x", msg->video_formats->list->H264_codec.misc_params.slice_enc_params);
+      g_string_append_printf(lines, " %02x", msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support);
+
+      if (msg->video_formats->list->preferred_display_mode_supported == GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED
+        && msg->video_formats->list->H264_codec.max_hres) {
+        g_string_append_printf(lines, " %04x", msg->video_formats->list->H264_codec.max_hres);
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+      if (msg->video_formats->list->preferred_display_mode_supported == GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED
+        && msg->video_formats->list->H264_codec.max_vres) {
+        g_string_append_printf(lines, " %04x", msg->video_formats->list->H264_codec.max_vres);
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  /* list of video 3D codecs */
+  if (msg->video_3d_formats) {
+    g_string_append_printf(lines, GST_STRING_WFD_3D_VIDEO_FORMATS);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    if (msg->video_3d_formats->list) {
+      g_string_append_printf(lines, " %02x", msg->video_3d_formats->list->native);
+      g_string_append_printf(lines, " %02x", msg->video_3d_formats->list->preferred_display_mode_supported);
+      g_string_append_printf(lines, " %02x", msg->video_3d_formats->list->H264_codec.profile);
+      g_string_append_printf(lines, " %02x", msg->video_3d_formats->list->H264_codec.level);
+      g_string_append_printf(lines, " %016llx", msg->video_3d_formats->list->H264_codec.misc_params.video_3d_capability);
+      g_string_append_printf(lines, " %02x", msg->video_3d_formats->list->H264_codec.misc_params.latency);
+      g_string_append_printf(lines, " %04x", msg->video_3d_formats->list->H264_codec.misc_params.min_slice_size);
+      g_string_append_printf(lines, " %04x", msg->video_3d_formats->list->H264_codec.misc_params.slice_enc_params);
+      g_string_append_printf(lines, " %02x", msg->video_3d_formats->list->H264_codec.misc_params.frame_rate_control_support);
+      if (msg->video_3d_formats->list->preferred_display_mode_supported == GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED
+        && msg->video_3d_formats->list->H264_codec.max_hres) {
+        g_string_append_printf(lines, " %04x", msg->video_3d_formats->list->H264_codec.max_hres);
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+
+      if (msg->video_3d_formats->list->preferred_display_mode_supported == GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED
+        && msg->video_3d_formats->list->H264_codec.max_vres) {
+        g_string_append_printf(lines, " %04x", msg->video_3d_formats->list->H264_codec.max_vres);
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->content_protection) {
+    g_string_append_printf(lines, GST_STRING_WFD_CONTENT_PROTECTION);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    if (msg->content_protection->hdcp2_spec) {
+      if (msg->content_protection->hdcp2_spec->hdcpversion) {
+        g_string_append_printf(lines, " %s", msg->content_protection->hdcp2_spec->hdcpversion);
+        g_string_append_printf(lines, " %s", msg->content_protection->hdcp2_spec->TCPPort);
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->display_edid) {
+    g_string_append_printf(lines, GST_STRING_WFD_DISPLAY_EDID);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    if (msg->display_edid->edid_supported) {
+      if (msg->display_edid->edid_block_count > 0 &&
+        msg->display_edid->edid_block_count <= EDID_BLOCK_COUNT_MAX_SIZE) {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE "%04x", msg->display_edid->edid_block_count);
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE "%s", msg->display_edid->edid_payload);
+
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->coupled_sink) {
+    g_string_append_printf(lines, GST_STRING_WFD_COUPLED_SINK);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    if (msg->coupled_sink->coupled_sink_cap) {
+      g_string_append_printf(lines, " %02x", msg->coupled_sink->coupled_sink_cap->status);
+      if (msg->coupled_sink->coupled_sink_cap->sink_address) {
+        g_string_append_printf(lines, " %s", msg->coupled_sink->coupled_sink_cap->sink_address);
+      } else {
+        g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+        g_string_append_printf(lines, GST_STRING_WFD_NONE);
+      }
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->trigger_method) {
+    g_string_append_printf(lines, GST_STRING_WFD_TRIGGER_METHOD);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    g_string_append_printf(lines, " %s", msg->trigger_method->wfd_trigger_method);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->presentation_url) {
+    g_string_append_printf(lines, GST_STRING_WFD_PRESENTATION_URL);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    if (msg->presentation_url->wfd_url0) {
+      g_string_append_printf(lines, " %s", msg->presentation_url->wfd_url0);
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    if (msg->presentation_url->wfd_url1) {
+      g_string_append_printf(lines, " %s", msg->presentation_url->wfd_url1);
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->client_rtp_ports) {
+    g_string_append_printf(lines, GST_STRING_WFD_CLIENT_RTP_PORTS);
+    if (msg->client_rtp_ports->profile) {
+      g_string_append_printf(lines, GST_STRING_WFD_COLON);
+      g_string_append_printf(lines, " %s", msg->client_rtp_ports->profile);
+      g_string_append_printf(lines, " %d", msg->client_rtp_ports->rtp_port0);
+      g_string_append_printf(lines, " %d", msg->client_rtp_ports->rtp_port1);
+      g_string_append_printf(lines, " %s", msg->client_rtp_ports->mode);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->route) {
+    g_string_append_printf(lines, GST_STRING_WFD_ROUTE);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    g_string_append_printf(lines, " %s", msg->route->destination);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->I2C) {
+    g_string_append_printf(lines, GST_STRING_WFD_I2C);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+    if (msg->I2C->I2CPresent) {
+      g_string_append_printf(lines, "%x", msg->I2C->I2C_port);
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->av_format_change_timing) {
+    g_string_append_printf(lines, GST_STRING_WFD_AV_FORMAT_CHANGE_TIMING);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    g_string_append_printf(lines, " %010llx", msg->av_format_change_timing->PTS);
+    g_string_append_printf(lines, " %010llx", msg->av_format_change_timing->DTS);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->preferred_display_mode) {
+    g_string_append_printf(lines, GST_STRING_WFD_PREFERRED_DISPLAY_MODE);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    if (msg->preferred_display_mode->displaymodesupported) {
+      g_string_append_printf(lines, " %06llx", msg->preferred_display_mode->p_clock);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->H);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->HB);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->HSPOL_HSOFF);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->HSW);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->V);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->VB);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->VSPOL_VSOFF);
+      g_string_append_printf(lines, " %04x", msg->preferred_display_mode->VSW);
+      g_string_append_printf(lines, " %02x", msg->preferred_display_mode->VBS3D);
+      g_string_append_printf(lines, " %02x", msg->preferred_display_mode->V2d_s3d_modes);
+      g_string_append_printf(lines, " %02x", msg->preferred_display_mode->P_depth);
+    } else {
+      g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    }
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->standby_resume_capability) {
+    g_string_append_printf(lines, GST_STRING_WFD_STANDBY_RESUME_CAPABILITY);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    g_string_append_printf(lines, GST_STRING_WFD_SPACE);
+    if (msg->standby_resume_capability->standby_resume_cap)
+      g_string_append_printf(lines, GST_STRING_WFD_SUPPORTED);
+    else
+      g_string_append_printf(lines, GST_STRING_WFD_NONE);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->standby) {
+    g_string_append_printf(lines, GST_STRING_WFD_STANDBY);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->connector_type) {
+    g_string_append_printf(lines, GST_STRING_WFD_CONNECTOR_TYPE);
+    g_string_append_printf(lines, GST_STRING_WFD_COLON);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  if (msg->idr_request) {
+    g_string_append_printf(lines, GST_STRING_WFD_IDR_REQUEST);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+
+  /*g_string_append_printf (lines, "\0"); */
+  /*if(g_str_has_suffix (lines, "\r\n\0"))
+  {
+  guint32 length = g_strlen(lines);
+  lines[length-2] = '\0';
+  }*/
+  return g_string_free(lines, FALSE);
+}
+
+gchar *gst_wfd_message_param_names_as_text(const GstWFDMessage *msg)
+{
+  /* change all vars so they match rfc? */
+  GString *lines;
+  g_return_val_if_fail(msg != NULL, NULL);
+
+  lines = g_string_new("");
+
+  /* list of audio codecs */
+  if (msg->audio_codecs) {
+    g_string_append_printf(lines, GST_STRING_WFD_AUDIO_CODECS);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  /* list of video codecs */
+  if (msg->video_formats) {
+    g_string_append_printf(lines, GST_STRING_WFD_VIDEO_FORMATS);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  /* list of video 3D codecs */
+  if (msg->video_3d_formats) {
+    g_string_append_printf(lines, GST_STRING_WFD_3D_VIDEO_FORMATS);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->content_protection) {
+    g_string_append_printf(lines, GST_STRING_WFD_CONTENT_PROTECTION);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->display_edid) {
+    g_string_append_printf(lines, GST_STRING_WFD_DISPLAY_EDID);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->coupled_sink) {
+    g_string_append_printf(lines, GST_STRING_WFD_COUPLED_SINK);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->trigger_method) {
+    g_string_append_printf(lines, GST_STRING_WFD_TRIGGER_METHOD);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->presentation_url) {
+    g_string_append_printf(lines, GST_STRING_WFD_PRESENTATION_URL);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->client_rtp_ports) {
+    g_string_append_printf(lines, GST_STRING_WFD_CLIENT_RTP_PORTS);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->route) {
+    g_string_append_printf(lines, GST_STRING_WFD_ROUTE);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->I2C) {
+    g_string_append_printf(lines, GST_STRING_WFD_I2C);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->av_format_change_timing) {
+    g_string_append_printf(lines, GST_STRING_WFD_AV_FORMAT_CHANGE_TIMING);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->preferred_display_mode) {
+    g_string_append_printf(lines, GST_STRING_WFD_PREFERRED_DISPLAY_MODE);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->standby_resume_capability) {
+    g_string_append_printf(lines, GST_STRING_WFD_STANDBY_RESUME_CAPABILITY);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->standby) {
+    g_string_append_printf(lines, GST_STRING_WFD_STANDBY);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->connector_type) {
+    g_string_append_printf(lines, GST_STRING_WFD_CONNECTOR_TYPE);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  if (msg->idr_request) {
+    g_string_append_printf(lines, GST_STRING_WFD_IDR_REQUEST);
+    g_string_append_printf(lines, GST_STRING_WFD_CRLF);
+  }
+  return g_string_free(lines, FALSE);
+}
+
+static void
+read_string_space_ended(gchar *dest, guint size, gchar *src)
+{
+  guint idx = 0;
+
+  while (!g_ascii_isspace(*src) && *src != '\0') {
+    if (idx < size - 1)
+      dest[idx++] = *src;
+    src++;
+  }
+
+  if (size > 0)
+    dest[idx] = '\0';
+}
+
+static void
+read_string_type_and_value(gchar *type, gchar *value, guint tsize, guint vsize, gchar del, gchar *src)
+{
+  guint idx;
+
+  idx = 0;
+  while (*src != del && *src != '\0') {
+    if (idx < tsize - 1)
+      type[idx++] = *src;
+    src++;
+  }
+
+  if (tsize > 0)
+    type[idx] = '\0';
+
+  src++;
+  idx = 0;
+  while (*src != '\0') {
+    if (idx < vsize - 1)
+      value[idx++] = *src;
+    src++;
+  }
+  if (vsize > 0)
+    value[idx] = '\0';
+}
+
+static gboolean
+gst_wfd_parse_line(GstWFDMessage *msg, gchar *buffer)
+{
+  gchar type[8192] = {0};
+  gchar value[8192] = {0};
+  gchar temp[8192] = {0};
+  gchar *p = buffer;
+  gchar *v = value;
+
+#define GST_WFD_SKIP_SPACE(q) if (*q && g_ascii_isspace(*q)) q++;
+#define GST_WFD_SKIP_EQUAL(q) if (*q && *q == '=') q++;
+#define GST_WFD_SKIP_COMMA(q) if (*q && g_ascii_ispunct(*q)) q++;
+#define GST_WFD_READ_STRING(field) read_string_space_ended(temp, sizeof(temp), v); v += strlen(temp); REPLACE_STRING(field, temp);
+#define GST_WFD_READ_UINT32(field) read_string_space_ended(temp, sizeof(temp), v); v += strlen(temp); field = strtoul(temp, NULL, 16);
+#define GST_WFD_READ_UINT32_DIGIT(field) read_string_space_ended(temp, sizeof(temp), v); v += strlen(temp); field = strtoul(temp, NULL, 10);
+
+  /*g_print("gst_wfd_parse_line input: %s\n", buffer); */
+  read_string_type_and_value(type, value, sizeof(type), sizeof(value), ':', p);
+  /*g_print("gst_wfd_parse_line type:%s value:%s\n", type, value); */
+  if (!g_strcmp0(type, GST_STRING_WFD_AUDIO_CODECS)) {
+    msg->audio_codecs = g_new0(GstWFDAudioCodeclist, 1);
+    if (strlen(v)) {
+      guint i = 0;
+      msg->audio_codecs->count = strlen(v) / 16;
+      msg->audio_codecs->list = g_new0(GstWFDAudioCodec, msg->audio_codecs->count);
+      for (; i < msg->audio_codecs->count; i++) {
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_STRING(msg->audio_codecs->list[i].audio_format);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->audio_codecs->list[i].modes);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->audio_codecs->list[i].latency);
+        GST_WFD_SKIP_COMMA(v);
+      }
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_VIDEO_FORMATS)) {
+    msg->video_formats = g_new0(GstWFDVideoCodeclist, 1);
+    if (strlen(v)) {
+      msg->video_formats->count = 1;
+      msg->video_formats->list = g_new0(GstWFDVideoCodec, 1);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->native);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->preferred_display_mode_supported);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.profile);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.level);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.CEA_Support);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.VESA_Support);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.HH_Support);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.latency);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.min_slice_size);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.slice_enc_params);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support);
+      GST_WFD_SKIP_SPACE(v);
+      if (msg->video_formats->list->preferred_display_mode_supported == GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED) {
+        GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.max_hres);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->video_formats->list->H264_codec.max_vres);
+        GST_WFD_SKIP_SPACE(v);
+      }
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_3D_VIDEO_FORMATS)) {
+    msg->video_3d_formats = g_new0(GstWFD3DFormats, 1);
+    if (strlen(v)) {
+      msg->video_3d_formats->count = 1;
+      msg->video_3d_formats->list = g_new0(GstWFD3dCapList, 1);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->native);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->preferred_display_mode_supported);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.profile);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.level);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.misc_params.video_3d_capability);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.misc_params.latency);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.misc_params.min_slice_size);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.misc_params.slice_enc_params);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.misc_params.frame_rate_control_support);
+      GST_WFD_SKIP_SPACE(v);
+      if (msg->video_3d_formats->list->preferred_display_mode_supported == GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED) {
+        GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.max_hres);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->video_3d_formats->list->H264_codec.max_vres);
+        GST_WFD_SKIP_SPACE(v);
+      }
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_CONTENT_PROTECTION)) {
+    msg->content_protection = g_new0(GstWFDContentProtection, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      msg->content_protection->hdcp2_spec = g_new0(GstWFDHdcp2Spec, 1);
+      if (strstr(v, GST_STRING_WFD_NONE)) {
+        msg->content_protection->hdcp2_spec->hdcpversion = g_strdup(GST_STRING_WFD_NONE);
+      } else {
+        GST_WFD_READ_STRING(msg->content_protection->hdcp2_spec->hdcpversion);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_STRING(msg->content_protection->hdcp2_spec->TCPPort);
+      }
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_DISPLAY_EDID)) {
+    msg->display_edid = g_new0(GstWFDDisplayEdid, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      if (strstr(v, GST_STRING_WFD_NONE)) {
+        msg->display_edid->edid_supported = 0;
+      } else {
+        msg->display_edid->edid_supported = 1;
+        GST_WFD_READ_UINT32(msg->display_edid->edid_block_count);
+        GST_WFD_SKIP_SPACE(v);
+        if (msg->display_edid->edid_block_count) {
+          gchar *edid_string = v;
+          int i = 0, j = 0, size = 0;
+          guint32 payload_size = EDID_BLOCK_SIZE * msg->display_edid->edid_block_count;
+          msg->display_edid->edid_payload = g_malloc(payload_size);
+          size = EDID_BLOCK_SIZE * msg->display_edid->edid_block_count * 2;
+          for (; i < size; j++) {
+            int k = 0, kk = 0;
+            if (edid_string[i] > 0x29 && edid_string[i] < 0x40) k = edid_string[i] - 48;
+            else if (edid_string[i] > 0x60 && edid_string[i] < 0x67) k = edid_string[i] - 87;
+            else if (edid_string[i] > 0x40 && edid_string[i] < 0x47) k = edid_string[i] - 55;
+
+            if (edid_string[i + 1] > 0x29 && edid_string[i + 1] < 0x40) kk = edid_string[i + 1] - 48;
+            else if (edid_string[i + 1] > 0x60 && edid_string[i + 1] < 0x67) kk = edid_string[i + 1] - 87;
+            else if (edid_string[i + 1] > 0x40 && edid_string[i + 1] < 0x47) kk = edid_string[i + 1] - 55;
+
+            msg->display_edid->edid_payload[j] = (k << 4) | kk;
+            i += 2;
+          }
+          /*memcpy(msg->display_edid->edid_payload, v, payload_size); */
+          v += (payload_size * 2);
+        } else v += strlen(v);
+      }
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_COUPLED_SINK)) {
+    msg->coupled_sink = g_new0(GstWFDCoupledSink, 1);
+    if (strlen(v)) {
+      msg->coupled_sink->coupled_sink_cap = g_new0(GstWFDCoupledSinkCap, 1);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->coupled_sink->coupled_sink_cap->status);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->coupled_sink->coupled_sink_cap->sink_address);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_TRIGGER_METHOD)) {
+    msg->trigger_method = g_new0(GstWFDTriggerMethod, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->trigger_method->wfd_trigger_method);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_PRESENTATION_URL)) {
+    msg->presentation_url = g_new0(GstWFDPresentationUrl, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->presentation_url->wfd_url0);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->presentation_url->wfd_url1);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_CLIENT_RTP_PORTS)) {
+    msg->client_rtp_ports = g_new0(GstWFDClientRtpPorts, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->client_rtp_ports->profile);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32_DIGIT(msg->client_rtp_ports->rtp_port0);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32_DIGIT(msg->client_rtp_ports->rtp_port1);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->client_rtp_ports->mode);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_ROUTE)) {
+    msg->route = g_new0(GstWFDRoute, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_STRING(msg->route->destination);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_I2C)) {
+    msg->I2C = g_new0(GstWFDI2C, 1);
+    if (strlen(v)) {
+      msg->I2C->I2CPresent = TRUE;
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32_DIGIT(msg->I2C->I2C_port);
+      if (msg->I2C->I2C_port) msg->I2C->I2CPresent = TRUE;
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_AV_FORMAT_CHANGE_TIMING)) {
+    msg->av_format_change_timing = g_new0(GstWFDAVFormatChangeTiming, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->av_format_change_timing->PTS);
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->av_format_change_timing->DTS);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_PREFERRED_DISPLAY_MODE)) {
+    msg->preferred_display_mode = g_new0(GstWFDPreferredDisplayMode, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      if (!strstr(v, GST_STRING_WFD_NONE)) {
+        msg->preferred_display_mode->displaymodesupported = FALSE;
+      } else {
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->p_clock);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->HB);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->HSPOL_HSOFF);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->HSW);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->V);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->VB);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->VSPOL_VSOFF);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->VSW);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->VBS3D);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->V2d_s3d_modes);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->P_depth);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.profile);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.level);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.CEA_Support);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.VESA_Support);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.HH_Support);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.latency);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.min_slice_size);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.slice_enc_params);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.misc_params.frame_rate_control_support);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.max_hres);
+        GST_WFD_SKIP_SPACE(v);
+        GST_WFD_READ_UINT32(msg->preferred_display_mode->H264_codec.max_vres);
+        GST_WFD_SKIP_SPACE(v);
+      }
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_STANDBY_RESUME_CAPABILITY)) {
+    msg->standby_resume_capability = g_new0(GstWFDStandbyResumeCapability, 1);
+    if (strlen(v)) {
+      GST_WFD_SKIP_SPACE(v);
+      if (!g_strcmp0(v, GST_STRING_WFD_SUPPORTED))
+        msg->standby_resume_capability->standby_resume_cap = TRUE;
+      else
+        msg->standby_resume_capability->standby_resume_cap = FALSE;
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_STANDBY)) {
+    msg->standby = g_new0(GstWFDStandby, 1);
+    msg->standby->wfd_standby = TRUE;
+  } else if (!g_strcmp0(type, GST_STRING_WFD_CONNECTOR_TYPE)) {
+    msg->connector_type = g_new0(GstWFDConnectorType, 1);
+    if (strlen(v)) {
+      msg->connector_type->supported = TRUE;
+      GST_WFD_SKIP_SPACE(v);
+      GST_WFD_READ_UINT32(msg->connector_type->connector_type);
+    }
+  } else if (!g_strcmp0(type, GST_STRING_WFD_IDR_REQUEST)) {
+    msg->idr_request = g_new0(GstWFDIdrRequest, 1);
+    msg->idr_request->idr_request = TRUE;
+  }
+
+  return TRUE;
+}
+
+/**
+* gst_wfd_message_parse_buffer:
+* @data: the start of the buffer
+* @size: the size of the buffer
+* @msg: the result #GstWFDMessage
+*
+* Parse the contents of @size bytes pointed to by @data and store the result in
+* @msg.
+*
+* Returns: #GST_WFD_OK on success.
+*/
+GstWFDResult
+gst_wfd_message_parse_buffer(const guint8 *data, guint size, GstWFDMessage *msg)
+{
+  const gchar *p;
+  gchar buffer[MAX_LINE_LEN] = {0};
+  guint idx = 0;
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(data != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(size != 0, GST_WFD_EINVAL);
+
+  p = (const gchar *) data;
+  while (TRUE) {
+
+    if (*p == '\0')
+      break;
+
+    idx = 0;
+    while (*p != '\n' && *p != '\r' && *p != '\0') {
+      if (idx < sizeof(buffer) - 1)
+        buffer[idx++] = *p;
+      p++;
+    }
+    buffer[idx] = '\0';
+    gst_wfd_parse_line(msg, buffer);
+
+    if (*p == '\0')
+      break;
+    p += 2;
+  }
+
+  return GST_WFD_OK;
+}
+
+/**
+* gst_wfd_message_dump:
+* @msg: a #GstWFDMessage
+*
+* Dump the parsed contents of @msg to stdout.
+*
+* Returns: a #GstWFDResult.
+*/
+GstWFDResult
+gst_wfd_message_dump(const GstWFDMessage *msg)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_print("===========WFD Message dump=========");
+
+  if (msg->audio_codecs) {
+    guint i = 0;
+    g_print("Audio supported formats : ");
+    for (; i < msg->audio_codecs->count; i++) {
+      g_print("Codec: %s", msg->audio_codecs->list[i].audio_format);
+      if (!strcmp(msg->audio_codecs->list[i].audio_format, GST_STRING_WFD_LPCM)) {
+        if (msg->audio_codecs->list[i].modes & GST_WFD_FREQ_44100)
+          g_print("  Freq: %d", 44100);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_FREQ_48000)
+          g_print("  Freq: %d", 48000);
+        g_print("  Channels: %d", 2);
+      }
+      if (!strcmp(msg->audio_codecs->list[i].audio_format, GST_STRING_WFD_AAC)) {
+        g_print("  Freq: %d", 48000);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_2)
+          g_print("  Channels: %d", 2);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_4)
+          g_print("  Channels: %d", 4);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_6)
+          g_print("  Channels: %d", 6);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_8)
+          g_print("  Channels: %d", 8);
+      }
+      if (!strcmp(msg->audio_codecs->list[i].audio_format, GST_STRING_WFD_AC3)) {
+        g_print("  Freq: %d", 48000);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_2)
+          g_print("  Channels: %d", 2);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_4)
+          g_print("  Channels: %d", 4);
+        if (msg->audio_codecs->list[i].modes & GST_WFD_CHANNEL_6)
+          g_print("  Channels: %d", 6);
+      }
+      g_print("  Bitwidth: %d", 16);
+      g_print("  Latency: %d", msg->audio_codecs->list[i].latency);
+    }
+  }
+
+
+  if (msg->video_formats) {
+    g_print("Video supported formats : ");
+    if (msg->video_formats->list) {
+      g_print("Codec: H264");
+      guint nativeindex = 0;
+      if ((msg->video_formats->list->native & 0x7) == GST_WFD_VIDEO_CEA_RESOLUTION) {
+        g_print("  Native type: CEA");
+      } else if ((msg->video_formats->list->native & 0x7) == GST_WFD_VIDEO_VESA_RESOLUTION) {
+        g_print("  Native type: VESA");
+      } else if ((msg->video_formats->list->native & 0x7) == GST_WFD_VIDEO_HH_RESOLUTION) {
+        g_print("  Native type: HH");
+      }
+      nativeindex = msg->video_formats->list->native >> 3;
+      g_print("  Resolution: %d", (1 << nativeindex));
+
+      if (msg->video_formats->list->H264_codec.profile & GST_WFD_H264_BASE_PROFILE) {
+        g_print("  Profile: BASE");
+      } else if (msg->video_formats->list->H264_codec.profile & GST_WFD_H264_HIGH_PROFILE) {
+        g_print("  Profile: HIGH");
+      }
+      if (msg->video_formats->list->H264_codec.level & GST_WFD_H264_LEVEL_3_1) {
+        g_print("  Level: 3.1");
+      } else if (msg->video_formats->list->H264_codec.level & GST_WFD_H264_LEVEL_3_2) {
+        g_print("  Level: 3.2");
+      } else if (msg->video_formats->list->H264_codec.level & GST_WFD_H264_LEVEL_4) {
+        g_print("  Level: 4");
+      } else if (msg->video_formats->list->H264_codec.level & GST_WFD_H264_LEVEL_4_1) {
+        g_print("  Level: 4.1");
+      } else if (msg->video_formats->list->H264_codec.level & GST_WFD_H264_LEVEL_4_2) {
+        g_print("  Level: 4.2");
+      }
+      g_print("  Latency: %d", msg->video_formats->list->H264_codec.misc_params.latency);
+      g_print("  min_slice_size: %x", msg->video_formats->list->H264_codec.misc_params.min_slice_size);
+      g_print("  slice_enc_params: %x", msg->video_formats->list->H264_codec.misc_params.slice_enc_params);
+      g_print("  frame_rate_control_support: %x", msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support);
+      if (msg->video_formats->list->H264_codec.max_hres) {
+        g_print("  Max Width: %04d", msg->video_formats->list->H264_codec.max_hres);
+      }
+      if (msg->video_formats->list->H264_codec.max_vres) {
+        g_print("  Max Height: %04d", msg->video_formats->list->H264_codec.max_vres);
+      }
+    }
+  }
+
+  if (msg->video_3d_formats) {
+    g_print("wfd_3d_formats");
+  }
+
+  if (msg->content_protection) {
+    g_print(GST_STRING_WFD_CONTENT_PROTECTION);
+  }
+
+  if (msg->display_edid) {
+    g_print(GST_STRING_WFD_DISPLAY_EDID);
+  }
+
+  if (msg->coupled_sink) {
+    g_print(GST_STRING_WFD_COUPLED_SINK);
+  }
+
+  if (msg->trigger_method) {
+    g_print("  Trigger type: %s", msg->trigger_method->wfd_trigger_method);
+  }
+
+  if (msg->presentation_url) {
+    g_print(GST_STRING_WFD_PRESENTATION_URL);
+  }
+
+  if (msg->client_rtp_ports) {
+    g_print(" Client RTP Ports : ");
+    if (msg->client_rtp_ports->profile) {
+      g_print("%s", msg->client_rtp_ports->profile);
+      g_print("  %d", msg->client_rtp_ports->rtp_port0);
+      g_print("  %d", msg->client_rtp_ports->rtp_port1);
+      g_print("  %s", msg->client_rtp_ports->mode);
+    }
+  }
+
+  if (msg->route) {
+    g_print(GST_STRING_WFD_ROUTE);
+  }
+
+  if (msg->I2C) {
+    g_print(GST_STRING_WFD_I2C);
+  }
+
+  if (msg->av_format_change_timing) {
+    g_print(GST_STRING_WFD_AV_FORMAT_CHANGE_TIMING);
+  }
+
+  if (msg->preferred_display_mode) {
+    g_print(GST_STRING_WFD_PREFERRED_DISPLAY_MODE);
+  }
+
+  if (msg->standby_resume_capability) {
+    g_print(GST_STRING_WFD_STANDBY_RESUME_CAPABILITY);
+  }
+
+  if (msg->standby) {
+    g_print(GST_STRING_WFD_STANDBY);
+  }
+
+  if (msg->connector_type) {
+    g_print(GST_STRING_WFD_CONNECTOR_TYPE);
+  }
+
+  if (msg->idr_request) {
+    g_print(GST_STRING_WFD_IDR_REQUEST);
+  }
+
+  g_print("===============================================");
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_supported_audio_format(GstWFDMessage *msg, GstWFDAudioFormats aCodec, guint aFreq, guint aChanels,
+                                               guint aBitwidth, guint32 aLatency)
+{
+  guint temp = aCodec;
+  guint i = 0;
+  guint pcm = 0, aac = 0, ac3 = 0;
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->audio_codecs)
+    msg->audio_codecs = g_new0(GstWFDAudioCodeclist, 1);
+
+  if (aCodec != GST_WFD_AUDIO_UNKNOWN) {
+    while (temp) {
+      msg->audio_codecs->count++;
+      temp >>= 1;
+    }
+    msg->audio_codecs->list = g_new0(GstWFDAudioCodec, msg->audio_codecs->count);
+    for (; i < msg->audio_codecs->count; i++) {
+      if ((aCodec & GST_WFD_AUDIO_LPCM) && (!pcm)) {
+        msg->audio_codecs->list[i].audio_format = g_strdup(GST_STRING_WFD_LPCM);
+        msg->audio_codecs->list[i].modes = aFreq;
+        msg->audio_codecs->list[i].latency = aLatency;
+        pcm = 1;
+      } else if ((aCodec & GST_WFD_AUDIO_AAC) && (!aac)) {
+        msg->audio_codecs->list[i].audio_format = g_strdup(GST_STRING_WFD_AAC);
+        msg->audio_codecs->list[i].modes = aChanels;
+        msg->audio_codecs->list[i].latency = aLatency;
+        aac = 1;
+      } else if ((aCodec & GST_WFD_AUDIO_AC3) && (!ac3)) {
+        msg->audio_codecs->list[i].audio_format = g_strdup(GST_STRING_WFD_AC3);
+        msg->audio_codecs->list[i].modes = aChanels;
+        msg->audio_codecs->list[i].latency = aLatency;
+        ac3 = 1;
+      }
+    }
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_prefered_audio_format(GstWFDMessage *msg, GstWFDAudioFormats aCodec, GstWFDAudioFreq aFreq, GstWFDAudioChannels aChanels,
+                                              guint aBitwidth, guint32 aLatency)
+{
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->audio_codecs)
+    msg->audio_codecs = g_new0(GstWFDAudioCodeclist, 1);
+
+  msg->audio_codecs->list = g_new0(GstWFDAudioCodec, 1);
+  msg->audio_codecs->count = 1;
+  if (aCodec == GST_WFD_AUDIO_LPCM) {
+    msg->audio_codecs->list->audio_format = g_strdup(GST_STRING_WFD_LPCM);
+    msg->audio_codecs->list->modes = aFreq;
+    msg->audio_codecs->list->latency = aLatency;
+  } else if (aCodec == GST_WFD_AUDIO_AAC) {
+    msg->audio_codecs->list->audio_format = g_strdup(GST_STRING_WFD_AAC);
+    msg->audio_codecs->list->modes = aChanels;
+    msg->audio_codecs->list->latency = aLatency;
+  } else if (aCodec == GST_WFD_AUDIO_AC3) {
+    msg->audio_codecs->list->audio_format = g_strdup(GST_STRING_WFD_AC3);
+    msg->audio_codecs->list->modes = aChanels;
+    msg->audio_codecs->list->latency = aLatency;
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_supported_audio_format(GstWFDMessage *msg, guint *aCodec, guint *aFreq, guint *aChanels,
+                                               guint *aBitwidth, guint32 *aLatency)
+{
+  guint i = 0;
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(msg->audio_codecs != NULL, GST_WFD_EINVAL);
+
+  for (; i < msg->audio_codecs->count; i++) {
+    if (!g_strcmp0(msg->audio_codecs->list[i].audio_format, GST_STRING_WFD_LPCM)) {
+      *aCodec |= GST_WFD_AUDIO_LPCM;
+      *aFreq |= msg->audio_codecs->list[i].modes;
+      *aChanels |= GST_WFD_CHANNEL_2;
+      *aBitwidth = 16;
+      *aLatency = msg->audio_codecs->list[i].latency;
+    } else if (!g_strcmp0(msg->audio_codecs->list[i].audio_format, GST_STRING_WFD_AAC)) {
+      *aCodec |= GST_WFD_AUDIO_AAC;
+      *aFreq |= GST_WFD_FREQ_48000;
+      *aChanels |= msg->audio_codecs->list[i].modes;
+      *aBitwidth = 16;
+      *aLatency = msg->audio_codecs->list[i].latency;
+    } else if (!g_strcmp0(msg->audio_codecs->list[i].audio_format, GST_STRING_WFD_AC3)) {
+      *aCodec |= GST_WFD_AUDIO_AC3;
+      *aFreq |= GST_WFD_FREQ_48000;
+      *aChanels |= msg->audio_codecs->list[i].modes;
+      *aBitwidth = 16;
+      *aLatency = msg->audio_codecs->list[i].latency;
+    }
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_prefered_audio_format(GstWFDMessage *msg, GstWFDAudioFormats *aCodec, GstWFDAudioFreq *aFreq, GstWFDAudioChannels *aChanels,
+                                              guint *aBitwidth, guint32 *aLatency)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!g_strcmp0(msg->audio_codecs->list->audio_format, GST_STRING_WFD_LPCM)) {
+    *aCodec = GST_WFD_AUDIO_LPCM;
+    *aFreq = msg->audio_codecs->list->modes;
+    *aChanels = GST_WFD_CHANNEL_2;
+    *aBitwidth = 16;
+    *aLatency = msg->audio_codecs->list->latency;
+  } else if (!g_strcmp0(msg->audio_codecs->list->audio_format, GST_STRING_WFD_AAC)) {
+    *aCodec = GST_WFD_AUDIO_AAC;
+    *aFreq = GST_WFD_FREQ_48000;
+    *aChanels = msg->audio_codecs->list->modes;
+    *aBitwidth = 16;
+    *aLatency = msg->audio_codecs->list->latency;
+  } else if (!g_strcmp0(msg->audio_codecs->list->audio_format, GST_STRING_WFD_AC3)) {
+    *aCodec = GST_WFD_AUDIO_AC3;
+    *aFreq = GST_WFD_FREQ_48000;
+    *aChanels = msg->audio_codecs->list->modes;
+    *aBitwidth = 16;
+    *aLatency = msg->audio_codecs->list->latency;
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_supported_video_format(GstWFDMessage *msg, GstWFDVideoCodecs vCodec,
+                                               GstWFDVideoNativeResolution vNative, guint64 vNativeResolution,
+                                               guint64 vCEAResolution, guint64 vVESAResolution, guint64 vHHResolution,
+                                               guint vProfile, guint vLevel, guint32 vLatency, guint32 vMaxHeight,
+                                               guint32 vMaxWidth, guint32 min_slice_size, guint32 slice_enc_params, guint frame_rate_control,
+                                               guint preferred_display_mode)
+{
+  guint nativeindex = 0;
+  guint64 temp = vNativeResolution;
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->video_formats)
+    msg->video_formats = g_new0(GstWFDVideoCodeclist, 1);
+
+  if (vCodec != GST_WFD_VIDEO_UNKNOWN) {
+    msg->video_formats->list = g_new0(GstWFDVideoCodec, 1);
+    while (temp) {
+      nativeindex++;
+      temp >>= 1;
+    }
+
+    msg->video_formats->list->native = nativeindex - 1;
+    msg->video_formats->list->native <<= 3;
+
+    if (vNative == GST_WFD_VIDEO_VESA_RESOLUTION)
+      msg->video_formats->list->native |= 1;
+    else if (vNative == GST_WFD_VIDEO_HH_RESOLUTION)
+      msg->video_formats->list->native |= 2;
+
+    msg->video_formats->list->preferred_display_mode_supported = preferred_display_mode;
+    msg->video_formats->list->H264_codec.profile = vProfile;
+    msg->video_formats->list->H264_codec.level = vLevel;
+    msg->video_formats->list->H264_codec.max_hres = vMaxWidth;
+    msg->video_formats->list->H264_codec.max_vres = vMaxHeight;
+    msg->video_formats->list->H264_codec.misc_params.CEA_Support = vCEAResolution;
+    msg->video_formats->list->H264_codec.misc_params.VESA_Support = vVESAResolution;
+    msg->video_formats->list->H264_codec.misc_params.HH_Support = vHHResolution;
+    msg->video_formats->list->H264_codec.misc_params.latency = vLatency;
+    msg->video_formats->list->H264_codec.misc_params.min_slice_size = min_slice_size;
+    msg->video_formats->list->H264_codec.misc_params.slice_enc_params = slice_enc_params;
+    msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support = frame_rate_control;
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_prefered_video_format(GstWFDMessage *msg, GstWFDVideoCodecs vCodec,
+                                              GstWFDVideoNativeResolution vNative, guint64 vNativeResolution,
+                                              GstWFDVideoCEAResolution vCEAResolution, GstWFDVideoVESAResolution vVESAResolution,
+                                              GstWFDVideoHHResolution vHHResolution,  GstWFDVideoH264Profile vProfile,
+                                              GstWFDVideoH264Level vLevel, guint32 vLatency, guint32 vMaxHeight,
+                                              guint32 vMaxWidth, guint32 min_slice_size, guint32 slice_enc_params, guint frame_rate_control)
+{
+  guint nativeindex = 0;
+  guint64 temp = vNativeResolution;
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->video_formats)
+    msg->video_formats = g_new0(GstWFDVideoCodeclist, 1);
+  msg->video_formats->list = g_new0(GstWFDVideoCodec, 1);
+
+  while (temp) {
+    nativeindex++;
+    temp >>= 1;
+  }
+
+  if (nativeindex) msg->video_formats->list->native = nativeindex - 1;
+  msg->video_formats->list->native <<= 3;
+
+  if (vNative == GST_WFD_VIDEO_VESA_RESOLUTION)
+    msg->video_formats->list->native |= 1;
+  else if (vNative == GST_WFD_VIDEO_HH_RESOLUTION)
+    msg->video_formats->list->native |= 2;
+
+  msg->video_formats->list->preferred_display_mode_supported = GST_WFD_PREFERRED_DISPLAY_MODE_NOT_SUPPORTED;
+  msg->video_formats->list->H264_codec.profile = vProfile;
+  msg->video_formats->list->H264_codec.level = vLevel;
+  msg->video_formats->list->H264_codec.max_hres = vMaxWidth;
+  msg->video_formats->list->H264_codec.max_vres = vMaxHeight;
+  msg->video_formats->list->H264_codec.misc_params.CEA_Support = vCEAResolution;
+  msg->video_formats->list->H264_codec.misc_params.VESA_Support = vVESAResolution;
+  msg->video_formats->list->H264_codec.misc_params.HH_Support = vHHResolution;
+  msg->video_formats->list->H264_codec.misc_params.latency = vLatency;
+  msg->video_formats->list->H264_codec.misc_params.min_slice_size = min_slice_size;
+  msg->video_formats->list->H264_codec.misc_params.slice_enc_params = slice_enc_params;
+  msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support = frame_rate_control;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_supported_video_format(GstWFDMessage *msg, GstWFDVideoCodecs *vCodec,
+                                               GstWFDVideoNativeResolution *vNative, guint64 *vNativeResolution,
+                                               guint64 *vCEAResolution, guint64 *vVESAResolution, guint64 *vHHResolution,
+                                               guint *vProfile, guint *vLevel, guint32 *vLatency, guint32 *vMaxHeight,
+                                               guint32 *vMaxWidth, guint32 *min_slice_size, guint32 *slice_enc_params, guint *frame_rate_control)
+{
+  guint nativeindex = 0;
+
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(msg->video_formats != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(msg->video_formats->list != NULL, GST_WFD_EINVAL);
+
+  *vCodec = GST_WFD_VIDEO_H264;
+  *vNative = msg->video_formats->list->native & 0x7;
+  nativeindex = msg->video_formats->list->native >> 3;
+  *vNativeResolution = (guint64)1 << nativeindex;
+  *vProfile = msg->video_formats->list->H264_codec.profile;
+  *vLevel = msg->video_formats->list->H264_codec.level;
+  *vMaxWidth = msg->video_formats->list->H264_codec.max_hres;
+  *vMaxHeight = msg->video_formats->list->H264_codec.max_vres;
+  *vCEAResolution = msg->video_formats->list->H264_codec.misc_params.CEA_Support;
+  *vVESAResolution = msg->video_formats->list->H264_codec.misc_params.VESA_Support;
+  *vHHResolution = msg->video_formats->list->H264_codec.misc_params.HH_Support;
+  *vLatency = msg->video_formats->list->H264_codec.misc_params.latency;
+  *min_slice_size = msg->video_formats->list->H264_codec.misc_params.min_slice_size;
+  *slice_enc_params = msg->video_formats->list->H264_codec.misc_params.slice_enc_params;
+  *frame_rate_control = msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_prefered_video_format(GstWFDMessage *msg, GstWFDVideoCodecs *vCodec,
+                                              GstWFDVideoNativeResolution *vNative, guint64 *vNativeResolution,
+                                              GstWFDVideoCEAResolution *vCEAResolution, GstWFDVideoVESAResolution *vVESAResolution,
+                                              GstWFDVideoHHResolution *vHHResolution,  GstWFDVideoH264Profile *vProfile,
+                                              GstWFDVideoH264Level *vLevel, guint32 *vLatency, guint32 *vMaxHeight,
+                                              guint32 *vMaxWidth, guint32 *min_slice_size, guint32 *slice_enc_params, guint *frame_rate_control)
+{
+  guint nativeindex = 0;
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(msg->video_formats != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(msg->video_formats->list != NULL, GST_WFD_EINVAL);
+
+  *vCodec = GST_WFD_VIDEO_H264;
+  *vNative = msg->video_formats->list->native & 0x7;
+  nativeindex = msg->video_formats->list->native >> 3;
+  *vNativeResolution = (guint64)1 << nativeindex;
+  *vProfile = msg->video_formats->list->H264_codec.profile;
+  *vLevel = msg->video_formats->list->H264_codec.level;
+  *vMaxWidth = msg->video_formats->list->H264_codec.max_hres;
+  *vMaxHeight = msg->video_formats->list->H264_codec.max_vres;
+  *vCEAResolution = msg->video_formats->list->H264_codec.misc_params.CEA_Support;
+  *vVESAResolution = msg->video_formats->list->H264_codec.misc_params.VESA_Support;
+  *vHHResolution = msg->video_formats->list->H264_codec.misc_params.HH_Support;
+  *vLatency = msg->video_formats->list->H264_codec.misc_params.latency;
+  *min_slice_size = msg->video_formats->list->H264_codec.misc_params.min_slice_size;
+  *slice_enc_params = msg->video_formats->list->H264_codec.misc_params.slice_enc_params;
+  *frame_rate_control = msg->video_formats->list->H264_codec.misc_params.frame_rate_control_support;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_contentprotection_type(GstWFDMessage *msg, GstWFDHDCPProtection hdcpversion, guint32 TCPPort)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->content_protection) msg->content_protection = g_new0(GstWFDContentProtection, 1);
+  if (hdcpversion == GST_WFD_HDCP_NONE) return GST_WFD_OK;
+  msg->content_protection->hdcp2_spec = g_new0(GstWFDHdcp2Spec, 1);
+  if (hdcpversion == GST_WFD_HDCP_2_0) msg->content_protection->hdcp2_spec->hdcpversion = g_strdup(GST_STRING_WFD_HDCP2_0);
+  else if (hdcpversion == GST_WFD_HDCP_2_1) msg->content_protection->hdcp2_spec->hdcpversion = g_strdup(GST_STRING_WFD_HDCP2_1);
+  char str[11] = {0, };
+  snprintf(str, 11, "port=%d", TCPPort);
+  msg->content_protection->hdcp2_spec->TCPPort = g_strdup(str);
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_contentprotection_type(GstWFDMessage *msg, GstWFDHDCPProtection *hdcpversion, guint32 *TCPPort)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->content_protection && msg->content_protection->hdcp2_spec) {
+    char *result = NULL;
+    char *ptr = NULL;
+    if (!g_strcmp0(msg->content_protection->hdcp2_spec->hdcpversion, GST_STRING_WFD_NONE)) {
+      g_print("HDCP none");
+      *hdcpversion = GST_WFD_HDCP_NONE;
+      *TCPPort = 0;
+      return GST_WFD_OK;
+    }
+    if (!g_strcmp0(msg->content_protection->hdcp2_spec->hdcpversion, GST_STRING_WFD_HDCP2_0)) *hdcpversion = GST_WFD_HDCP_2_0;
+    else if (!g_strcmp0(msg->content_protection->hdcp2_spec->hdcpversion, GST_STRING_WFD_HDCP2_1)) *hdcpversion = GST_WFD_HDCP_2_1;
+    else {
+      g_print("Unknown protection type");
+      *hdcpversion = GST_WFD_HDCP_NONE;
+      *TCPPort = 0;
+      return GST_WFD_OK;
+    }
+
+    result = strtok_r(msg->content_protection->hdcp2_spec->TCPPort, GST_STRING_WFD_EQUALS, &ptr);
+    while (result != NULL) {
+      result = strtok_r(NULL, GST_STRING_WFD_EQUALS, &ptr);
+      *TCPPort = atoi(result);
+      break;
+    }
+  } else *hdcpversion = GST_WFD_HDCP_NONE;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_display_EDID(GstWFDMessage *msg, gboolean edid_supported, guint32 edid_blockcount, gchar *edid_playload)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->display_edid) msg->display_edid = g_new0(GstWFDDisplayEdid, 1);
+  msg->display_edid->edid_supported = edid_supported;
+  if (!edid_supported) return GST_WFD_OK;
+  if (edid_blockcount > 0 && edid_blockcount <= EDID_BLOCK_COUNT_MAX_SIZE) {
+    msg->display_edid->edid_block_count = edid_blockcount;
+    msg->display_edid->edid_payload = g_malloc(EDID_BLOCK_SIZE * edid_blockcount);
+    if (!msg->display_edid->edid_payload)
+      memcpy(msg->display_edid->edid_payload, edid_playload, EDID_BLOCK_SIZE * edid_blockcount);
+    else
+      msg->display_edid->edid_supported = FALSE;
+  } else
+    msg->display_edid->edid_supported = FALSE;
+
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_display_EDID(GstWFDMessage *msg, gboolean *edid_supported, guint32 *edid_blockcount, gchar **edid_playload)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(edid_supported != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(edid_blockcount != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(edid_playload != NULL, GST_WFD_EINVAL);
+
+  if (msg->display_edid) {
+    if (msg->display_edid->edid_supported) {
+      *edid_blockcount = msg->display_edid->edid_block_count;
+      if (msg->display_edid->edid_block_count > 0) {
+        char *temp;
+        temp = g_malloc0(EDID_BLOCK_SIZE * msg->display_edid->edid_block_count);
+        if (temp) {
+          memcpy(temp, msg->display_edid->edid_payload, EDID_BLOCK_SIZE * msg->display_edid->edid_block_count);
+          *edid_playload = temp;
+          *edid_supported = TRUE;
+        } else {
+          *edid_supported = FALSE;
+        }
+      } else *edid_supported = FALSE;
+    }
+  } else *edid_supported = FALSE;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_coupled_sink(GstWFDMessage *msg, GstWFDCoupledSinkStatus status, gchar *sink_address)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->coupled_sink) msg->coupled_sink = g_new0(GstWFDCoupledSink, 1);
+  if (status == GST_WFD_SINK_UNKNOWN) return GST_WFD_OK;
+  msg->coupled_sink->coupled_sink_cap = g_new0(GstWFDCoupledSinkCap, 1);
+  msg->coupled_sink->coupled_sink_cap->status = status;
+  msg->coupled_sink->coupled_sink_cap->sink_address = g_strdup(sink_address);
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_coupled_sink(GstWFDMessage *msg, GstWFDCoupledSinkStatus *status, gchar **sink_address)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->coupled_sink && msg->coupled_sink->coupled_sink_cap) {
+    *status = msg->coupled_sink->coupled_sink_cap->status;
+    *sink_address = g_strdup(msg->coupled_sink->coupled_sink_cap->sink_address);
+  } else *status = GST_WFD_SINK_UNKNOWN;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_trigger_type(GstWFDMessage *msg, GstWFDTrigger trigger)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->trigger_method)
+    msg->trigger_method = g_new0(GstWFDTriggerMethod, 1);
+  if (trigger == GST_WFD_TRIGGER_SETUP)
+    msg->trigger_method->wfd_trigger_method = g_strdup(GST_STRING_WFD_SETUP);
+  else if (trigger == GST_WFD_TRIGGER_PAUSE)
+    msg->trigger_method->wfd_trigger_method = g_strdup(GST_STRING_WFD_PAUSE);
+  else if (trigger == GST_WFD_TRIGGER_TEARDOWN)
+    msg->trigger_method->wfd_trigger_method = g_strdup(GST_STRING_WFD_TEARDOWN);
+  else if (trigger == GST_WFD_TRIGGER_PLAY)
+    msg->trigger_method->wfd_trigger_method = g_strdup(GST_STRING_WFD_PLAY);
+  else
+    return GST_WFD_EINVAL;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_trigger_type(GstWFDMessage *msg, GstWFDTrigger *trigger)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!g_strcmp0(msg->trigger_method->wfd_trigger_method, GST_STRING_WFD_SETUP))
+    *trigger = GST_WFD_TRIGGER_SETUP;
+  else if (!g_strcmp0(msg->trigger_method->wfd_trigger_method, GST_STRING_WFD_PAUSE))
+    *trigger = GST_WFD_TRIGGER_PAUSE;
+  else if (!g_strcmp0(msg->trigger_method->wfd_trigger_method, GST_STRING_WFD_TEARDOWN))
+    *trigger = GST_WFD_TRIGGER_TEARDOWN;
+  else if (!g_strcmp0(msg->trigger_method->wfd_trigger_method, GST_STRING_WFD_PLAY))
+    *trigger = GST_WFD_TRIGGER_PLAY;
+  else {
+    *trigger = GST_WFD_TRIGGER_UNKNOWN;
+    return GST_WFD_EINVAL;
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_presentation_url(GstWFDMessage *msg, gchar *wfd_url0, gchar *wfd_url1)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->presentation_url) msg->presentation_url = g_new0(GstWFDPresentationUrl, 1);
+  if (wfd_url0) msg->presentation_url->wfd_url0 = g_strdup(wfd_url0);
+  if (wfd_url1) msg->presentation_url->wfd_url1 = g_strdup(wfd_url1);
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_presentation_url(GstWFDMessage *msg, gchar **wfd_url0, gchar **wfd_url1)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->presentation_url) {
+    *wfd_url0 = g_strdup(msg->presentation_url->wfd_url0);
+    *wfd_url1 = g_strdup(msg->presentation_url->wfd_url1);
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_prefered_RTP_ports(GstWFDMessage *msg, GstWFDRTSPTransMode trans, GstWFDRTSPProfile profile,
+                                           GstWFDRTSPLowerTrans lowertrans, guint32 rtp_port0, guint32 rtp_port1)
+{
+  GString *lines;
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+
+  if (!msg->client_rtp_ports)
+    msg->client_rtp_ports = g_new0(GstWFDClientRtpPorts, 1);
+
+  if (trans != GST_WFD_RTSP_TRANS_UNKNOWN) {
+    lines = g_string_new("");
+    if (trans == GST_WFD_RTSP_TRANS_RTP)  g_string_append_printf(lines, GST_STRING_WFD_RTP);
+    else if (trans == GST_WFD_RTSP_TRANS_RDT) g_string_append_printf(lines, GST_STRING_WFD_RDT);
+
+    if (profile != GST_WFD_RTSP_PROFILE_UNKNOWN) g_string_append_printf(lines, GST_STRING_WFD_SLASH);
+
+    if (profile == GST_WFD_RTSP_PROFILE_AVP) g_string_append_printf(lines, GST_STRING_WFD_AVP);
+    else if (profile == GST_WFD_RTSP_PROFILE_SAVP) g_string_append_printf(lines, GST_STRING_WFD_SAVP);
+
+    if (lowertrans != GST_WFD_RTSP_LOWER_TRANS_UNKNOWN) g_string_append_printf(lines, GST_STRING_WFD_SLASH);
+
+    if (lowertrans == GST_WFD_RTSP_LOWER_TRANS_UDP) {
+      g_string_append_printf(lines, GST_STRING_WFD_UDP);
+      g_string_append_printf(lines, GST_STRING_WFD_SEMI_COLON);
+      g_string_append_printf(lines, GST_STRING_WFD_UNICAST);
+    } else if (lowertrans == GST_WFD_RTSP_LOWER_TRANS_UDP_MCAST) {
+      g_string_append_printf(lines, GST_STRING_WFD_UDP);
+      g_string_append_printf(lines, GST_STRING_WFD_SEMI_COLON);
+      g_string_append_printf(lines, GST_STRING_WFD_MULTICAST);
+    } else if (lowertrans == GST_WFD_RTSP_LOWER_TRANS_TCP) {
+      g_string_append_printf(lines, GST_STRING_WFD_TCP);
+      g_string_append_printf(lines, GST_STRING_WFD_SEMI_COLON);
+      g_string_append_printf(lines, GST_STRING_WFD_UNICAST);
+    } else if (lowertrans == GST_WFD_RTSP_LOWER_TRANS_HTTP) {
+      g_string_append_printf(lines, GST_STRING_WFD_TCP_HTTP);
+    }
+
+    msg->client_rtp_ports->profile = g_string_free(lines, FALSE);
+    msg->client_rtp_ports->rtp_port0 = rtp_port0;
+    msg->client_rtp_ports->rtp_port1 = rtp_port1;
+    msg->client_rtp_ports->mode = g_strdup("mode=play");
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_prefered_RTP_ports(GstWFDMessage *msg, GstWFDRTSPTransMode *trans, GstWFDRTSPProfile *profile,
+                                           GstWFDRTSPLowerTrans *lowertrans, guint32 *rtp_port0, guint32 *rtp_port1)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  g_return_val_if_fail(msg->client_rtp_ports != NULL, GST_WFD_EINVAL);
+
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_RTP)) *trans = GST_WFD_RTSP_TRANS_RTP;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_RDT)) *trans = GST_WFD_RTSP_TRANS_RDT;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_AVP)) *profile = GST_WFD_RTSP_PROFILE_AVP;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_SAVP)) *profile = GST_WFD_RTSP_PROFILE_SAVP;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_UDP) &&
+    g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_UNICAST)) *lowertrans = GST_WFD_RTSP_LOWER_TRANS_UDP;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_UDP) &&
+    g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_MULTICAST)) *lowertrans = GST_WFD_RTSP_LOWER_TRANS_UDP_MCAST;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_TCP) &&
+    g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_UNICAST)) *lowertrans = GST_WFD_RTSP_LOWER_TRANS_TCP;
+  if (g_strrstr(msg->client_rtp_ports->profile, GST_STRING_WFD_TCP_HTTP)) *lowertrans = GST_WFD_RTSP_LOWER_TRANS_HTTP;
+
+  *rtp_port0 = msg->client_rtp_ports->rtp_port0;
+  *rtp_port1 = msg->client_rtp_ports->rtp_port1;
+
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_audio_sink_type(GstWFDMessage *msg, GstWFDSinkType sinktype)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->route) msg->route = g_new0(GstWFDRoute, 1);
+  if (sinktype == GST_WFD_PRIMARY_SINK) msg->route->destination = g_strdup(GST_STRING_WFD_PRIMARY);
+  else if (sinktype == GST_WFD_SECONDARY_SINK) msg->route->destination = g_strdup(GST_STRING_WFD_SECONDARY);
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_audio_sink_type(GstWFDMessage *msg, GstWFDSinkType *sinktype)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->route) {
+    if (!g_strcmp0(msg->route->destination, GST_STRING_WFD_PRIMARY)) *sinktype = GST_WFD_PRIMARY_SINK;
+    else if (!g_strcmp0(msg->route->destination, GST_STRING_WFD_SECONDARY)) *sinktype = GST_WFD_SECONDARY_SINK;
+  }
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_I2C_port(GstWFDMessage *msg, gboolean i2csupport, guint32 i2cport)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->I2C) msg->I2C = g_new0(GstWFDI2C, 1);
+  msg->I2C->I2CPresent = i2csupport;
+  msg->I2C->I2C_port = i2cport;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_I2C_port(GstWFDMessage *msg, gboolean *i2csupport, guint32 *i2cport)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->I2C && msg->I2C->I2CPresent) {
+    *i2csupport = msg->I2C->I2CPresent;
+    *i2cport = msg->I2C->I2C_port;
+  } else *i2csupport = FALSE;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_av_format_change_timing(GstWFDMessage *msg, guint64 PTS, guint64 DTS)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->av_format_change_timing) msg->av_format_change_timing = g_new0(GstWFDAVFormatChangeTiming, 1);
+  msg->av_format_change_timing->PTS = PTS;
+  msg->av_format_change_timing->DTS = DTS;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_av_format_change_timing(GstWFDMessage *msg, guint64 *PTS, guint64 *DTS)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->av_format_change_timing) {
+    *PTS = msg->av_format_change_timing->PTS;
+    *DTS = msg->av_format_change_timing->DTS;
+  }
+  return GST_WFD_OK;
+}
+
+#ifdef STANDBY_RESUME_CAPABILITY
+GstWFDResult gst_wfd_message_set_standby_resume_capability(GstWFDMessage *msg, gboolean supported)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->standby_resume_capability) msg->standby_resume_capability = g_new0(GstWFDStandbyResumeCapability, 1);
+  msg->standby_resume_capability->standby_resume_cap = supported;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_standby_resume_capability(GstWFDMessage *msg, gboolean *supported)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->standby_resume_capability) *supported = msg->standby_resume_capability->standby_resume_cap;
+  return GST_WFD_OK;
+}
+#endif
+GstWFDResult gst_wfd_message_set_standby(GstWFDMessage *msg, gboolean standby_enable)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->standby) msg->standby = g_new0(GstWFDStandby, 1);
+  msg->standby->wfd_standby = standby_enable;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_standby(GstWFDMessage *msg, gboolean *standby_enable)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->standby) *standby_enable = msg->standby->wfd_standby;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_connector_type(GstWFDMessage *msg, GstWFDConnector connector)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->connector_type) msg->connector_type = g_new0(GstWFDConnectorType, 1);
+  msg->connector_type->connector_type = connector;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_get_connector_type(GstWFDMessage *msg, GstWFDConnector *connector)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (msg->connector_type) *connector = msg->connector_type->connector_type;
+  return GST_WFD_OK;
+}
+
+GstWFDResult gst_wfd_message_set_idr_request(GstWFDMessage *msg)
+{
+  g_return_val_if_fail(msg != NULL, GST_WFD_EINVAL);
+  if (!msg->idr_request) msg->idr_request = g_new0(GstWFDIdrRequest, 1);
+  msg->idr_request->idr_request = TRUE;
+  return GST_WFD_OK;
+}
diff --git a/wfdmanager/wfdbase/gstwfdsinkmessage.h b/wfdmanager/wfdbase/gstwfdsinkmessage.h
new file mode 100755 (executable)
index 0000000..221ed03
--- /dev/null
@@ -0,0 +1,577 @@
+/*
+ * wfdrtsp message
+ *
+ * Copyright (c) 2011 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Taewan Kim<taewan79.kim@samsung.com>, Yejin Cho<cho.yejin@samsung.com>, Sangkyu Park<sk1122.park@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library (COPYING); if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+#ifndef __GST_WFD_SINK_MESSAGE_H__
+#define __GST_WFD_SINK_MESSAGE_H__
+
+#include <glib.h>
+
+G_BEGIN_DECLS
+
+#define GST_STRING_WFD_AUDIO_CODECS               "wfd_audio_codecs"
+#define GST_STRING_WFD_VIDEO_FORMATS              "wfd_video_formats"
+#define GST_STRING_WFD_3D_VIDEO_FORMATS           "wfd_3d_video_formats"
+#define GST_STRING_WFD_CONTENT_PROTECTION         "wfd_content_protection"
+#define GST_STRING_WFD_DISPLAY_EDID               "wfd_display_edid"
+#define GST_STRING_WFD_COUPLED_SINK               "wfd_coupled_sink"
+#define GST_STRING_WFD_TRIGGER_METHOD             "wfd_trigger_method"
+#define GST_STRING_WFD_PRESENTATION_URL           "wfd_presentation_URL"
+#define GST_STRING_WFD_CLIENT_RTP_PORTS           "wfd_client_rtp_ports"
+#define GST_STRING_WFD_ROUTE                      "wfd_route"
+#define GST_STRING_WFD_I2C                        "wfd_I2C"
+#define GST_STRING_WFD_AV_FORMAT_CHANGE_TIMING    "wfd_av_format_change_timing"
+#define GST_STRING_WFD_PREFERRED_DISPLAY_MODE     "wfd_preferred_display_mode"
+#define GST_STRING_WFD_STANDBY_RESUME_CAPABILITY  "wfd_standby_resume_capability"
+#define GST_STRING_WFD_STANDBY                    "wfd_standby"
+#define GST_STRING_WFD_CONNECTOR_TYPE             "wfd_connector_type"
+#define GST_STRING_WFD_IDR_REQUEST                "wfd_idr_request"
+#define GST_STRING_WFD_NONE                       "none"
+#define GST_STRING_WFD_ENABLE                     "enable"
+#define GST_STRING_WFD_DISABLE                    "disable"
+#define GST_STRING_WFD_CRLF                       "\r\n"
+#define GST_STRING_WFD_SPACE                      " "
+#define GST_STRING_WFD_INPUT_CATEGORY_LIST        "input_category_list"
+#define GST_STRING_WFD_GENERIC                    "GENERIC"
+#define GST_STRING_WFD_HIDC                       "HIDC"
+#define GST_STRING_WFD_GENERIC_CAP_LIST           "generic_cap_list"
+#define GST_STRING_WFD_KEYBOARD                   "Keyboard"
+#define GST_STRING_WFD_MOUSE                      "Mouse"
+#define GST_STRING_WFD_SINGLE_TOUCH               "SingleTouch"
+#define GST_STRING_WFD_MULTI_TOUCH                "MultiTouch"
+#define GST_STRING_WFD_JOYSTICK                   "Joystick"
+#define GST_STRING_WFD_CAMERA                     "Camera"
+#define GST_STRING_WFD_GESTURE                    "Gesture"
+#define GST_STRING_WFD_REMOTE_CONTROL             "RemoteControl"
+#define GST_STRING_WFD_HIDC_CAP_LIST              "hidc_cap_list"
+#define GST_STRING_WFD_INFRARED                   "Infrared"
+#define GST_STRING_WFD_USB                        "USB"
+#define GST_STRING_WFD_BT                         "BT"
+#define GST_STRING_WFD_ZIGBEE                     "Zigbee"
+#define GST_STRING_WFD_WIFI                       "Wi-Fi"
+#define GST_STRING_WFD_NO_SP                      "No-SP"
+#define GST_STRING_WFD_PORT                       "port"
+#define GST_STRING_WFD_SUPPORTED                  "supported"
+#define GST_STRING_WFD_LPCM                       "LPCM"
+#define GST_STRING_WFD_AAC                        "AAC"
+#define GST_STRING_WFD_AC3                        "AC3"
+#define GST_STRING_WFD_HDCP2_0                    "HDCP2.0"
+#define GST_STRING_WFD_HDCP2_1                    "HDCP2.1"
+#define GST_STRING_WFD_SETUP                      "SETUP"
+#define GST_STRING_WFD_PAUSE                      "PAUSE"
+#define GST_STRING_WFD_TEARDOWN                   "TEARDOWN"
+#define GST_STRING_WFD_PLAY                       "PLAY"
+#define GST_STRING_WFD_RTP                        "RTP"
+#define GST_STRING_WFD_RDT                        "RDT"
+#define GST_STRING_WFD_AVP                        "AVP"
+#define GST_STRING_WFD_SAVP                       "SAVP"
+#define GST_STRING_WFD_UDP                        "UDP"
+#define GST_STRING_WFD_TCP                        "TCP"
+#define GST_STRING_WFD_UNICAST                    "unicast"
+#define GST_STRING_WFD_MULTICAST                  "multicast"
+#define GST_STRING_WFD_TCP_HTTP                   "HTTP"
+#define GST_STRING_WFD_PRIMARY                    "primary"
+#define GST_STRING_WFD_SECONDARY                  "secondary"
+#define GST_STRING_WFD_COMMA                      ","
+#define GST_STRING_WFD_EQUALS                     "="
+#define GST_STRING_WFD_COLON                      ":"
+#define GST_STRING_WFD_SEMI_COLON                 ";"
+#define GST_STRING_WFD_SLASH                      "/"
+
+/**
+ * GstWFDResult:
+ * @GST_WFD_OK: A successful return value
+ * @GST_WFD_EINVAL: a function was given invalid parameters
+ *
+ * Return values for the WFD functions.
+ */
+typedef enum {
+  GST_WFD_OK     = 0,
+  GST_WFD_EINVAL = -1,
+  GST_WFD_NOT_IMPLEMENTED = -2,
+  GST_WFD_NOT_SUPPORTED = -3
+} GstWFDResult;
+
+typedef enum {
+  GST_WFD_AUDIO_UNKNOWN   = 0,
+  GST_WFD_AUDIO_LPCM      = (1 << 0),
+  GST_WFD_AUDIO_AAC       = (1 << 1),
+  GST_WFD_AUDIO_AC3       = (1 << 2)
+} GstWFDAudioFormats;
+
+typedef enum {
+  GST_WFD_FREQ_UNKNOWN  = 0,
+  GST_WFD_FREQ_44100    = (1 << 0),
+  GST_WFD_FREQ_48000    = (1 << 1)
+} GstWFDAudioFreq;
+
+typedef enum {
+  GST_WFD_CHANNEL_UNKNOWN = 0,
+  GST_WFD_CHANNEL_2       = (1 << 0),
+  GST_WFD_CHANNEL_4       = (1 << 1),
+  GST_WFD_CHANNEL_6       = (1 << 2),
+  GST_WFD_CHANNEL_8       = (1 << 3)
+} GstWFDAudioChannels;
+
+
+typedef enum {
+  GST_WFD_VIDEO_UNKNOWN = 0,
+  GST_WFD_VIDEO_H264    = (1 << 0)
+} GstWFDVideoCodecs;
+
+typedef enum {
+  GST_WFD_VIDEO_CEA_RESOLUTION = 0,
+  GST_WFD_VIDEO_VESA_RESOLUTION,
+  GST_WFD_VIDEO_HH_RESOLUTION
+} GstWFDVideoNativeResolution;
+
+typedef enum {
+  GST_WFD_CEA_UNKNOWN      = 0,
+  GST_WFD_CEA_640x480P60   = (1 << 0),
+  GST_WFD_CEA_720x480P60   = (1 << 1),
+  GST_WFD_CEA_720x480I60   = (1 << 2),
+  GST_WFD_CEA_720x576P50   = (1 << 3),
+  GST_WFD_CEA_720x576I50   = (1 << 4),
+  GST_WFD_CEA_1280x720P30  = (1 << 5),
+  GST_WFD_CEA_1280x720P60  = (1 << 6),
+  GST_WFD_CEA_1920x1080P30 = (1 << 7),
+  GST_WFD_CEA_1920x1080P60 = (1 << 8),
+  GST_WFD_CEA_1920x1080I60 = (1 << 9),
+  GST_WFD_CEA_1280x720P25  = (1 << 10),
+  GST_WFD_CEA_1280x720P50  = (1 << 11),
+  GST_WFD_CEA_1920x1080P25 = (1 << 12),
+  GST_WFD_CEA_1920x1080P50 = (1 << 13),
+  GST_WFD_CEA_1920x1080I50 = (1 << 14),
+  GST_WFD_CEA_1280x720P24  = (1 << 15),
+  GST_WFD_CEA_1920x1080P24 = (1 << 16)
+} GstWFDVideoCEAResolution;
+
+typedef enum {
+  GST_WFD_VESA_UNKNOWN       = 0,
+  GST_WFD_VESA_800x600P30    = (1 << 0),
+  GST_WFD_VESA_800x600P60    = (1 << 1),
+  GST_WFD_VESA_1024x768P30   = (1 << 2),
+  GST_WFD_VESA_1024x768P60   = (1 << 3),
+  GST_WFD_VESA_1152x864P30   = (1 << 4),
+  GST_WFD_VESA_1152x864P60   = (1 << 5),
+  GST_WFD_VESA_1280x768P30   = (1 << 6),
+  GST_WFD_VESA_1280x768P60   = (1 << 7),
+  GST_WFD_VESA_1280x800P30   = (1 << 8),
+  GST_WFD_VESA_1280x800P60   = (1 << 9),
+  GST_WFD_VESA_1360x768P30   = (1 << 10),
+  GST_WFD_VESA_1360x768P60   = (1 << 11),
+  GST_WFD_VESA_1366x768P30   = (1 << 12),
+  GST_WFD_VESA_1366x768P60   = (1 << 13),
+  GST_WFD_VESA_1280x1024P30  = (1 << 14),
+  GST_WFD_VESA_1280x1024P60  = (1 << 15),
+  GST_WFD_VESA_1400x1050P30  = (1 << 16),
+  GST_WFD_VESA_1400x1050P60  = (1 << 17),
+  GST_WFD_VESA_1440x900P30   = (1 << 18),
+  GST_WFD_VESA_1440x900P60   = (1 << 19),
+  GST_WFD_VESA_1600x900P30   = (1 << 20),
+  GST_WFD_VESA_1600x900P60   = (1 << 21),
+  GST_WFD_VESA_1600x1200P30  = (1 << 22),
+  GST_WFD_VESA_1600x1200P60  = (1 << 23),
+  GST_WFD_VESA_1680x1024P30  = (1 << 24),
+  GST_WFD_VESA_1680x1024P60  = (1 << 25),
+  GST_WFD_VESA_1680x1050P30  = (1 << 26),
+  GST_WFD_VESA_1680x1050P60  = (1 << 27),
+  GST_WFD_VESA_1920x1200P30  = (1 << 28),
+  GST_WFD_VESA_1920x1200P60  = (1 << 29)
+} GstWFDVideoVESAResolution;
+
+typedef enum {
+  GST_WFD_HH_UNKNOWN     = 0,
+  GST_WFD_HH_800x480P30  = (1 << 0),
+  GST_WFD_HH_800x480P60  = (1 << 1),
+  GST_WFD_HH_854x480P30  = (1 << 2),
+  GST_WFD_HH_854x480P60  = (1 << 3),
+  GST_WFD_HH_864x480P30  = (1 << 4),
+  GST_WFD_HH_864x480P60  = (1 << 5),
+  GST_WFD_HH_640x360P30  = (1 << 6),
+  GST_WFD_HH_640x360P60  = (1 << 7),
+  GST_WFD_HH_960x540P30  = (1 << 8),
+  GST_WFD_HH_960x540P60  = (1 << 9),
+  GST_WFD_HH_848x480P30  = (1 << 10),
+  GST_WFD_HH_848x480P60  = (1 << 11)
+} GstWFDVideoHHResolution;
+
+typedef enum {
+  GST_WFD_H264_UNKNOWN_PROFILE = 0,
+  GST_WFD_H264_BASE_PROFILE    = (1 << 0),
+  GST_WFD_H264_HIGH_PROFILE    = (1 << 1)
+} GstWFDVideoH264Profile;
+
+typedef enum {
+  GST_WFD_H264_LEVEL_UNKNOWN = 0,
+  GST_WFD_H264_LEVEL_3_1   = (1 << 0),
+  GST_WFD_H264_LEVEL_3_2   = (1 << 1),
+  GST_WFD_H264_LEVEL_4     = (1 << 2),
+  GST_WFD_H264_LEVEL_4_1   = (1 << 3),
+  GST_WFD_H264_LEVEL_4_2   = (1 << 4)
+} GstWFDVideoH264Level;
+
+typedef enum {
+  GST_WFD_HDCP_NONE = 0,
+  GST_WFD_HDCP_2_0  = (1 << 0),
+  GST_WFD_HDCP_2_1  = (1 << 1)
+} GstWFDHDCPProtection;
+
+typedef enum {
+  GST_WFD_SINK_UNKNOWN = -1,
+  GST_WFD_SINK_NOT_COUPLED = 0,
+  GST_WFD_SINK_COUPLED,
+  GST_WFD_SINK_TEARDOWN_COUPLING,
+  GST_WFD_SINK_RESERVED
+} GstWFDCoupledSinkStatus;
+
+typedef enum {
+  GST_WFD_TRIGGER_UNKNOWN = 0,
+  GST_WFD_TRIGGER_SETUP,
+  GST_WFD_TRIGGER_PAUSE,
+  GST_WFD_TRIGGER_TEARDOWN,
+  GST_WFD_TRIGGER_PLAY
+} GstWFDTrigger;
+
+typedef enum {
+  GST_WFD_RTSP_TRANS_UNKNOWN =  0,
+  GST_WFD_RTSP_TRANS_RTP     = (1 << 0),
+  GST_WFD_RTSP_TRANS_RDT     = (1 << 1)
+} GstWFDRTSPTransMode;
+
+typedef enum {
+  GST_WFD_RTSP_PROFILE_UNKNOWN =  0,
+  GST_WFD_RTSP_PROFILE_AVP     = (1 << 0),
+  GST_WFD_RTSP_PROFILE_SAVP    = (1 << 1)
+} GstWFDRTSPProfile;
+
+typedef enum {
+  GST_WFD_RTSP_LOWER_TRANS_UNKNOWN   = 0,
+  GST_WFD_RTSP_LOWER_TRANS_UDP       = (1 << 0),
+  GST_WFD_RTSP_LOWER_TRANS_UDP_MCAST = (1 << 1),
+  GST_WFD_RTSP_LOWER_TRANS_TCP       = (1 << 2),
+  GST_WFD_RTSP_LOWER_TRANS_HTTP      = (1 << 3)
+} GstWFDRTSPLowerTrans;
+
+typedef enum {
+  GST_WFD_PRIMARY_SINK   = 0,
+  GST_WFD_SECONDARY_SINK
+} GstWFDSinkType;
+
+typedef enum {
+  GST_WFD_CONNECTOR_VGA           = 0,
+  GST_WFD_CONNECTOR_S,
+  GST_WFD_CONNECTOR_COMPOSITE,
+  GST_WFD_CONNECTOR_COMPONENT,
+  GST_WFD_CONNECTOR_DVI,
+  GST_WFD_CONNECTOR_HDMI,
+  GST_WFD_CONNECTOR_LVDS,
+  GST_WFD_CONNECTOR_RESERVED_7,
+  GST_WFD_CONNECTOR_JAPANESE_D,
+  GST_WFD_CONNECTOR_SDI,
+  GST_WFD_CONNECTOR_DP,
+  GST_WFD_CONNECTOR_RESERVED_11,
+  GST_WFD_CONNECTOR_UDI,
+  GST_WFD_CONNECTOR_NO           = 254,
+  GST_WFD_CONNECTOR_PHYSICAL     = 255
+} GstWFDConnector;
+
+typedef enum {
+  GST_WFD_PREFERRED_DISPLAY_MODE_NOT_SUPPORTED = 0,
+  GST_WFD_PREFERRED_DISPLAY_MODE_SUPPORTED = 1
+} GstWFDPreferredDisplayModeEnum;
+
+typedef struct {
+  gchar  *audio_format;
+  guint32 modes;
+  guint latency;
+} GstWFDAudioCodec;
+
+typedef struct {
+  guint  count;
+  GstWFDAudioCodec *list;
+} GstWFDAudioCodeclist;
+
+
+typedef struct {
+  guint CEA_Support;
+  guint VESA_Support;
+  guint HH_Support;
+  guint latency;
+  guint min_slice_size;
+  guint slice_enc_params;
+  guint frame_rate_control_support;
+} GstWFDVideoH264MiscParams;
+
+typedef struct {
+  guint profile;
+  guint level;
+  guint max_hres;
+  guint max_vres;
+  GstWFDVideoH264MiscParams misc_params;
+} GstWFDVideoH264Codec;
+
+typedef struct {
+  guint native;
+  guint preferred_display_mode_supported;
+  GstWFDVideoH264Codec H264_codec;
+} GstWFDVideoCodec;
+
+typedef struct {
+  guint count;
+  GstWFDVideoCodec *list;
+} GstWFDVideoCodeclist;
+
+typedef struct {
+  guint64 video_3d_capability;
+  guint latency;
+  guint min_slice_size;
+  guint slice_enc_params;
+  guint frame_rate_control_support;
+} GstWFD3DVideoH264MiscParams;
+
+typedef struct {
+  guint profile;
+  guint level;
+  GstWFD3DVideoH264MiscParams misc_params;
+  guint max_hres;
+  guint max_vres;
+} GstWFD3DVideoH264Codec;
+
+typedef struct {
+  guint native;
+  guint preferred_display_mode_supported;
+  GstWFD3DVideoH264Codec H264_codec;
+} GstWFD3dCapList;
+
+typedef struct {
+  guint count;
+  GstWFD3dCapList *list;
+} GstWFD3DFormats;
+
+typedef struct {
+  gchar *hdcpversion;
+  gchar *TCPPort;
+} GstWFDHdcp2Spec;
+
+typedef struct {
+  GstWFDHdcp2Spec *hdcp2_spec;
+} GstWFDContentProtection;
+
+typedef struct {
+  guint edid_supported;
+  guint edid_block_count;
+  gchar *edid_payload;
+} GstWFDDisplayEdid;
+
+typedef struct {
+  guint status;
+  gchar *sink_address;
+} GstWFDCoupledSinkCap;
+
+typedef struct {
+  GstWFDCoupledSinkCap *coupled_sink_cap;
+} GstWFDCoupledSink;
+
+typedef struct {
+  gchar *wfd_trigger_method;
+} GstWFDTriggerMethod;
+
+typedef struct {
+  gchar *wfd_url0;
+  gchar *wfd_url1;
+} GstWFDPresentationUrl;
+
+typedef struct {
+  gchar *profile;
+  guint32 rtp_port0;
+  guint32 rtp_port1;
+  gchar *mode;
+} GstWFDClientRtpPorts;
+
+typedef struct {
+  gchar *destination;
+} GstWFDRoute;
+
+typedef struct {
+  gboolean I2CPresent;
+  guint32 I2C_port;
+} GstWFDI2C;
+
+typedef struct {
+  guint64 PTS;
+  guint64 DTS;
+} GstWFDAVFormatChangeTiming;
+
+typedef struct {
+  gboolean displaymodesupported;
+  guint64 p_clock;
+  guint32 H;
+  guint32 HB;
+  guint32 HSPOL_HSOFF;
+  guint32 HSW;
+  guint32 V;
+  guint32 VB;
+  guint32 VSPOL_VSOFF;
+  guint32 VSW;
+  guint VBS3D;
+  guint R;
+  guint V2d_s3d_modes;
+  guint P_depth;
+  GstWFDVideoH264Codec H264_codec;
+} GstWFDPreferredDisplayMode;
+
+typedef struct {
+  gboolean standby_resume_cap;
+} GstWFDStandbyResumeCapability;
+
+typedef struct {
+  gboolean wfd_standby;
+} GstWFDStandby;
+
+typedef struct {
+  gboolean supported;
+  gint32 connector_type;
+} GstWFDConnectorType;
+
+typedef struct {
+  gboolean idr_request;
+} GstWFDIdrRequest;
+
+/***********************************************************/
+
+typedef struct {
+
+  GstWFDAudioCodeclist *audio_codecs;
+  GstWFDVideoCodeclist *video_formats;
+  GstWFD3DFormats *video_3d_formats;
+  GstWFDContentProtection *content_protection;
+  GstWFDDisplayEdid *display_edid;
+  GstWFDCoupledSink *coupled_sink;
+  GstWFDTriggerMethod *trigger_method;
+  GstWFDPresentationUrl *presentation_url;
+  GstWFDClientRtpPorts *client_rtp_ports;
+  GstWFDRoute *route;
+  GstWFDI2C *I2C;
+  GstWFDAVFormatChangeTiming *av_format_change_timing;
+  GstWFDPreferredDisplayMode *preferred_display_mode;
+  GstWFDStandbyResumeCapability *standby_resume_capability;
+  GstWFDStandby *standby;
+  GstWFDConnectorType *connector_type;
+  GstWFDIdrRequest *idr_request;
+} GstWFDMessage;
+
+/* Session descriptions */
+GstWFDResult gst_wfd_message_new(GstWFDMessage **msg);
+GstWFDResult gst_wfd_message_init(GstWFDMessage *msg);
+GstWFDResult gst_wfd_message_uninit(GstWFDMessage *msg);
+GstWFDResult gst_wfd_message_free(GstWFDMessage *msg);
+GstWFDResult gst_wfd_message_parse_buffer(const guint8 *data, guint size, GstWFDMessage *msg);
+gchar *gst_wfd_message_as_text(const GstWFDMessage *msg);
+gchar *gst_wfd_message_param_names_as_text(const GstWFDMessage *msg);
+GstWFDResult gst_wfd_message_dump(const GstWFDMessage *msg);
+
+
+GstWFDResult gst_wfd_message_set_supported_audio_format(GstWFDMessage *msg,
+                                               guint aCodec, guint aFreq, guint aChanels,
+                                               guint aBitwidth, guint32 aLatency);
+GstWFDResult gst_wfd_message_set_prefered_audio_format(GstWFDMessage *msg,
+                                              GstWFDAudioFormats aCodec, GstWFDAudioFreq aFreq, GstWFDAudioChannels aChanels,
+                                              guint aBitwidth, guint32 aLatency);
+GstWFDResult gst_wfd_message_get_supported_audio_format(GstWFDMessage *msg,
+                                               guint *aCodec, guint *aFreq, guint *aChanels,
+                                               guint *aBitwidth, guint32 *aLatency);
+GstWFDResult gst_wfd_message_get_prefered_audio_format(GstWFDMessage *msg,
+                                              GstWFDAudioFormats *aCodec, GstWFDAudioFreq *aFreq, GstWFDAudioChannels *aChanels,
+                                              guint *aBitwidth, guint32 *aLatency);
+
+GstWFDResult gst_wfd_message_set_supported_video_format(GstWFDMessage *msg, GstWFDVideoCodecs vCodec,
+                                               GstWFDVideoNativeResolution vNative, guint64 vNativeResolution,
+                                               guint64 vCEAResolution, guint64 vVESAResolution, guint64 vHHResolution,
+                                               guint vProfile, guint vLevel, guint32 vLatency, guint32 vMaxHeight,
+                                               guint32 vMaxWidth, guint32 min_slice_size, guint32 slice_enc_params, guint frame_rate_control,
+                                               guint preferred_display_mode);
+GstWFDResult gst_wfd_message_set_prefered_video_format(GstWFDMessage *msg, GstWFDVideoCodecs vCodec,
+                                              GstWFDVideoNativeResolution vNative, guint64 vNativeResolution,
+                                              GstWFDVideoCEAResolution vCEAResolution, GstWFDVideoVESAResolution vVESAResolution,
+                                              GstWFDVideoHHResolution vHHResolution, GstWFDVideoH264Profile vProfile,
+                                              GstWFDVideoH264Level vLevel, guint32 vLatency, guint32 vMaxHeight,
+                                              guint32 vMaxWidth, guint32 min_slice_size, guint32 slice_enc_params, guint frame_rate_control);
+GstWFDResult gst_wfd_message_get_supported_video_format(GstWFDMessage *msg, GstWFDVideoCodecs *vCodec,
+                                               GstWFDVideoNativeResolution *vNative, guint64 *vNativeResolution,
+                                               guint64 *vCEAResolution, guint64 *vVESAResolution, guint64 *vHHResolution,
+                                               guint *vProfile, guint *vLevel, guint32 *vLatency, guint32 *vMaxHeight,
+                                               guint32 *vMaxWidth, guint32 *min_slice_size, guint32 *slice_enc_params, guint *frame_rate_control);
+GstWFDResult gst_wfd_message_get_prefered_video_format(GstWFDMessage *msg, GstWFDVideoCodecs *vCodec,
+                                              GstWFDVideoNativeResolution *vNative, guint64 *vNativeResolution,
+                                              GstWFDVideoCEAResolution *vCEAResolution, GstWFDVideoVESAResolution *vVESAResolution,
+                                              GstWFDVideoHHResolution *vHHResolution, GstWFDVideoH264Profile *vProfile,
+                                              GstWFDVideoH264Level *vLevel, guint32 *vLatency, guint32 *vMaxHeight,
+                                              guint32 *vMaxWidth, guint32 *min_slice_size, guint32 *slice_enc_params, guint *frame_rate_control);
+
+/* Todo wfd-3d-formats */
+
+GstWFDResult gst_wfd_message_set_contentprotection_type(GstWFDMessage *msg, GstWFDHDCPProtection hdcpversion, guint32 TCPPort);
+GstWFDResult gst_wfd_message_get_contentprotection_type(GstWFDMessage *msg, GstWFDHDCPProtection *hdcpversion, guint32 *TCPPort);
+
+GstWFDResult gst_wfd_message_set_display_EDID(GstWFDMessage *msg, gboolean edid_supported, guint32 edid_blockcount, gchar *edid_playload);
+GstWFDResult gst_wfd_message_get_display_EDID(GstWFDMessage *msg, gboolean *edid_supported, guint32 *edid_blockcount, gchar **edid_playload);
+
+
+GstWFDResult gst_wfd_message_set_coupled_sink(GstWFDMessage *msg, GstWFDCoupledSinkStatus status, gchar *sink_address);
+GstWFDResult gst_wfd_message_get_coupled_sink(GstWFDMessage *msg, GstWFDCoupledSinkStatus *status, gchar **sink_address);
+
+GstWFDResult gst_wfd_message_set_trigger_type(GstWFDMessage *msg, GstWFDTrigger trigger);
+GstWFDResult gst_wfd_message_get_trigger_type(GstWFDMessage *msg, GstWFDTrigger *trigger);
+
+GstWFDResult gst_wfd_message_set_presentation_url(GstWFDMessage *msg, gchar *wfd_url0, gchar *wfd_url1);
+GstWFDResult gst_wfd_message_get_presentation_url(GstWFDMessage *msg, gchar **wfd_url0, gchar **wfd_url1);
+
+GstWFDResult gst_wfd_message_set_prefered_RTP_ports(GstWFDMessage *msg, GstWFDRTSPTransMode trans, GstWFDRTSPProfile profile,
+                                           GstWFDRTSPLowerTrans lowertrans, guint32 rtp_port0, guint32 rtp_port1);
+GstWFDResult gst_wfd_message_get_prefered_RTP_ports(GstWFDMessage *msg, GstWFDRTSPTransMode *trans, GstWFDRTSPProfile *profile,
+                                           GstWFDRTSPLowerTrans *lowertrans, guint32 *rtp_port0, guint32 *rtp_port1);
+
+GstWFDResult gst_wfd_message_set_audio_sink_type(GstWFDMessage *msg, GstWFDSinkType sinktype);
+GstWFDResult gst_wfd_message_get_audio_sink_type(GstWFDMessage *msg, GstWFDSinkType *sinktype);
+
+GstWFDResult gst_wfd_message_set_I2C_port(GstWFDMessage *msg, gboolean i2csupport, guint32 i2cport);
+GstWFDResult gst_wfd_message_get_I2C_port(GstWFDMessage *msg, gboolean *i2csupport, guint32 *i2cport);
+
+GstWFDResult gst_wfd_message_set_av_format_change_timing(GstWFDMessage *msg, guint64 PTS, guint64 DTS);
+GstWFDResult gst_wfd_message_get_av_format_change_timing(GstWFDMessage *msg, guint64 *PTS, guint64 *DTS);
+
+/* Todo wfd-preferred-display-mode */
+
+GstWFDResult gst_wfd_message_set_standby_resume_capability(GstWFDMessage *msg, gboolean supported);
+GstWFDResult gst_wfd_message_get_standby_resume_capability(GstWFDMessage *msg, gboolean *supported);
+
+GstWFDResult gst_wfd_message_set_standby(GstWFDMessage *msg, gboolean standby_enable);
+GstWFDResult gst_wfd_message_get_standby(GstWFDMessage *msg, gboolean *standby_enable);
+
+GstWFDResult gst_wfd_message_set_connector_type(GstWFDMessage *msg, GstWFDConnector connector);
+GstWFDResult gst_wfd_message_get_connector_type(GstWFDMessage *msg, GstWFDConnector *connector);
+
+GstWFDResult gst_wfd_message_set_idr_request(GstWFDMessage *msg);
+
+G_END_DECLS
+
+#endif /* __GST_WFD_SINK_MESSAGE_H__ */
diff --git a/wfdmanager/wfdrtpbuffer/gstwfdrtpbuffer.c b/wfdmanager/wfdrtpbuffer/gstwfdrtpbuffer.c
new file mode 100644 (file)
index 0000000..20244b8
--- /dev/null
@@ -0,0 +1,3602 @@
+/*
+ * Farsight Voice+Video library
+ *
+ *  Copyright 2007 Collabora Ltd,
+ *  Copyright 2007 Nokia Corporation
+ *   @author: Philippe Kalaf <philippe.kalaf@collabora.co.uk>.
+ *  Copyright 2007 Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+/**
+ * SECTION:element-wfdrtpbuffer
+ *
+ * This element reorders and removes duplicate RTP packets as they are received
+ * from a network source.
+ *
+ * The element needs the clock-rate of the RTP payload in order to estimate the
+ * delay. This information is obtained either from the caps on the sink pad or,
+ * when no caps are present, from the #GstWfdRTPBuffer::request-pt-map signal.
+ * To clear the previous pt-map use the #GstWfdRTPBuffer::clear-pt-map signal.
+ *
+ * The wfdrtpbuffer will wait for missing packets up to a configurable time
+ * limit using the #GstWfdRTPBuffer:latency property. Packets arriving too
+ * late are considered to be lost packets. If the #GstWfdRTPBuffer:do-lost
+ * property is set, lost packets will result in a custom serialized downstream
+ * event of name GstRTPPacketLost. The lost packet events are usually used by a
+ * depayloader or other element to create concealment data or some other logic
+ * to gracefully handle the missing packets.
+ *
+ * The jitterbuffer will use the DTS (or PTS if no DTS is set) of the incomming
+ * buffer and the rtptime inside the RTP packet to create a PTS on the outgoing
+ * buffer.
+ *
+ * The jitterbuffer can also be configured to send early retransmission events
+ * upstream by setting the #GstWfdRTPBuffer:do-retransmission property. In
+ * this mode, the jitterbuffer tries to estimate when a packet should arrive and
+ * sends a custom upstream event named GstRTPRetransmissionRequest when the
+ * packet is considered late. The initial expected packet arrival time is
+ * calculated as follows:
+ *
+ * - If seqnum N arrived at time T, seqnum N+1 is expected to arrive at
+ *     T + packet-spacing + #GstWfdRTPBuffer:rtx-delay. The packet spacing is
+ *     calculated from the DTS (or PTS is no DTS) of two consecutive RTP
+ *     packets with different rtptime.
+ *
+ * - If seqnum N0 arrived at time T0 and seqnum Nm arrived at time Tm,
+ *     seqnum Ni is expected at time Ti = T0 + i*(Tm - T0)/(Nm - N0). Any
+ *     previously scheduled timeout is overwritten.
+ *
+ * - If seqnum N arrived, all seqnum older than
+ *     N - #GstWfdRTPBuffer:rtx-delay-reorder are considered late
+ *     immediately. This is to request fast feedback for abonormally reorder
+ *     packets before any of the previous timeouts is triggered.
+ *
+ * A late packet triggers the GstRTPRetransmissionRequest custom upstream
+ * event. After the initial timeout expires and the retransmission event is
+ * sent, the timeout is scheduled for
+ * T + #GstWfdRTPBuffer:rtx-retry-timeout. If the missing packet did not
+ * arrive after #GstWfdRTPBuffer:rtx-retry-timeout, a new
+ * GstRTPRetransmissionRequest is sent upstream and the timeout is rescheduled
+ * again for T + #GstWfdRTPBuffer:rtx-retry-timeout. This repeats until
+ * #GstWfdRTPBuffer:rtx-retry-period elapsed, at which point no further
+ * retransmission requests are sent and the regular logic is performed to
+ * schedule a lost packet as discussed above.
+ *
+ * This element acts as a live element and so adds #GstWfdRTPBuffer:latency
+ * to the pipeline.
+ *
+ * This element will automatically be used inside rtpbin.
+ *
+ * <refsect2>
+ * <title>Example pipelines</title>
+ * |[
+ * gst-launch-1.0 rtspsrc location=rtsp://192.168.1.133:8554/mpeg1or2AudioVideoTest ! wfdrtpbuffer ! rtpmpvdepay ! mpeg2dec ! xvimagesink
+ * ]| Connect to a streaming server and decode the MPEG video. The jitterbuffer is
+ * inserted into the pipeline to smooth out network jitter and to reorder the
+ * out-of-order RTP packets.
+ * </refsect2>
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <gst/rtp/gstrtpbuffer.h>
+
+#include "gstwfdrtpbuffer.h"
+#include "wfdrtpbuffer.h"
+#include "rtpstats.h"
+
+//#include "glib-compat-private.h"
+
+GST_DEBUG_CATEGORY (wfdrtpbuffer_debug);
+#define GST_CAT_DEFAULT (wfdrtpbuffer_debug)
+
+/* WfdRTPBuffer signals and args */
+enum
+{
+  SIGNAL_REQUEST_PT_MAP,
+  SIGNAL_CLEAR_PT_MAP,
+  SIGNAL_HANDLE_SYNC,
+  SIGNAL_ON_NPT_STOP,
+  SIGNAL_SET_ACTIVE,
+  LAST_SIGNAL
+};
+
+#define DEFAULT_LATENCY_MS          200
+#define DEFAULT_DROP_ON_LATENCY     FALSE
+#define DEFAULT_TS_OFFSET           0
+#define DEFAULT_DO_LOST             FALSE
+#define DEFAULT_MODE                WFD_RTP_BUFFER_MODE_SLAVE
+#define DEFAULT_PERCENT             0
+#define DEFAULT_DO_RETRANSMISSION   FALSE
+#define DEFAULT_RTX_DELAY           -1
+#define DEFAULT_RTX_DELAY_REORDER   3
+#define DEFAULT_RTX_RETRY_TIMEOUT   -1
+#define DEFAULT_RTX_RETRY_PERIOD    -1
+
+#define DEFAULT_AUTO_RTX_DELAY (20 * GST_MSECOND)
+#define DEFAULT_AUTO_RTX_TIMEOUT (40 * GST_MSECOND)
+
+enum
+{
+  PROP_0,
+  PROP_LATENCY,
+  PROP_DROP_ON_LATENCY,
+  PROP_TS_OFFSET,
+  PROP_DO_LOST,
+  PROP_MODE,
+  PROP_PERCENT,
+  PROP_DO_RETRANSMISSION,
+  PROP_RTX_DELAY,
+  PROP_RTX_DELAY_REORDER,
+  PROP_RTX_RETRY_TIMEOUT,
+  PROP_RTX_RETRY_PERIOD,
+  PROP_STATS,
+  PROP_LAST
+};
+
+#define JBUF_LOCK(priv)   (g_mutex_lock (&(priv)->jbuf_lock))
+
+#define JBUF_LOCK_CHECK(priv,label) G_STMT_START {    \
+  JBUF_LOCK (priv);                                   \
+  if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))    \
+    goto label;                                       \
+} G_STMT_END
+#define JBUF_UNLOCK(priv) (g_mutex_unlock (&(priv)->jbuf_lock))
+
+#define JBUF_WAIT_TIMER(priv)   G_STMT_START {            \
+  GST_DEBUG ("waiting timer");                            \
+  (priv)->waiting_timer = TRUE;                           \
+  g_cond_wait (&(priv)->jbuf_timer, &(priv)->jbuf_lock);  \
+  (priv)->waiting_timer = FALSE;                          \
+  GST_DEBUG ("waiting timer done");                       \
+} G_STMT_END
+#define JBUF_SIGNAL_TIMER(priv) G_STMT_START {            \
+  if (G_UNLIKELY ((priv)->waiting_timer)) {               \
+    GST_DEBUG ("signal timer");                           \
+    g_cond_signal (&(priv)->jbuf_timer);                  \
+  }                                                       \
+} G_STMT_END
+
+#define JBUF_WAIT_EVENT(priv,label) G_STMT_START {       \
+  GST_DEBUG ("waiting event");                           \
+  (priv)->waiting_event = TRUE;                          \
+  g_cond_wait (&(priv)->jbuf_event, &(priv)->jbuf_lock); \
+  (priv)->waiting_event = FALSE;                         \
+  GST_DEBUG ("waiting event done");                      \
+  if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))       \
+    goto label;                                          \
+} G_STMT_END
+#define JBUF_SIGNAL_EVENT(priv) G_STMT_START {           \
+  if (G_UNLIKELY ((priv)->waiting_event)) {              \
+    GST_DEBUG ("signal event");                          \
+    g_cond_signal (&(priv)->jbuf_event);                 \
+  }                                                      \
+} G_STMT_END
+
+#define JBUF_WAIT_QUERY(priv,label) G_STMT_START {       \
+  GST_DEBUG ("waiting query");                           \
+  (priv)->waiting_query = TRUE;                          \
+  g_cond_wait (&(priv)->jbuf_query, &(priv)->jbuf_lock); \
+  (priv)->waiting_query = FALSE;                         \
+  GST_DEBUG ("waiting query done");                      \
+  if (G_UNLIKELY (priv->srcresult != GST_FLOW_OK))       \
+    goto label;                                          \
+} G_STMT_END
+#define JBUF_SIGNAL_QUERY(priv,res) G_STMT_START {       \
+  (priv)->last_query = res;                              \
+  if (G_UNLIKELY ((priv)->waiting_query)) {              \
+    GST_DEBUG ("signal query");                          \
+    g_cond_signal (&(priv)->jbuf_query);                 \
+  }                                                      \
+} G_STMT_END
+
+
+struct _GstWfdRTPBufferPrivate
+{
+  GstPad *sinkpad, *srcpad;
+  GstPad *rtcpsinkpad;
+
+  WfdRTPBuffer *jbuf;
+  GMutex jbuf_lock;
+  gboolean waiting_timer;
+  GCond jbuf_timer;
+  gboolean waiting_event;
+  GCond jbuf_event;
+  gboolean waiting_query;
+  GCond jbuf_query;
+  gboolean last_query;
+  gboolean discont;
+  gboolean ts_discont;
+  gboolean active;
+  guint64 out_offset;
+
+  gboolean timer_running;
+  GThread *timer_thread;
+
+  /* properties */
+  guint latency_ms;
+  guint64 latency_ns;
+  gboolean drop_on_latency;
+  gint64 ts_offset;
+  gboolean do_lost;
+  gboolean do_retransmission;
+  gint rtx_delay;
+  gint rtx_delay_reorder;
+  gint rtx_retry_timeout;
+  gint rtx_retry_period;
+
+  /* the last seqnum we pushed out */
+  guint32 last_popped_seqnum;
+  /* the next expected seqnum we push */
+  guint32 next_seqnum;
+  /* last output time */
+  GstClockTime last_out_time;
+  /* last valid input timestamp and rtptime pair */
+  GstClockTime ips_dts;
+  guint64 ips_rtptime;
+  GstClockTime packet_spacing;
+
+  /* the next expected seqnum we receive */
+  GstClockTime last_in_dts;
+  guint32 last_in_seqnum;
+  guint32 next_in_seqnum;
+
+  GArray *timers;
+
+  /* start and stop ranges */
+  GstClockTime npt_start;
+  GstClockTime npt_stop;
+  guint64 ext_timestamp;
+  guint64 last_elapsed;
+  guint64 estimated_eos;
+  GstClockID eos_id;
+
+  /* state */
+  gboolean eos;
+  guint last_percent;
+
+  /* clock rate and rtp timestamp offset */
+  gint last_pt;
+  gint32 clock_rate;
+  gint64 clock_base;
+  gint64 prev_ts_offset;
+
+  /* when we are shutting down */
+  GstFlowReturn srcresult;
+  gboolean blocked;
+
+  /* for sync */
+  GstSegment segment;
+  GstClockID clock_id;
+  GstClockTime timer_timeout;
+  guint16 timer_seqnum;
+  /* the latency of the upstream peer, we have to take this into account when
+   * synchronizing the buffers. */
+  GstClockTime peer_latency;
+  guint64 ext_rtptime;
+  GstBuffer *last_sr;
+
+  /* some accounting */
+  guint64 num_late;
+  guint64 num_duplicates;
+  guint64 num_rtx_requests;
+  guint64 num_rtx_success;
+  guint64 num_rtx_failed;
+  gdouble avg_rtx_num;
+  guint64 avg_rtx_rtt;
+
+  /* for the jitter */
+  GstClockTime last_dts;
+  guint64 last_rtptime;
+  GstClockTime avg_jitter;
+};
+
+typedef enum
+{
+  TIMER_TYPE_EXPECTED,
+  TIMER_TYPE_LOST,
+  TIMER_TYPE_DEADLINE,
+  TIMER_TYPE_EOS
+} TimerType;
+
+typedef struct
+{
+  guint idx;
+  guint16 seqnum;
+  guint num;
+  TimerType type;
+  GstClockTime timeout;
+  GstClockTime duration;
+  GstClockTime rtx_base;
+  GstClockTime rtx_delay;
+  GstClockTime rtx_retry;
+  GstClockTime rtx_last;
+  guint num_rtx_retry;
+} TimerData;
+
+#define GST_WFD_RTP_BUFFER_GET_PRIVATE(o) \
+  (G_TYPE_INSTANCE_GET_PRIVATE ((o), GST_TYPE_WFD_RTP_BUFFER, \
+                                GstWfdRTPBufferPrivate))
+
+static GstStaticPadTemplate gst_wfd_rtp_buffer_sink_template =
+GST_STATIC_PAD_TEMPLATE ("sink",
+    GST_PAD_SINK,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("application/x-rtp, "
+        "clock-rate = (int) [ 1, 2147483647 ]"
+        /* "payload = (int) , "
+         * "encoding-name = (string) "
+         */ )
+    );
+
+static GstStaticPadTemplate gst_wfd_rtp_buffer_sink_rtcp_template =
+GST_STATIC_PAD_TEMPLATE ("sink_rtcp",
+    GST_PAD_SINK,
+    GST_PAD_REQUEST,
+    GST_STATIC_CAPS ("application/x-rtcp")
+    );
+
+static GstStaticPadTemplate gst_wfd_rtp_buffer_src_template =
+GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("application/x-rtp"
+        /* "payload = (int) , "
+         * "clock-rate = (int) , "
+         * "encoding-name = (string) "
+         */ )
+    );
+
+static guint gst_wfd_rtp_buffer_signals[LAST_SIGNAL] = { 0 };
+
+#define gst_wfd_rtp_buffer_parent_class parent_class
+G_DEFINE_TYPE (GstWfdRTPBuffer, gst_wfd_rtp_buffer, GST_TYPE_ELEMENT);
+
+/* object overrides */
+static void gst_wfd_rtp_buffer_set_property (GObject * object,
+    guint prop_id, const GValue * value, GParamSpec * pspec);
+static void gst_wfd_rtp_buffer_get_property (GObject * object,
+    guint prop_id, GValue * value, GParamSpec * pspec);
+static void gst_wfd_rtp_buffer_finalize (GObject * object);
+
+/* element overrides */
+static GstStateChangeReturn gst_wfd_rtp_buffer_change_state (GstElement
+    * element, GstStateChange transition);
+static GstPad *gst_wfd_rtp_buffer_request_new_pad (GstElement * element,
+    GstPadTemplate * templ, const gchar * name, const GstCaps * filter);
+static void gst_wfd_rtp_buffer_release_pad (GstElement * element,
+    GstPad * pad);
+static GstClock *gst_wfd_rtp_buffer_provide_clock (GstElement * element);
+
+/* pad overrides */
+static GstCaps *gst_wfd_rtp_buffer_getcaps (GstPad * pad, GstCaps * filter);
+static GstIterator *gst_wfd_rtp_buffer_iterate_internal_links (GstPad * pad,
+    GstObject * parent);
+
+/* sinkpad overrides */
+static gboolean gst_wfd_rtp_buffer_sink_event (GstPad * pad,
+    GstObject * parent, GstEvent * event);
+static GstFlowReturn gst_wfd_rtp_buffer_chain (GstPad * pad,
+    GstObject * parent, GstBuffer * buffer);
+
+static gboolean gst_wfd_rtp_buffer_sink_rtcp_event (GstPad * pad,
+    GstObject * parent, GstEvent * event);
+static GstFlowReturn gst_wfd_rtp_buffer_chain_rtcp (GstPad * pad,
+    GstObject * parent, GstBuffer * buffer);
+
+static gboolean gst_wfd_rtp_buffer_sink_query (GstPad * pad,
+    GstObject * parent, GstQuery * query);
+
+/* srcpad overrides */
+static gboolean gst_wfd_rtp_buffer_src_event (GstPad * pad,
+    GstObject * parent, GstEvent * event);
+static gboolean gst_wfd_rtp_buffer_src_activate_mode (GstPad * pad,
+    GstObject * parent, GstPadMode mode, gboolean active);
+static void gst_wfd_rtp_buffer_loop (GstWfdRTPBuffer * jitterbuffer);
+static gboolean gst_wfd_rtp_buffer_src_query (GstPad * pad,
+    GstObject * parent, GstQuery * query);
+
+static void
+gst_wfd_rtp_buffer_clear_pt_map (GstWfdRTPBuffer * jitterbuffer);
+static GstClockTime
+gst_wfd_rtp_buffer_set_active (GstWfdRTPBuffer * jitterbuffer,
+    gboolean active, guint64 base_time);
+static void do_handle_sync (GstWfdRTPBuffer * jitterbuffer);
+
+static void unschedule_current_timer (GstWfdRTPBuffer * jitterbuffer);
+static void remove_all_timers (GstWfdRTPBuffer * jitterbuffer);
+
+static void wait_next_timeout (GstWfdRTPBuffer * jitterbuffer);
+
+static GstStructure *gst_wfd_rtp_buffer_create_stats (GstWfdRTPBuffer *
+    jitterbuffer);
+
+static void
+gst_wfd_rtp_buffer_class_init (GstWfdRTPBufferClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstElementClass *gstelement_class;
+
+  gobject_class = (GObjectClass *) klass;
+  gstelement_class = (GstElementClass *) klass;
+
+  g_type_class_add_private (klass, sizeof (GstWfdRTPBufferPrivate));
+
+  gobject_class->finalize = gst_wfd_rtp_buffer_finalize;
+
+  gobject_class->set_property = gst_wfd_rtp_buffer_set_property;
+  gobject_class->get_property = gst_wfd_rtp_buffer_get_property;
+
+  /**
+   * GstWfdRTPBuffer:latency:
+   *
+   * The maximum latency of the jitterbuffer. Packets will be kept in the buffer
+   * for at most this time.
+   */
+  g_object_class_install_property (gobject_class, PROP_LATENCY,
+      g_param_spec_uint ("latency", "Buffer latency in ms",
+          "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:drop-on-latency:
+   *
+   * Drop oldest buffers when the queue is completely filled.
+   */
+  g_object_class_install_property (gobject_class, PROP_DROP_ON_LATENCY,
+      g_param_spec_boolean ("drop-on-latency",
+          "Drop buffers when maximum latency is reached",
+          "Tells the jitterbuffer to never exceed the given latency in size",
+          DEFAULT_DROP_ON_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:ts-offset:
+   *
+   * Adjust GStreamer output buffer timestamps in the jitterbuffer with offset.
+   * This is mainly used to ensure interstream synchronisation.
+   */
+  g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
+      g_param_spec_int64 ("ts-offset", "Timestamp Offset",
+          "Adjust buffer timestamps with offset in nanoseconds", G_MININT64,
+          G_MAXINT64, DEFAULT_TS_OFFSET,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstWfdRTPBuffer:do-lost:
+   *
+   * Send out a GstRTPPacketLost event downstream when a packet is considered
+   * lost.
+   */
+  g_object_class_install_property (gobject_class, PROP_DO_LOST,
+      g_param_spec_boolean ("do-lost", "Do Lost",
+          "Send an event downstream when a packet is lost", DEFAULT_DO_LOST,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstWfdRTPBuffer:mode:
+   *
+   * Control the buffering and timestamping mode used by the jitterbuffer.
+   */
+  g_object_class_install_property (gobject_class, PROP_MODE,
+      g_param_spec_enum ("mode", "Mode",
+          "Control the buffering algorithm in use", WFD_TYPE_RTP_BUFFER_MODE,
+          DEFAULT_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:percent:
+   *
+   * The percent of the jitterbuffer that is filled.
+   */
+  g_object_class_install_property (gobject_class, PROP_PERCENT,
+      g_param_spec_int ("percent", "percent",
+          "The buffer filled percent", 0, 100,
+          0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:do-retransmission:
+   *
+   * Send out a GstRTPRetransmission event upstream when a packet is considered
+   * late and should be retransmitted.
+   *
+   * Since: 1.2
+   */
+  g_object_class_install_property (gobject_class, PROP_DO_RETRANSMISSION,
+      g_param_spec_boolean ("do-retransmission", "Do Retransmission",
+          "Send retransmission events upstream when a packet is late",
+          DEFAULT_DO_RETRANSMISSION,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstWfdRTPBuffer:rtx-delay:
+   *
+   * When a packet did not arrive at the expected time, wait this extra amount
+   * of time before sending a retransmission event.
+   *
+   * When -1 is used, the max jitter will be used as extra delay.
+   *
+   * Since: 1.2
+   */
+  g_object_class_install_property (gobject_class, PROP_RTX_DELAY,
+      g_param_spec_int ("rtx-delay", "RTX Delay",
+          "Extra time in ms to wait before sending retransmission "
+          "event (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_DELAY,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:rtx-delay-reorder:
+   *
+   * Assume that a retransmission event should be sent when we see
+   * this much packet reordering.
+   *
+   * When -1 is used, the value will be estimated based on observed packet
+   * reordering.
+   *
+   * Since: 1.2
+   */
+  g_object_class_install_property (gobject_class, PROP_RTX_DELAY_REORDER,
+      g_param_spec_int ("rtx-delay-reorder", "RTX Delay Reorder",
+          "Sending retransmission event when this much reordering (-1 automatic)",
+          -1, G_MAXINT, DEFAULT_RTX_DELAY_REORDER,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer::rtx-retry-timeout:
+   *
+   * When no packet has been received after sending a retransmission event
+   * for this time, retry sending a retransmission event.
+   *
+   * When -1 is used, the value will be estimated based on observed round
+   * trip time.
+   *
+   * Since: 1.2
+   */
+  g_object_class_install_property (gobject_class, PROP_RTX_RETRY_TIMEOUT,
+      g_param_spec_int ("rtx-retry-timeout", "RTX Retry Timeout",
+          "Retry sending a transmission event after this timeout in "
+          "ms (-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_TIMEOUT,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:rtx-retry-period:
+   *
+   * The amount of time to try to get a retransmission.
+   *
+   * When -1 is used, the value will be estimated based on the jitterbuffer
+   * latency and the observed round trip time.
+   *
+   * Since: 1.2
+   */
+  g_object_class_install_property (gobject_class, PROP_RTX_RETRY_PERIOD,
+      g_param_spec_int ("rtx-retry-period", "RTX Retry Period",
+          "Try to get a retransmission for this many ms "
+          "(-1 automatic)", -1, G_MAXINT, DEFAULT_RTX_RETRY_PERIOD,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+  /**
+   * GstWfdRTPBuffer:stats:
+   *
+   * Various jitterbuffer statistics. This property returns a GstStructure
+   * with name application/x-rtp-jitterbuffer-stats with the following fields:
+   *
+   *  "rtx-count"         G_TYPE_UINT64 The number of retransmissions requested
+   *  "rtx-success-count" G_TYPE_UINT64 The number of successful retransmissions
+   *  "rtx-per-packet"    G_TYPE_DOUBLE Average number of RTX per packet
+   *  "rtx-rtt"           G_TYPE_UINT64 Average round trip time per RTX
+   *
+   * Since: 1.4
+   */
+  g_object_class_install_property (gobject_class, PROP_STATS,
+      g_param_spec_boxed ("stats", "Statistics",
+          "Various statistics", GST_TYPE_STRUCTURE,
+          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
+
+  /**
+   * GstWfdRTPBuffer::request-pt-map:
+   * @buffer: the object which received the signal
+   * @pt: the pt
+   *
+   * Request the payload type as #GstCaps for @pt.
+   */
+  gst_wfd_rtp_buffer_signals[SIGNAL_REQUEST_PT_MAP] =
+      g_signal_new ("request-pt-map", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstWfdRTPBufferClass,
+          request_pt_map), NULL, NULL, g_cclosure_marshal_generic,
+      GST_TYPE_CAPS, 1, G_TYPE_UINT);
+  /**
+   * GstWfdRTPBuffer::handle-sync:
+   * @buffer: the object which received the signal
+   * @struct: a GstStructure containing sync values.
+   *
+   * Be notified of new sync values.
+   */
+  gst_wfd_rtp_buffer_signals[SIGNAL_HANDLE_SYNC] =
+      g_signal_new ("handle-sync", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstWfdRTPBufferClass,
+          handle_sync), NULL, NULL, g_cclosure_marshal_VOID__BOXED,
+      G_TYPE_NONE, 1, GST_TYPE_STRUCTURE | G_SIGNAL_TYPE_STATIC_SCOPE);
+
+  /**
+   * GstWfdRTPBuffer::on-npt-stop:
+   * @buffer: the object which received the signal
+   *
+   * Signal that the jitterbufer has pushed the RTP packet that corresponds to
+   * the npt-stop position.
+   */
+  gst_wfd_rtp_buffer_signals[SIGNAL_ON_NPT_STOP] =
+      g_signal_new ("on-npt-stop", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstWfdRTPBufferClass,
+          on_npt_stop), NULL, NULL, g_cclosure_marshal_VOID__VOID,
+      G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  /**
+   * GstWfdRTPBuffer::clear-pt-map:
+   * @buffer: the object which received the signal
+   *
+   * Invalidate the clock-rate as obtained with the
+   * #GstWfdRTPBuffer::request-pt-map signal.
+   */
+  gst_wfd_rtp_buffer_signals[SIGNAL_CLEAR_PT_MAP] =
+      g_signal_new ("clear-pt-map", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
+      G_STRUCT_OFFSET (GstWfdRTPBufferClass, clear_pt_map), NULL, NULL,
+      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  /**
+   * GstWfdRTPBuffer::set-active:
+   * @buffer: the object which received the signal
+   *
+   * Start pushing out packets with the given base time. This signal is only
+   * useful in buffering mode.
+   *
+   * Returns: the time of the last pushed packet.
+   */
+  gst_wfd_rtp_buffer_signals[SIGNAL_SET_ACTIVE] =
+      g_signal_new ("set-active", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
+      G_STRUCT_OFFSET (GstWfdRTPBufferClass, set_active), NULL, NULL,
+      g_cclosure_marshal_generic, G_TYPE_UINT64, 2, G_TYPE_BOOLEAN,
+      G_TYPE_UINT64);
+
+  gstelement_class->change_state =
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_change_state);
+  gstelement_class->request_new_pad =
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_request_new_pad);
+  gstelement_class->release_pad =
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_release_pad);
+  gstelement_class->provide_clock =
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_provide_clock);
+
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&gst_wfd_rtp_buffer_src_template));
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&gst_wfd_rtp_buffer_sink_template));
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&gst_wfd_rtp_buffer_sink_rtcp_template));
+
+  gst_element_class_set_static_metadata (gstelement_class,
+      "The Wi-Fi Display RTP packet jitter-buffer", "Filter/Network/RTP",
+      "A buffer that deals with network jitter and other transmission faults",
+      "Taewan kim <taewan79.kim@samsung.com>, "
+      "YeJin Cho <cho.yejin@samsung.com>,"
+      "Sangkyu Park <sk1122.park@samsung.com>");
+
+  klass->clear_pt_map = GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_clear_pt_map);
+  klass->set_active = GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_set_active);
+
+  GST_DEBUG_CATEGORY_INIT
+      (wfdrtpbuffer_debug, "wfdrtpbuffer", 0, "WFD RTP Jitter Buffer");
+}
+
+static void
+gst_wfd_rtp_buffer_init (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = GST_WFD_RTP_BUFFER_GET_PRIVATE (jitterbuffer);
+  jitterbuffer->priv = priv;
+
+  priv->latency_ms = DEFAULT_LATENCY_MS;
+  priv->latency_ns = priv->latency_ms * GST_MSECOND;
+  priv->drop_on_latency = DEFAULT_DROP_ON_LATENCY;
+  priv->do_lost = DEFAULT_DO_LOST;
+  priv->do_retransmission = DEFAULT_DO_RETRANSMISSION;
+  priv->rtx_delay = DEFAULT_RTX_DELAY;
+  priv->rtx_delay_reorder = DEFAULT_RTX_DELAY_REORDER;
+  priv->rtx_retry_timeout = DEFAULT_RTX_RETRY_TIMEOUT;
+  priv->rtx_retry_period = DEFAULT_RTX_RETRY_PERIOD;
+
+  priv->last_dts = -1;
+  priv->last_rtptime = -1;
+  priv->avg_jitter = 0;
+  priv->timers = g_array_new (FALSE, TRUE, sizeof (TimerData));
+  priv->jbuf = wfd_rtp_buffer_new ();
+  g_mutex_init (&priv->jbuf_lock);
+  g_cond_init (&priv->jbuf_timer);
+  g_cond_init (&priv->jbuf_event);
+  g_cond_init (&priv->jbuf_query);
+
+  /* reset skew detection initialy */
+  wfd_rtp_buffer_reset_skew (priv->jbuf);
+  wfd_rtp_buffer_set_delay (priv->jbuf, priv->latency_ns);
+  wfd_rtp_buffer_set_buffering (priv->jbuf, FALSE);
+  priv->active = TRUE;
+
+  priv->srcpad =
+      gst_pad_new_from_static_template (&gst_wfd_rtp_buffer_src_template,
+      "src");
+
+  gst_pad_set_activatemode_function (priv->srcpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_src_activate_mode));
+  gst_pad_set_query_function (priv->srcpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_src_query));
+  gst_pad_set_event_function (priv->srcpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_src_event));
+
+  priv->sinkpad =
+      gst_pad_new_from_static_template (&gst_wfd_rtp_buffer_sink_template,
+      "sink");
+
+  gst_pad_set_chain_function (priv->sinkpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_chain));
+  gst_pad_set_event_function (priv->sinkpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_sink_event));
+  gst_pad_set_query_function (priv->sinkpad,
+      GST_DEBUG_FUNCPTR (gst_wfd_rtp_buffer_sink_query));
+
+  gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->srcpad);
+  gst_element_add_pad (GST_ELEMENT (jitterbuffer), priv->sinkpad);
+
+  GST_OBJECT_FLAG_SET (jitterbuffer, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
+}
+
+#define IS_DROPABLE(it) (((it)->type == ITEM_TYPE_BUFFER) || ((it)->type == ITEM_TYPE_LOST))
+
+#define ITEM_TYPE_BUFFER        0
+#define ITEM_TYPE_LOST          1
+#define ITEM_TYPE_EVENT         2
+#define ITEM_TYPE_QUERY         3
+
+static WfdRTPBufferItem *
+alloc_item (gpointer data, guint type, GstClockTime dts, GstClockTime pts,
+    guint seqnum, guint count, guint rtptime)
+{
+  WfdRTPBufferItem *item;
+
+  item = g_slice_new (WfdRTPBufferItem);
+  item->data = data;
+  item->next = NULL;
+  item->prev = NULL;
+  item->type = type;
+  item->dts = dts;
+  item->pts = pts;
+  item->seqnum = seqnum;
+  item->count = count;
+  item->rtptime = rtptime;
+
+  return item;
+}
+
+static void
+free_item (WfdRTPBufferItem * item)
+{
+  if (item && item->data && item->type != ITEM_TYPE_QUERY)
+    gst_mini_object_unref (item->data);
+  g_slice_free (WfdRTPBufferItem, item);
+}
+
+static void
+gst_wfd_rtp_buffer_finalize (GObject * object)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (object);
+  priv = jitterbuffer->priv;
+
+  g_array_free (priv->timers, TRUE);
+  g_mutex_clear (&priv->jbuf_lock);
+  g_cond_clear (&priv->jbuf_timer);
+  g_cond_clear (&priv->jbuf_event);
+  g_cond_clear (&priv->jbuf_query);
+
+  wfd_rtp_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
+  g_object_unref (priv->jbuf);
+
+  G_OBJECT_CLASS (parent_class)->finalize (object);
+}
+
+static GstIterator *
+gst_wfd_rtp_buffer_iterate_internal_links (GstPad * pad, GstObject * parent)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstPad *otherpad = NULL;
+  GstIterator *it = NULL;
+  GValue val = { 0, };
+
+  jitterbuffer = GST_WFD_RTP_BUFFER_CAST (parent);
+
+  if (pad == jitterbuffer->priv->sinkpad) {
+    otherpad = jitterbuffer->priv->srcpad;
+  } else if (pad == jitterbuffer->priv->srcpad) {
+    otherpad = jitterbuffer->priv->sinkpad;
+  } else if (pad == jitterbuffer->priv->rtcpsinkpad) {
+    it = gst_iterator_new_single (GST_TYPE_PAD, NULL);
+  }
+
+  if (it == NULL) {
+    g_value_init (&val, GST_TYPE_PAD);
+    g_value_set_object (&val, otherpad);
+    it = gst_iterator_new_single (GST_TYPE_PAD, &val);
+    g_value_unset (&val);
+  }
+
+  return it;
+}
+
+static GstPad *
+create_rtcp_sink (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "creating RTCP sink pad");
+
+  priv->rtcpsinkpad =
+      gst_pad_new_from_static_template
+      (&gst_wfd_rtp_buffer_sink_rtcp_template, "sink_rtcp");
+  gst_pad_set_chain_function (priv->rtcpsinkpad,
+      gst_wfd_rtp_buffer_chain_rtcp);
+  gst_pad_set_event_function (priv->rtcpsinkpad,
+      (GstPadEventFunction) gst_wfd_rtp_buffer_sink_rtcp_event);
+  gst_pad_set_iterate_internal_links_function (priv->rtcpsinkpad,
+      gst_wfd_rtp_buffer_iterate_internal_links);
+  gst_pad_set_active (priv->rtcpsinkpad, TRUE);
+  gst_element_add_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
+
+  return priv->rtcpsinkpad;
+}
+
+static void
+remove_rtcp_sink (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "removing RTCP sink pad");
+
+  gst_pad_set_active (priv->rtcpsinkpad, FALSE);
+
+  gst_element_remove_pad (GST_ELEMENT_CAST (jitterbuffer), priv->rtcpsinkpad);
+  priv->rtcpsinkpad = NULL;
+}
+
+static GstPad *
+gst_wfd_rtp_buffer_request_new_pad (GstElement * element,
+    GstPadTemplate * templ, const gchar * name, const GstCaps * filter)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstElementClass *klass;
+  GstPad *result;
+  GstWfdRTPBufferPrivate *priv;
+
+  g_return_val_if_fail (templ != NULL, NULL);
+  g_return_val_if_fail (GST_IS_WFD_RTP_BUFFER (element), NULL);
+
+  jitterbuffer = GST_WFD_RTP_BUFFER_CAST (element);
+  priv = jitterbuffer->priv;
+  klass = GST_ELEMENT_GET_CLASS (element);
+
+  GST_DEBUG_OBJECT (element, "requesting pad %s", GST_STR_NULL (name));
+
+  /* figure out the template */
+  if (templ == gst_element_class_get_pad_template (klass, "sink_rtcp")) {
+    if (priv->rtcpsinkpad != NULL)
+      goto exists;
+
+    result = create_rtcp_sink (jitterbuffer);
+  } else
+    goto wrong_template;
+
+  return result;
+
+  /* ERRORS */
+wrong_template:
+  {
+    g_warning ("wfdrtpbuffer: this is not our template");
+    return NULL;
+  }
+exists:
+  {
+    g_warning ("wfdrtpbuffer: pad already requested");
+    return NULL;
+  }
+}
+
+static void
+gst_wfd_rtp_buffer_release_pad (GstElement * element, GstPad * pad)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  g_return_if_fail (GST_IS_WFD_RTP_BUFFER (element));
+  g_return_if_fail (GST_IS_PAD (pad));
+
+  jitterbuffer = GST_WFD_RTP_BUFFER_CAST (element);
+  priv = jitterbuffer->priv;
+
+  GST_DEBUG_OBJECT (element, "releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
+
+  if (priv->rtcpsinkpad == pad) {
+    remove_rtcp_sink (jitterbuffer);
+  } else
+    goto wrong_pad;
+
+  return;
+
+  /* ERRORS */
+wrong_pad:
+  {
+    g_warning ("wfdrtpbuffer: asked to release an unknown pad");
+    return;
+  }
+}
+
+static GstClock *
+gst_wfd_rtp_buffer_provide_clock (GstElement * element)
+{
+  return gst_system_clock_obtain ();
+}
+
+static void
+gst_wfd_rtp_buffer_clear_pt_map (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  /* this will trigger a new pt-map request signal, FIXME, do something better. */
+
+  JBUF_LOCK (priv);
+  priv->clock_rate = -1;
+  /* do not clear current content, but refresh state for new arrival */
+  GST_DEBUG_OBJECT (jitterbuffer, "reset jitterbuffer");
+  wfd_rtp_buffer_reset_skew (priv->jbuf);
+  JBUF_UNLOCK (priv);
+}
+
+static GstClockTime
+gst_wfd_rtp_buffer_set_active (GstWfdRTPBuffer * jbuf, gboolean active,
+    guint64 offset)
+{
+  GstWfdRTPBufferPrivate *priv;
+  GstClockTime last_out;
+  WfdRTPBufferItem *item;
+
+  priv = jbuf->priv;
+
+  JBUF_LOCK (priv);
+  GST_DEBUG_OBJECT (jbuf, "setting active %d with offset %" GST_TIME_FORMAT,
+      active, GST_TIME_ARGS (offset));
+
+  if (active != priv->active) {
+    /* add the amount of time spent in paused to the output offset. All
+     * outgoing buffers will have this offset applied to their timestamps in
+     * order to make them arrive in time in the sink. */
+    priv->out_offset = offset;
+    GST_DEBUG_OBJECT (jbuf, "out offset %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (priv->out_offset));
+    priv->active = active;
+    JBUF_SIGNAL_EVENT (priv);
+  }
+  if (!active) {
+    wfd_rtp_buffer_set_buffering (priv->jbuf, TRUE);
+  }
+  if ((item = wfd_rtp_buffer_peek (priv->jbuf))) {
+    /* head buffer timestamp and offset gives our output time */
+    last_out = item->dts + priv->ts_offset;
+  } else {
+    /* use last known time when the buffer is empty */
+    last_out = priv->last_out_time;
+  }
+  JBUF_UNLOCK (priv);
+
+  return last_out;
+}
+
+static GstCaps *
+gst_wfd_rtp_buffer_getcaps (GstPad * pad, GstCaps * filter)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+  GstPad *other;
+  GstCaps *caps;
+  GstCaps *templ;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (gst_pad_get_parent (pad));
+  priv = jitterbuffer->priv;
+
+  other = (pad == priv->srcpad ? priv->sinkpad : priv->srcpad);
+
+  caps = gst_pad_peer_query_caps (other, filter);
+
+  templ = gst_pad_get_pad_template_caps (pad);
+  if (caps == NULL) {
+    GST_DEBUG_OBJECT (jitterbuffer, "use template");
+    caps = templ;
+  } else {
+    GstCaps *intersect;
+
+    GST_DEBUG_OBJECT (jitterbuffer, "intersect with template");
+
+    intersect = gst_caps_intersect (caps, templ);
+    gst_caps_unref (caps);
+    gst_caps_unref (templ);
+
+    caps = intersect;
+  }
+  gst_object_unref (jitterbuffer);
+
+  return caps;
+}
+
+/*
+ * Must be called with JBUF_LOCK held
+ */
+
+static gboolean
+gst_wfd_rtp_buffer_sink_parse_caps (GstWfdRTPBuffer * jitterbuffer,
+    GstCaps * caps)
+{
+  GstWfdRTPBufferPrivate *priv;
+  GstStructure *caps_struct;
+  guint val;
+  GstClockTime tval;
+
+  priv = jitterbuffer->priv;
+
+  /* first parse the caps */
+  caps_struct = gst_caps_get_structure (caps, 0);
+
+  GST_DEBUG_OBJECT (jitterbuffer, "got caps");
+
+  /* we need a clock-rate to convert the rtp timestamps to GStreamer time and to
+   * measure the amount of data in the buffer */
+  if (!gst_structure_get_int (caps_struct, "clock-rate", &priv->clock_rate))
+    goto error;
+
+  if (priv->clock_rate <= 0)
+    goto wrong_rate;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "got clock-rate %d", priv->clock_rate);
+
+  wfd_rtp_buffer_set_clock_rate (priv->jbuf, priv->clock_rate);
+
+  /* The clock base is the RTP timestamp corrsponding to the npt-start value. We
+   * can use this to track the amount of time elapsed on the sender. */
+  if (gst_structure_get_uint (caps_struct, "clock-base", &val))
+    priv->clock_base = val;
+  else
+    priv->clock_base = -1;
+
+  priv->ext_timestamp = priv->clock_base;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "got clock-base %" G_GINT64_FORMAT,
+      priv->clock_base);
+
+  if (gst_structure_get_uint (caps_struct, "seqnum-base", &val)) {
+    /* first expected seqnum, only update when we didn't have a previous base. */
+    if (priv->next_in_seqnum == -1)
+      priv->next_in_seqnum = val;
+    if (priv->next_seqnum == -1) {
+      priv->next_seqnum = val;
+      JBUF_SIGNAL_EVENT (priv);
+    }
+  }
+
+  GST_DEBUG_OBJECT (jitterbuffer, "got seqnum-base %d", priv->next_in_seqnum);
+
+  /* the start and stop times. The seqnum-base corresponds to the start time. We
+   * will keep track of the seqnums on the output and when we reach the one
+   * corresponding to npt-stop, we emit the npt-stop-reached signal */
+  if (gst_structure_get_clock_time (caps_struct, "npt-start", &tval))
+    priv->npt_start = tval;
+  else
+    priv->npt_start = 0;
+
+  if (gst_structure_get_clock_time (caps_struct, "npt-stop", &tval))
+    priv->npt_stop = tval;
+  else
+    priv->npt_stop = -1;
+
+  GST_DEBUG_OBJECT (jitterbuffer,
+      "npt start/stop: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
+      GST_TIME_ARGS (priv->npt_start), GST_TIME_ARGS (priv->npt_stop));
+
+  return TRUE;
+
+  /* ERRORS */
+error:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "No clock-rate in caps!");
+    return FALSE;
+  }
+wrong_rate:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "Invalid clock-rate %d", priv->clock_rate);
+    return FALSE;
+  }
+}
+
+static void
+gst_wfd_rtp_buffer_flush_start (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  JBUF_LOCK (priv);
+  /* mark ourselves as flushing */
+  priv->srcresult = GST_FLOW_FLUSHING;
+  GST_DEBUG_OBJECT (jitterbuffer, "Disabling pop on queue");
+  /* this unblocks any waiting pops on the src pad task */
+  JBUF_SIGNAL_EVENT (priv);
+  JBUF_SIGNAL_QUERY (priv, FALSE);
+  JBUF_UNLOCK (priv);
+}
+
+static void
+gst_wfd_rtp_buffer_flush_stop (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  JBUF_LOCK (priv);
+  GST_DEBUG_OBJECT (jitterbuffer, "Enabling pop on queue");
+  /* Mark as non flushing */
+  priv->srcresult = GST_FLOW_OK;
+  gst_segment_init (&priv->segment, GST_FORMAT_TIME);
+  priv->last_popped_seqnum = -1;
+  priv->last_out_time = -1;
+  priv->next_seqnum = -1;
+  priv->ips_rtptime = -1;
+  priv->ips_dts = GST_CLOCK_TIME_NONE;
+  priv->packet_spacing = 0;
+  priv->next_in_seqnum = -1;
+  priv->clock_rate = -1;
+  priv->last_pt = -1;
+  priv->eos = FALSE;
+  priv->estimated_eos = -1;
+  priv->last_elapsed = 0;
+  priv->ext_timestamp = -1;
+  priv->avg_jitter = 0;
+  priv->last_dts = -1;
+  priv->last_rtptime = -1;
+  GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
+  wfd_rtp_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
+  wfd_rtp_buffer_disable_buffering (priv->jbuf, FALSE);
+  wfd_rtp_buffer_reset_skew (priv->jbuf);
+  remove_all_timers (jitterbuffer);
+  JBUF_UNLOCK (priv);
+}
+
+static gboolean
+gst_wfd_rtp_buffer_src_activate_mode (GstPad * pad, GstObject * parent,
+    GstPadMode mode, gboolean active)
+{
+  gboolean result;
+  GstWfdRTPBuffer *jitterbuffer = NULL;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (parent);
+
+  switch (mode) {
+    case GST_PAD_MODE_PUSH:
+      if (active) {
+        /* allow data processing */
+        gst_wfd_rtp_buffer_flush_stop (jitterbuffer);
+
+        /* start pushing out buffers */
+        GST_DEBUG_OBJECT (jitterbuffer, "Starting task on srcpad");
+        result = gst_pad_start_task (jitterbuffer->priv->srcpad,
+            (GstTaskFunction) gst_wfd_rtp_buffer_loop, jitterbuffer, NULL);
+      } else {
+        /* make sure all data processing stops ASAP */
+        gst_wfd_rtp_buffer_flush_start (jitterbuffer);
+
+        /* NOTE this will hardlock if the state change is called from the src pad
+         * task thread because we will _join() the thread. */
+        GST_DEBUG_OBJECT (jitterbuffer, "Stopping task on srcpad");
+        result = gst_pad_stop_task (pad);
+      }
+      break;
+    default:
+      result = FALSE;
+      break;
+  }
+  return result;
+}
+
+static GstStateChangeReturn
+gst_wfd_rtp_buffer_change_state (GstElement * element,
+    GstStateChange transition)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (element);
+  priv = jitterbuffer->priv;
+
+  switch (transition) {
+    case GST_STATE_CHANGE_NULL_TO_READY:
+      break;
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      JBUF_LOCK (priv);
+      /* reset negotiated values */
+      priv->clock_rate = -1;
+      priv->clock_base = -1;
+      priv->peer_latency = 0;
+      priv->last_pt = -1;
+      /* block until we go to PLAYING */
+      priv->blocked = TRUE;
+      priv->timer_running = TRUE;
+      priv->timer_thread =
+          g_thread_new ("timer", (GThreadFunc) wait_next_timeout, jitterbuffer);
+      JBUF_UNLOCK (priv);
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      JBUF_LOCK (priv);
+      /* unblock to allow streaming in PLAYING */
+      priv->blocked = FALSE;
+      JBUF_SIGNAL_EVENT (priv);
+      JBUF_SIGNAL_TIMER (priv);
+      JBUF_UNLOCK (priv);
+      break;
+    default:
+      break;
+  }
+
+  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      /* we are a live element because we sync to the clock, which we can only
+       * do in the PLAYING state */
+      if (ret != GST_STATE_CHANGE_FAILURE)
+        ret = GST_STATE_CHANGE_NO_PREROLL;
+      break;
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+      JBUF_LOCK (priv);
+      /* block to stop streaming when PAUSED */
+      priv->blocked = TRUE;
+      unschedule_current_timer (jitterbuffer);
+      JBUF_UNLOCK (priv);
+      if (ret != GST_STATE_CHANGE_FAILURE)
+        ret = GST_STATE_CHANGE_NO_PREROLL;
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      JBUF_LOCK (priv);
+      gst_buffer_replace (&priv->last_sr, NULL);
+      priv->timer_running = FALSE;
+      unschedule_current_timer (jitterbuffer);
+      JBUF_SIGNAL_TIMER (priv);
+      JBUF_SIGNAL_QUERY (priv, FALSE);
+      JBUF_UNLOCK (priv);
+      g_thread_join (priv->timer_thread);
+      priv->timer_thread = NULL;
+      break;
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      break;
+    default:
+      break;
+  }
+
+  return ret;
+}
+
+static gboolean
+gst_wfd_rtp_buffer_src_event (GstPad * pad, GstObject * parent,
+    GstEvent * event)
+{
+  gboolean ret = TRUE;
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER_CAST (parent);
+  priv = jitterbuffer->priv;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_LATENCY:
+    {
+      GstClockTime latency;
+
+      gst_event_parse_latency (event, &latency);
+
+      GST_DEBUG_OBJECT (jitterbuffer,
+          "configuring latency of %" GST_TIME_FORMAT, GST_TIME_ARGS (latency));
+
+      JBUF_LOCK (priv);
+      /* adjust the overall buffer delay to the total pipeline latency in
+       * buffering mode because if downstream consumes too fast (because of
+       * large latency or queues, we would start rebuffering again. */
+      if (wfd_rtp_buffer_get_mode (priv->jbuf) ==
+          WFD_RTP_BUFFER_MODE_BUFFER) {
+        wfd_rtp_buffer_set_delay (priv->jbuf, latency);
+      }
+      JBUF_UNLOCK (priv);
+
+      ret = gst_pad_push_event (priv->sinkpad, event);
+      break;
+    }
+    default:
+      ret = gst_pad_push_event (priv->sinkpad, event);
+      break;
+  }
+
+  return ret;
+}
+
+/* handles and stores the event in the jitterbuffer, must be called with
+ * LOCK */
+static gboolean
+queue_event (GstWfdRTPBuffer * jitterbuffer, GstEvent * event)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  WfdRTPBufferItem *item;
+  gboolean head;
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_CAPS:
+    {
+      GstCaps *caps;
+
+      gst_event_parse_caps (event, &caps);
+      if (!gst_wfd_rtp_buffer_sink_parse_caps (jitterbuffer, caps))
+        goto wrong_caps;
+
+      break;
+    }
+    case GST_EVENT_SEGMENT:
+      gst_event_copy_segment (event, &priv->segment);
+
+      /* we need time for now */
+      if (priv->segment.format != GST_FORMAT_TIME)
+        goto newseg_wrong_format;
+
+      GST_DEBUG_OBJECT (jitterbuffer,
+          "newsegment:  %" GST_SEGMENT_FORMAT, &priv->segment);
+      break;
+    case GST_EVENT_EOS:
+      priv->eos = TRUE;
+      wfd_rtp_buffer_disable_buffering (priv->jbuf, TRUE);
+      break;
+    default:
+      break;
+  }
+
+
+  GST_DEBUG_OBJECT (jitterbuffer, "adding event");
+  item = alloc_item (event, ITEM_TYPE_EVENT, -1, -1, -1, 0, -1);
+  wfd_rtp_buffer_insert (priv->jbuf, item, &head, NULL);
+  if (head)
+    JBUF_SIGNAL_EVENT (priv);
+
+  return TRUE;
+
+  /* ERRORS */
+wrong_caps:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "received invalid caps");
+    gst_event_unref (event);
+    return FALSE;
+  }
+newseg_wrong_format:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "received non TIME newsegment");
+    gst_event_unref (event);
+    return FALSE;
+  }
+}
+
+static gboolean
+gst_wfd_rtp_buffer_sink_event (GstPad * pad, GstObject * parent,
+    GstEvent * event)
+{
+  gboolean ret = TRUE;
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (parent);
+  priv = jitterbuffer->priv;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_CUSTOM_DOWNSTREAM:{
+      const GstStructure *structure;
+
+      structure = gst_event_get_structure (event);
+      if (gst_structure_has_name (structure, "GstWFDEvent")) {
+        gboolean reset = FALSE;
+        gst_structure_get_boolean (structure, "reset", &reset);
+        if (reset) {
+          JBUF_LOCK (priv);
+          GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
+          gst_segment_init (&priv->segment, GST_FORMAT_TIME);
+          priv->last_popped_seqnum = -1;
+          priv->last_out_time = -1;
+          priv->next_seqnum = -1;
+          priv->ips_rtptime = -1;
+          priv->ips_dts = GST_CLOCK_TIME_NONE;
+          priv->packet_spacing = 0;
+          priv->next_in_seqnum = -1;
+          priv->clock_rate = -1;
+          priv->last_pt = -1;
+          priv->eos = FALSE;
+          priv->estimated_eos = -1;
+          priv->last_elapsed = 0;
+          priv->ext_timestamp = -1;
+          priv->avg_jitter = 0;
+          priv->last_dts = -1;
+          priv->last_rtptime = -1;
+          GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
+          wfd_rtp_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
+          wfd_rtp_buffer_disable_buffering (priv->jbuf, FALSE);
+          wfd_rtp_buffer_reset_skew (priv->jbuf);
+          remove_all_timers (jitterbuffer);
+          JBUF_SIGNAL_EVENT (priv);
+          JBUF_UNLOCK (priv);
+        }
+      }
+      ret = gst_pad_event_default (pad, parent, event);
+      break;
+    }
+    case GST_EVENT_FLUSH_START:
+      ret = gst_pad_push_event (priv->srcpad, event);
+      gst_wfd_rtp_buffer_flush_start (jitterbuffer);
+      /* wait for the loop to go into PAUSED */
+      gst_pad_pause_task (priv->srcpad);
+      break;
+    case GST_EVENT_FLUSH_STOP:
+      ret = gst_pad_push_event (priv->srcpad, event);
+      ret =
+          gst_wfd_rtp_buffer_src_activate_mode (priv->srcpad, parent,
+          GST_PAD_MODE_PUSH, TRUE);
+      break;
+    default:
+      if (GST_EVENT_IS_SERIALIZED (event)) {
+        /* serialized events go in the queue */
+        JBUF_LOCK (priv);
+        if (priv->srcresult != GST_FLOW_OK) {
+          /* Errors in sticky event pushing are no problem and ignored here
+           * as they will cause more meaningful errors during data flow.
+           * For EOS events, that are not followed by data flow, we still
+           * return FALSE here though.
+           */
+          if (!GST_EVENT_IS_STICKY (event) ||
+              GST_EVENT_TYPE (event) == GST_EVENT_EOS)
+            goto out_flow_error;
+        }
+        /* refuse more events on EOS */
+        if (priv->eos)
+          goto out_eos;
+        ret = queue_event (jitterbuffer, event);
+        JBUF_UNLOCK (priv);
+      } else {
+        /* non-serialized events are forwarded downstream immediately */
+        ret = gst_pad_push_event (priv->srcpad, event);
+      }
+      break;
+  }
+  return ret;
+
+  /* ERRORS */
+out_flow_error:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer,
+        "refusing event, we have a downstream flow error: %s",
+        gst_flow_get_name (priv->srcresult));
+    JBUF_UNLOCK (priv);
+    gst_event_unref (event);
+    return FALSE;
+  }
+out_eos:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "refusing event, we are EOS");
+    JBUF_UNLOCK (priv);
+    gst_event_unref (event);
+    return FALSE;
+  }
+}
+
+static gboolean
+gst_wfd_rtp_buffer_sink_rtcp_event (GstPad * pad, GstObject * parent,
+    GstEvent * event)
+{
+  gboolean ret = TRUE;
+  GstWfdRTPBuffer *jitterbuffer;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (parent);
+
+  GST_DEBUG_OBJECT (jitterbuffer, "received %s", GST_EVENT_TYPE_NAME (event));
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_FLUSH_START:
+      gst_event_unref (event);
+      break;
+    case GST_EVENT_FLUSH_STOP:
+      gst_event_unref (event);
+      break;
+    default:
+      ret = gst_pad_event_default (pad, parent, event);
+      break;
+  }
+
+  return ret;
+}
+
+/*
+ * Must be called with JBUF_LOCK held, will release the LOCK when emiting the
+ * signal. The function returns GST_FLOW_ERROR when a parsing error happened and
+ * GST_FLOW_FLUSHING when the element is shutting down. On success
+ * GST_FLOW_OK is returned.
+ */
+static GstFlowReturn
+gst_wfd_rtp_buffer_get_clock_rate (GstWfdRTPBuffer * jitterbuffer,
+    guint8 pt)
+{
+  GValue ret = { 0 };
+  GValue args[2] = { {0}, {0} };
+  GstCaps *caps;
+  gboolean res;
+
+  g_value_init (&args[0], GST_TYPE_ELEMENT);
+  g_value_set_object (&args[0], jitterbuffer);
+  g_value_init (&args[1], G_TYPE_UINT);
+  g_value_set_uint (&args[1], pt);
+
+  g_value_init (&ret, GST_TYPE_CAPS);
+  g_value_set_boxed (&ret, NULL);
+
+  JBUF_UNLOCK (jitterbuffer->priv);
+  g_signal_emitv (args, gst_wfd_rtp_buffer_signals[SIGNAL_REQUEST_PT_MAP], 0,
+      &ret);
+  JBUF_LOCK_CHECK (jitterbuffer->priv, out_flushing);
+
+  g_value_unset (&args[0]);
+  g_value_unset (&args[1]);
+  caps = (GstCaps *) g_value_dup_boxed (&ret);
+  g_value_unset (&ret);
+  if (!caps)
+    goto no_caps;
+
+  res = gst_wfd_rtp_buffer_sink_parse_caps (jitterbuffer, caps);
+  gst_caps_unref (caps);
+
+  if (G_UNLIKELY (!res))
+    goto parse_failed;
+
+  return GST_FLOW_OK;
+
+  /* ERRORS */
+no_caps:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "could not get caps");
+    return GST_FLOW_ERROR;
+  }
+out_flushing:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
+    return GST_FLOW_FLUSHING;
+  }
+parse_failed:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "parse failed");
+    return GST_FLOW_ERROR;
+  }
+}
+
+/* call with jbuf lock held */
+static GstMessage *
+check_buffering_percent (GstWfdRTPBuffer * jitterbuffer, gint percent)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstMessage *message = NULL;
+
+  if (percent == -1)
+    return NULL;
+
+  /* Post a buffering message */
+  if (priv->last_percent != percent) {
+    priv->last_percent = percent;
+    message =
+        gst_message_new_buffering (GST_OBJECT_CAST (jitterbuffer), percent);
+    gst_message_set_buffering_stats (message, GST_BUFFERING_LIVE, -1, -1, -1);
+  }
+
+  return message;
+}
+
+static GstClockTime
+apply_offset (GstWfdRTPBuffer * jitterbuffer, GstClockTime timestamp)
+{
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  if (timestamp == -1)
+    return -1;
+
+  /* apply the timestamp offset, this is used for inter stream sync */
+  timestamp += priv->ts_offset;
+  /* add the offset, this is used when buffering */
+  timestamp += priv->out_offset;
+
+  return timestamp;
+}
+
+static TimerData *
+find_timer (GstWfdRTPBuffer * jitterbuffer, TimerType type, guint16 seqnum)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  TimerData *timer = NULL;
+  gint i, len;
+
+  len = priv->timers->len;
+  for (i = 0; i < len; i++) {
+    TimerData *test = &g_array_index (priv->timers, TimerData, i);
+    if (test->seqnum == seqnum && test->type == type) {
+      timer = test;
+      break;
+    }
+  }
+  return timer;
+}
+
+static void
+unschedule_current_timer (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+
+  if (priv->clock_id) {
+    GST_DEBUG_OBJECT (jitterbuffer, "unschedule current timer");
+    gst_clock_id_unschedule (priv->clock_id);
+    priv->clock_id = NULL;
+  }
+}
+
+static GstClockTime
+get_timeout (GstWfdRTPBuffer * jitterbuffer, TimerData * timer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstClockTime test_timeout;
+
+  if ((test_timeout = timer->timeout) == -1)
+    return -1;
+
+  if (timer->type != TIMER_TYPE_EXPECTED) {
+    /* add our latency and offset to get output times. */
+    test_timeout = apply_offset (jitterbuffer, test_timeout);
+    test_timeout += priv->latency_ns;
+  }
+  return test_timeout;
+}
+
+static void
+recalculate_timer (GstWfdRTPBuffer * jitterbuffer, TimerData * timer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+
+  if (priv->clock_id) {
+    GstClockTime timeout = get_timeout (jitterbuffer, timer);
+
+    GST_DEBUG ("%" GST_TIME_FORMAT " <> %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (timeout), GST_TIME_ARGS (priv->timer_timeout));
+
+    if (timeout == -1 || timeout < priv->timer_timeout)
+      unschedule_current_timer (jitterbuffer);
+  }
+}
+
+static TimerData *
+add_timer (GstWfdRTPBuffer * jitterbuffer, TimerType type,
+    guint16 seqnum, guint num, GstClockTime timeout, GstClockTime delay,
+    GstClockTime duration)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  TimerData *timer;
+  gint len;
+
+  GST_DEBUG_OBJECT (jitterbuffer,
+      "add timer %d for seqnum %d to %" GST_TIME_FORMAT ", delay %"
+      GST_TIME_FORMAT, type, seqnum, GST_TIME_ARGS (timeout),
+      GST_TIME_ARGS (delay));
+
+  len = priv->timers->len;
+  g_array_set_size (priv->timers, len + 1);
+  timer = &g_array_index (priv->timers, TimerData, len);
+  timer->idx = len;
+  timer->type = type;
+  timer->seqnum = seqnum;
+  timer->num = num;
+  timer->timeout = timeout + delay;
+  timer->duration = duration;
+  if (type == TIMER_TYPE_EXPECTED) {
+    timer->rtx_base = timeout;
+    timer->rtx_delay = delay;
+    timer->rtx_retry = 0;
+  }
+  timer->num_rtx_retry = 0;
+  recalculate_timer (jitterbuffer, timer);
+  JBUF_SIGNAL_TIMER (priv);
+
+  return timer;
+}
+
+static void
+reschedule_timer (GstWfdRTPBuffer * jitterbuffer, TimerData * timer,
+    guint16 seqnum, GstClockTime timeout, GstClockTime delay, gboolean reset)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  gboolean seqchange, timechange;
+  guint16 oldseq;
+
+  seqchange = timer->seqnum != seqnum;
+  timechange = timer->timeout != timeout;
+
+  if (!seqchange && !timechange)
+    return;
+
+  oldseq = timer->seqnum;
+
+  GST_DEBUG_OBJECT (jitterbuffer,
+      "replace timer for seqnum %d->%d to %" GST_TIME_FORMAT,
+      oldseq, seqnum, GST_TIME_ARGS (timeout + delay));
+
+  timer->timeout = timeout + delay;
+  timer->seqnum = seqnum;
+  if (reset) {
+    timer->rtx_base = timeout;
+    timer->rtx_delay = delay;
+    timer->rtx_retry = 0;
+  }
+  if (seqchange)
+    timer->num_rtx_retry = 0;
+
+  if (priv->clock_id) {
+    /* we changed the seqnum and there is a timer currently waiting with this
+     * seqnum, unschedule it */
+    if (seqchange && priv->timer_seqnum == oldseq)
+      unschedule_current_timer (jitterbuffer);
+    /* we changed the time, check if it is earlier than what we are waiting
+     * for and unschedule if so */
+    else if (timechange)
+      recalculate_timer (jitterbuffer, timer);
+  }
+}
+
+static TimerData *
+set_timer (GstWfdRTPBuffer * jitterbuffer, TimerType type,
+    guint16 seqnum, GstClockTime timeout)
+{
+  TimerData *timer;
+
+  /* find the seqnum timer */
+  timer = find_timer (jitterbuffer, type, seqnum);
+  if (timer == NULL) {
+    timer = add_timer (jitterbuffer, type, seqnum, 0, timeout, 0, -1);
+  } else {
+    reschedule_timer (jitterbuffer, timer, seqnum, timeout, 0, FALSE);
+  }
+  return timer;
+}
+
+static void
+remove_timer (GstWfdRTPBuffer * jitterbuffer, TimerData * timer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  guint idx;
+
+  if (priv->clock_id && priv->timer_seqnum == timer->seqnum)
+    unschedule_current_timer (jitterbuffer);
+
+  idx = timer->idx;
+  GST_DEBUG_OBJECT (jitterbuffer, "removed index %d", idx);
+  g_array_remove_index_fast (priv->timers, idx);
+  timer->idx = idx;
+}
+
+static void
+remove_all_timers (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GST_DEBUG_OBJECT (jitterbuffer, "removed all timers");
+  g_array_set_size (priv->timers, 0);
+  unschedule_current_timer (jitterbuffer);
+}
+
+/* we just received a packet with seqnum and dts.
+ *
+ * First check for old seqnum that we are still expecting. If the gap with the
+ * current seqnum is too big, unschedule the timeouts.
+ *
+ * If we have a valid packet spacing estimate we can set a timer for when we
+ * should receive the next packet.
+ * If we don't have a valid estimate, we remove any timer we might have
+ * had for this packet.
+ */
+static void
+update_timers (GstWfdRTPBuffer * jitterbuffer, guint16 seqnum,
+    GstClockTime dts, gboolean do_next_seqnum)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  TimerData *timer = NULL;
+  gint i, len;
+
+  /* go through all timers and unschedule the ones with a large gap, also find
+   * the timer for the seqnum */
+  len = priv->timers->len;
+  for (i = 0; i < len; i++) {
+    TimerData *test = &g_array_index (priv->timers, TimerData, i);
+    gint gap;
+
+    gap = gst_rtp_buffer_compare_seqnum (test->seqnum, seqnum);
+
+    GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, #%d<->#%d gap %d", i,
+        test->type, test->seqnum, seqnum, gap);
+
+    if (gap == 0) {
+      GST_DEBUG ("found timer for current seqnum");
+      /* the timer for the current seqnum */
+      timer = test;
+      /* when no retransmission, we can stop now, we only need to find the
+       * timer for the current seqnum */
+      if (!priv->do_retransmission)
+        break;
+    } else if (gap > priv->rtx_delay_reorder) {
+      /* max gap, we exceeded the max reorder distance and we don't expect the
+       * missing packet to be this reordered */
+      if (test->num_rtx_retry == 0 && test->type == TIMER_TYPE_EXPECTED)
+        reschedule_timer (jitterbuffer, test, test->seqnum, -1, 0, FALSE);
+    }
+  }
+
+  do_next_seqnum = do_next_seqnum && priv->packet_spacing > 0
+      && priv->do_retransmission;
+
+  if (timer && timer->type != TIMER_TYPE_DEADLINE) {
+    if (timer->num_rtx_retry > 0) {
+      GstClockTime rtx_last, delay;
+
+      /* we scheduled a retry for this packet and now we have it */
+      priv->num_rtx_success++;
+      /* all the previous retry attempts failed */
+      priv->num_rtx_failed += timer->num_rtx_retry - 1;
+      /* number of retries before receiving the packet */
+      if (priv->avg_rtx_num == 0.0)
+        priv->avg_rtx_num = timer->num_rtx_retry;
+      else
+        priv->avg_rtx_num = (timer->num_rtx_retry + 7 * priv->avg_rtx_num) / 8;
+      /* calculate the delay between retransmission request and receiving this
+       * packet, start with when we scheduled this timeout last */
+      rtx_last = timer->rtx_last;
+      if (dts != GST_CLOCK_TIME_NONE && dts > rtx_last) {
+        /* we have a valid delay if this packet arrived after we scheduled the
+         * request */
+        delay = dts - rtx_last;
+        if (priv->avg_rtx_rtt == 0)
+          priv->avg_rtx_rtt = delay;
+        else
+          priv->avg_rtx_rtt = (delay + 7 * priv->avg_rtx_rtt) / 8;
+      } else
+        delay = 0;
+
+      GST_LOG_OBJECT (jitterbuffer,
+          "RTX success %" G_GUINT64_FORMAT ", failed %" G_GUINT64_FORMAT
+          ", requests %" G_GUINT64_FORMAT ", dups %" G_GUINT64_FORMAT
+          ", avg-num %g, delay %" GST_TIME_FORMAT ", avg-rtt %" GST_TIME_FORMAT,
+          priv->num_rtx_success, priv->num_rtx_failed, priv->num_rtx_requests,
+          priv->num_duplicates, priv->avg_rtx_num, GST_TIME_ARGS (delay),
+          GST_TIME_ARGS (priv->avg_rtx_rtt));
+
+      /* don't try to estimate the next seqnum because this is a retransmitted
+       * packet and it probably did not arrive with the expected packet
+       * spacing. */
+      do_next_seqnum = FALSE;
+    }
+  }
+
+  if (do_next_seqnum) {
+    GstClockTime expected, delay;
+
+    /* calculate expected arrival time of the next seqnum */
+    expected = dts + priv->packet_spacing;
+
+    if (priv->rtx_delay == -1) {
+      if (priv->avg_jitter == 0)
+        delay = DEFAULT_AUTO_RTX_DELAY;
+      else
+        /* jitter is in nanoseconds, 2x jitter is a good margin */
+        delay = priv->avg_jitter * 2;
+    } else {
+      delay = priv->rtx_delay * GST_MSECOND;
+    }
+
+    /* and update/install timer for next seqnum */
+    if (timer)
+      reschedule_timer (jitterbuffer, timer, priv->next_in_seqnum, expected,
+          delay, TRUE);
+    else
+      add_timer (jitterbuffer, TIMER_TYPE_EXPECTED, priv->next_in_seqnum, 0,
+          expected, delay, priv->packet_spacing);
+  } else if (timer && timer->type != TIMER_TYPE_DEADLINE) {
+    /* if we had a timer, remove it, we don't know when to expect the next
+     * packet. */
+    remove_timer (jitterbuffer, timer);
+  }
+}
+
+static void
+calculate_packet_spacing (GstWfdRTPBuffer * jitterbuffer, guint32 rtptime,
+    GstClockTime dts)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+
+  /* we need consecutive seqnums with a different
+   * rtptime to estimate the packet spacing. */
+  if (priv->ips_rtptime != rtptime) {
+    /* rtptime changed, check dts diff */
+    if (priv->ips_dts != -1 && dts != -1 && dts > priv->ips_dts) {
+      priv->packet_spacing = dts - priv->ips_dts;
+      GST_DEBUG_OBJECT (jitterbuffer,
+          "new packet spacing %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (priv->packet_spacing));
+    }
+    priv->ips_rtptime = rtptime;
+    priv->ips_dts = dts;
+  }
+}
+
+static void
+calculate_expected (GstWfdRTPBuffer * jitterbuffer, guint32 expected,
+    guint16 seqnum, GstClockTime dts, gint gap)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstClockTime total_duration, duration, expected_dts;
+  TimerType type;
+
+  GST_DEBUG_OBJECT (jitterbuffer,
+      "dts %" GST_TIME_FORMAT ", last %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (dts), GST_TIME_ARGS (priv->last_in_dts));
+
+  /* the total duration spanned by the missing packets */
+  if (dts >= priv->last_in_dts)
+    total_duration = dts - priv->last_in_dts;
+  else
+    total_duration = 0;
+
+  /* interpolate between the current time and the last time based on
+   * number of packets we are missing, this is the estimated duration
+   * for the missing packet based on equidistant packet spacing. */
+  duration = total_duration / (gap + 1);
+
+  GST_DEBUG_OBJECT (jitterbuffer, "duration %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (duration));
+
+  if (total_duration > priv->latency_ns) {
+    GstClockTime gap_time;
+    guint lost_packets;
+
+    gap_time = total_duration - priv->latency_ns;
+
+    if (duration > 0) {
+      lost_packets = gap_time / duration;
+      gap_time = lost_packets * duration;
+    } else {
+      lost_packets = gap;
+    }
+
+    /* too many lost packets, some of the missing packets are already
+     * too late and we can generate lost packet events for them. */
+    GST_DEBUG_OBJECT (jitterbuffer, "too many lost packets %" GST_TIME_FORMAT
+        " > %" GST_TIME_FORMAT ", consider %u lost",
+        GST_TIME_ARGS (total_duration), GST_TIME_ARGS (priv->latency_ns),
+        lost_packets);
+
+    /* this timer will fire immediately and the lost event will be pushed from
+     * the timer thread */
+    add_timer (jitterbuffer, TIMER_TYPE_LOST, expected, lost_packets,
+        priv->last_in_dts + duration, 0, gap_time);
+
+    expected += lost_packets;
+    priv->last_in_dts += gap_time;
+  }
+
+  expected_dts = priv->last_in_dts + duration;
+
+  if (priv->do_retransmission) {
+    TimerData *timer;
+
+    type = TIMER_TYPE_EXPECTED;
+    /* if we had a timer for the first missing packet, update it. */
+    if ((timer = find_timer (jitterbuffer, type, expected))) {
+      GstClockTime timeout = timer->timeout;
+
+      timer->duration = duration;
+      if (timeout > expected_dts) {
+        GstClockTime delay = timeout - expected_dts - timer->rtx_retry;
+        reschedule_timer (jitterbuffer, timer, timer->seqnum, expected_dts,
+            delay, TRUE);
+      }
+      expected++;
+      expected_dts += duration;
+    }
+  } else {
+    type = TIMER_TYPE_LOST;
+  }
+
+  while (gst_rtp_buffer_compare_seqnum (expected, seqnum) > 0) {
+    add_timer (jitterbuffer, type, expected, 0, expected_dts, 0, duration);
+    expected_dts += duration;
+    expected++;
+  }
+}
+
+static void
+calculate_jitter (GstWfdRTPBuffer * jitterbuffer, GstClockTime dts,
+    guint rtptime)
+{
+  gint32 rtpdiff;
+  GstClockTimeDiff dtsdiff, rtpdiffns, diff;
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+
+  if (G_UNLIKELY (dts == GST_CLOCK_TIME_NONE) || priv->clock_rate <= 0)
+    goto no_time;
+
+  if (priv->last_dts != -1)
+    dtsdiff = dts - priv->last_dts;
+  else
+    dtsdiff = 0;
+
+  if (priv->last_rtptime != -1)
+    rtpdiff = rtptime - (guint32) priv->last_rtptime;
+  else
+    rtpdiff = 0;
+
+  priv->last_dts = dts;
+  priv->last_rtptime = rtptime;
+
+  if (rtpdiff > 0)
+    rtpdiffns =
+        gst_util_uint64_scale_int (rtpdiff, GST_SECOND, priv->clock_rate);
+  else
+    rtpdiffns =
+        -gst_util_uint64_scale_int (-rtpdiff, GST_SECOND, priv->clock_rate);
+
+  diff = ABS (dtsdiff - rtpdiffns);
+
+  /* jitter is stored in nanoseconds */
+  priv->avg_jitter = (diff + (15 * priv->avg_jitter)) >> 4;
+
+  GST_LOG_OBJECT (jitterbuffer,
+      "dtsdiff %" GST_TIME_FORMAT " rtptime %" GST_TIME_FORMAT
+      ", clock-rate %d, diff %" GST_TIME_FORMAT ", jitter: %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (dtsdiff), GST_TIME_ARGS (rtpdiffns), priv->clock_rate,
+      GST_TIME_ARGS (diff), GST_TIME_ARGS (priv->avg_jitter));
+
+  return;
+
+  /* ERRORS */
+no_time:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer,
+        "no dts or no clock-rate, can't calculate jitter");
+    return;
+  }
+}
+
+static GstFlowReturn
+gst_wfd_rtp_buffer_chain (GstPad * pad, GstObject * parent,
+    GstBuffer * buffer)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+  guint16 seqnum;
+  guint32 expected, rtptime;
+  GstFlowReturn ret = GST_FLOW_OK;
+  GstClockTime dts, pts;
+  guint64 latency_ts;
+  gboolean head;
+  gint percent = -1;
+  guint8 pt;
+  GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
+  gboolean do_next_seqnum = FALSE;
+  WfdRTPBufferItem *item;
+  GstMessage *msg = NULL;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER_CAST (parent);
+
+  priv = jitterbuffer->priv;
+
+  if (G_UNLIKELY (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp)))
+    goto invalid_buffer;
+
+  pt = gst_rtp_buffer_get_payload_type (&rtp);
+  seqnum = gst_rtp_buffer_get_seq (&rtp);
+  rtptime = gst_rtp_buffer_get_timestamp (&rtp);
+  gst_rtp_buffer_unmap (&rtp);
+
+  /* make sure we have PTS and DTS set */
+  pts = GST_BUFFER_PTS (buffer);
+  dts = GST_BUFFER_DTS (buffer);
+  if (dts == -1)
+    dts = pts;
+  else if (pts == -1)
+    pts = dts;
+
+  /* take the DTS of the buffer. This is the time when the packet was
+   * received and is used to calculate jitter and clock skew. We will adjust
+   * this DTS with the smoothed value after processing it in the
+   * jitterbuffer and assign it as the PTS. */
+  /* bring to running time */
+  dts = gst_segment_to_running_time (&priv->segment, GST_FORMAT_TIME, dts);
+
+  GST_DEBUG_OBJECT (jitterbuffer,
+      "Received packet #%d at time %" GST_TIME_FORMAT ", discont %d", seqnum,
+      GST_TIME_ARGS (dts), GST_BUFFER_IS_DISCONT (buffer));
+
+  JBUF_LOCK_CHECK (priv, out_flushing);
+
+  if (G_UNLIKELY (priv->last_pt != pt)) {
+    GstCaps *caps;
+
+    GST_DEBUG_OBJECT (jitterbuffer, "pt changed from %u to %u", priv->last_pt,
+        pt);
+
+    priv->last_pt = pt;
+    /* reset clock-rate so that we get a new one */
+    priv->clock_rate = -1;
+
+    /* Try to get the clock-rate from the caps first if we can. If there are no
+     * caps we must fire the signal to get the clock-rate. */
+    if ((caps = gst_pad_get_current_caps (pad))) {
+      gst_wfd_rtp_buffer_sink_parse_caps (jitterbuffer, caps);
+      gst_caps_unref (caps);
+    }
+  }
+
+  if (G_UNLIKELY (priv->clock_rate == -1)) {
+    /* no clock rate given on the caps, try to get one with the signal */
+    if (gst_wfd_rtp_buffer_get_clock_rate (jitterbuffer,
+            pt) == GST_FLOW_FLUSHING)
+      goto out_flushing;
+
+    if (G_UNLIKELY (priv->clock_rate == -1))
+      goto no_clock_rate;
+  }
+
+  /* don't accept more data on EOS */
+  if (G_UNLIKELY (priv->eos))
+    goto have_eos;
+
+  calculate_jitter (jitterbuffer, dts, rtptime);
+
+  expected = priv->next_in_seqnum;
+
+  /* now check against our expected seqnum */
+  if (G_LIKELY (expected != -1)) {
+    gint gap;
+
+    /* now calculate gap */
+    gap = gst_rtp_buffer_compare_seqnum (expected, seqnum);
+
+    GST_DEBUG_OBJECT (jitterbuffer, "expected #%d, got #%d, gap of %d",
+        expected, seqnum, gap);
+
+    if (G_LIKELY (gap == 0)) {
+      /* packet is expected */
+      calculate_packet_spacing (jitterbuffer, rtptime, dts);
+      do_next_seqnum = TRUE;
+    } else {
+      gboolean reset = FALSE;
+
+      if (gap < 0) {
+        /* we received an old packet */
+        if (G_UNLIKELY (gap < -RTP_MAX_MISORDER)) {
+          /* too old packet, reset */
+          GST_DEBUG_OBJECT (jitterbuffer, "reset: buffer too old %d < %d", gap,
+              -RTP_MAX_MISORDER);
+          reset = TRUE;
+        } else {
+          GST_DEBUG_OBJECT (jitterbuffer, "old packet received");
+        }
+      } else {
+        /* new packet, we are missing some packets */
+        if (G_UNLIKELY (gap > RTP_MAX_DROPOUT)) {
+          /* packet too far in future, reset */
+          GST_DEBUG_OBJECT (jitterbuffer, "reset: buffer too new %d > %d", gap,
+              RTP_MAX_DROPOUT);
+          reset = TRUE;
+        } else {
+          GST_DEBUG_OBJECT (jitterbuffer, "%d missing packets", gap);
+          /* fill in the gap with EXPECTED timers */
+          calculate_expected (jitterbuffer, expected, seqnum, dts, gap);
+
+          do_next_seqnum = TRUE;
+        }
+      }
+      if (G_UNLIKELY (reset)) {
+        GST_DEBUG_OBJECT (jitterbuffer, "flush and reset jitterbuffer");
+        wfd_rtp_buffer_flush (priv->jbuf, (GFunc) free_item, NULL);
+        wfd_rtp_buffer_reset_skew (priv->jbuf);
+        remove_all_timers (jitterbuffer);
+        priv->last_popped_seqnum = -1;
+        priv->next_seqnum = seqnum;
+        do_next_seqnum = TRUE;
+        JBUF_SIGNAL_EVENT (priv);
+      }
+      /* reset spacing estimation when gap */
+      priv->ips_rtptime = -1;
+      priv->ips_dts = GST_CLOCK_TIME_NONE;
+    }
+  } else {
+    GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
+    do_next_seqnum = TRUE;
+    /* take rtptime and dts to calculate packet spacing */
+    priv->ips_rtptime = rtptime;
+    priv->ips_dts = dts;
+  }
+  if (do_next_seqnum) {
+    priv->last_in_seqnum = seqnum;
+    priv->last_in_dts = dts;
+    priv->next_in_seqnum = (seqnum + 1) & 0xffff;
+  }
+
+  /* let's check if this buffer is too late, we can only accept packets with
+   * bigger seqnum than the one we last pushed. */
+  if (G_LIKELY (priv->last_popped_seqnum != -1)) {
+    gint gap;
+
+    gap = gst_rtp_buffer_compare_seqnum (priv->last_popped_seqnum, seqnum);
+
+    /* priv->last_popped_seqnum >= seqnum, we're too late. */
+    if (G_UNLIKELY (gap <= 0))
+      goto too_late;
+  }
+
+  /* let's drop oldest packet if the queue is already full and drop-on-latency
+   * is set. We can only do this when there actually is a latency. When no
+   * latency is set, we just pump it in the queue and let the other end push it
+   * out as fast as possible. */
+  if (priv->latency_ms && priv->drop_on_latency) {
+    latency_ts =
+        gst_util_uint64_scale_int (priv->latency_ms, priv->clock_rate, 1000);
+
+    if (G_UNLIKELY (wfd_rtp_buffer_get_ts_diff (priv->jbuf) >= latency_ts)) {
+      WfdRTPBufferItem *old_item;
+
+      old_item = wfd_rtp_buffer_peek (priv->jbuf);
+
+      if (IS_DROPABLE (old_item)) {
+        old_item = wfd_rtp_buffer_pop (priv->jbuf, &percent);
+        GST_DEBUG_OBJECT (jitterbuffer, "Queue full, dropping old packet %p",
+            old_item);
+        priv->next_seqnum = (old_item->seqnum + 1) & 0xffff;
+        free_item (old_item);
+      }
+      /* we might have removed some head buffers, signal the pushing thread to
+       * see if it can push now */
+      JBUF_SIGNAL_EVENT (priv);
+    }
+  }
+
+  item = alloc_item (buffer, ITEM_TYPE_BUFFER, dts, pts, seqnum, 1, rtptime);
+
+  /* now insert the packet into the queue in sorted order. This function returns
+   * FALSE if a packet with the same seqnum was already in the queue, meaning we
+   * have a duplicate. */
+  if (G_UNLIKELY (!wfd_rtp_buffer_insert (priv->jbuf, item,
+              &head, &percent)))
+    goto duplicate;
+
+  /* update timers */
+  update_timers (jitterbuffer, seqnum, dts, do_next_seqnum);
+
+  /* we had an unhandled SR, handle it now */
+  if (priv->last_sr)
+    do_handle_sync (jitterbuffer);
+
+  if (G_UNLIKELY (head)) {
+    /* signal addition of new buffer when the _loop is waiting. */
+    if (G_LIKELY (priv->active))
+      JBUF_SIGNAL_EVENT (priv);
+
+    /* let's unschedule and unblock any waiting buffers. We only want to do this
+     * when the head buffer changed */
+    if (G_UNLIKELY (priv->clock_id)) {
+      GST_DEBUG_OBJECT (jitterbuffer, "Unscheduling waiting new buffer");
+      unschedule_current_timer (jitterbuffer);
+    }
+  }
+
+  GST_DEBUG_OBJECT (jitterbuffer,
+      "Pushed packet #%d, now %d packets, head: %d, " "percent %d", seqnum,
+      wfd_rtp_buffer_num_packets (priv->jbuf), head, percent);
+
+  msg = check_buffering_percent (jitterbuffer, percent);
+
+finished:
+  JBUF_UNLOCK (priv);
+
+  if (msg)
+    gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
+
+  return ret;
+
+  /* ERRORS */
+invalid_buffer:
+  {
+    /* this is not fatal but should be filtered earlier */
+    GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
+        ("Received invalid RTP payload, dropping"));
+    gst_buffer_unref (buffer);
+    return GST_FLOW_OK;
+  }
+no_clock_rate:
+  {
+    GST_WARNING_OBJECT (jitterbuffer,
+        "No clock-rate in caps!, dropping buffer");
+    gst_buffer_unref (buffer);
+    goto finished;
+  }
+out_flushing:
+  {
+    ret = priv->srcresult;
+    GST_DEBUG_OBJECT (jitterbuffer, "flushing %s", gst_flow_get_name (ret));
+    gst_buffer_unref (buffer);
+    goto finished;
+  }
+have_eos:
+  {
+    ret = GST_FLOW_EOS;
+    GST_WARNING_OBJECT (jitterbuffer, "we are EOS, refusing buffer");
+    gst_buffer_unref (buffer);
+    goto finished;
+  }
+too_late:
+  {
+    GST_WARNING_OBJECT (jitterbuffer, "Packet #%d too late as #%d was already"
+        " popped, dropping", seqnum, priv->last_popped_seqnum);
+    priv->num_late++;
+    gst_buffer_unref (buffer);
+    goto finished;
+  }
+duplicate:
+  {
+    GST_WARNING_OBJECT (jitterbuffer, "Duplicate packet #%d detected, dropping",
+        seqnum);
+    priv->num_duplicates++;
+    free_item (item);
+    goto finished;
+  }
+}
+
+static GstClockTime
+compute_elapsed (GstWfdRTPBuffer * jitterbuffer, WfdRTPBufferItem * item)
+{
+  guint64 ext_time, elapsed;
+  guint32 rtp_time;
+  GstWfdRTPBufferPrivate *priv;
+
+  priv = jitterbuffer->priv;
+  rtp_time = item->rtptime;
+
+  GST_LOG_OBJECT (jitterbuffer, "rtp %" G_GUINT32_FORMAT ", ext %"
+      G_GUINT64_FORMAT, rtp_time, priv->ext_timestamp);
+
+  if (rtp_time < priv->ext_timestamp) {
+    ext_time = priv->ext_timestamp;
+  } else {
+    ext_time = gst_rtp_buffer_ext_timestamp (&priv->ext_timestamp, rtp_time);
+  }
+
+  if (ext_time > priv->clock_base)
+    elapsed = ext_time - priv->clock_base;
+  else
+    elapsed = 0;
+
+  elapsed = gst_util_uint64_scale_int (elapsed, GST_SECOND, priv->clock_rate);
+  return elapsed;
+}
+
+static void
+update_estimated_eos (GstWfdRTPBuffer * jitterbuffer,
+    WfdRTPBufferItem * item)
+{
+  guint64 total, elapsed, left, estimated;
+  GstClockTime out_time;
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+
+  if (priv->npt_stop == -1 || priv->ext_timestamp == -1
+      || priv->clock_base == -1 || priv->clock_rate <= 0)
+    return;
+
+  /* compute the elapsed time */
+  elapsed = compute_elapsed (jitterbuffer, item);
+
+  /* do nothing if elapsed time doesn't increment */
+  if (priv->last_elapsed && elapsed <= priv->last_elapsed)
+    return;
+
+  priv->last_elapsed = elapsed;
+
+  /* this is the total time we need to play */
+  total = priv->npt_stop - priv->npt_start;
+  GST_LOG_OBJECT (jitterbuffer, "total %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (total));
+
+  /* this is how much time there is left */
+  if (total > elapsed)
+    left = total - elapsed;
+  else
+    left = 0;
+
+  /* if we have less time left that the size of the buffer, we will not
+   * be able to keep it filled, disabled buffering then */
+  if (left < wfd_rtp_buffer_get_delay (priv->jbuf)) {
+    GST_DEBUG_OBJECT (jitterbuffer, "left %" GST_TIME_FORMAT
+        ", disable buffering close to EOS", GST_TIME_ARGS (left));
+    wfd_rtp_buffer_disable_buffering (priv->jbuf, TRUE);
+  }
+
+  /* this is the current time as running-time */
+  out_time = item->dts;
+
+  if (elapsed > 0)
+    estimated = gst_util_uint64_scale (out_time, total, elapsed);
+  else {
+    /* if there is almost nothing left,
+     * we may never advance enough to end up in the above case */
+    if (total < GST_SECOND)
+      estimated = GST_SECOND;
+    else
+      estimated = -1;
+  }
+  GST_LOG_OBJECT (jitterbuffer, "elapsed %" GST_TIME_FORMAT ", estimated %"
+      GST_TIME_FORMAT, GST_TIME_ARGS (elapsed), GST_TIME_ARGS (estimated));
+
+  if (estimated != -1 && priv->estimated_eos != estimated) {
+    set_timer (jitterbuffer, TIMER_TYPE_EOS, -1, estimated);
+    priv->estimated_eos = estimated;
+  }
+}
+
+/* take a buffer from the queue and push it */
+static GstFlowReturn
+pop_and_push_next (GstWfdRTPBuffer * jitterbuffer, guint seqnum)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstFlowReturn result = GST_FLOW_OK;
+  WfdRTPBufferItem *item;
+  GstBuffer *outbuf = NULL;
+  GstEvent *outevent = NULL;
+  GstQuery *outquery = NULL;
+  GstClockTime dts, pts;
+  gint percent = -1;
+  gboolean do_push = TRUE;
+  guint type;
+  GstMessage *msg;
+
+  /* when we get here we are ready to pop and push the buffer */
+  item = wfd_rtp_buffer_pop (priv->jbuf, &percent);
+  type = item->type;
+
+  switch (type) {
+    case ITEM_TYPE_BUFFER:
+
+      /* we need to make writable to change the flags and timestamps */
+      outbuf = gst_buffer_make_writable (item->data);
+
+      if (G_UNLIKELY (priv->discont)) {
+        /* set DISCONT flag when we missed a packet. We pushed the buffer writable
+         * into the jitterbuffer so we can modify now. */
+        GST_DEBUG_OBJECT (jitterbuffer, "mark output buffer discont");
+        GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
+        priv->discont = FALSE;
+      }
+      if (G_UNLIKELY (priv->ts_discont)) {
+        GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_RESYNC);
+        priv->ts_discont = FALSE;
+      }
+
+      dts =
+          gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->dts);
+      pts =
+          gst_segment_to_position (&priv->segment, GST_FORMAT_TIME, item->pts);
+
+      /* apply timestamp with offset to buffer now */
+      GST_BUFFER_DTS (outbuf) = apply_offset (jitterbuffer, dts);
+      GST_BUFFER_PTS (outbuf) = apply_offset (jitterbuffer, pts);
+
+      /* update the elapsed time when we need to check against the npt stop time. */
+      update_estimated_eos (jitterbuffer, item);
+
+      priv->last_out_time = GST_BUFFER_PTS (outbuf);
+      break;
+    case ITEM_TYPE_LOST:
+      priv->discont = TRUE;
+      if (!priv->do_lost)
+        do_push = FALSE;
+      /* FALLTHROUGH */
+    case ITEM_TYPE_EVENT:
+      outevent = item->data;
+      break;
+    case ITEM_TYPE_QUERY:
+      outquery = item->data;
+      break;
+  }
+
+  /* now we are ready to push the buffer. Save the seqnum and release the lock
+   * so the other end can push stuff in the queue again. */
+  if (seqnum != -1) {
+    priv->last_popped_seqnum = seqnum;
+    priv->next_seqnum = (seqnum + item->count) & 0xffff;
+  }
+  msg = check_buffering_percent (jitterbuffer, percent);
+  JBUF_UNLOCK (priv);
+
+  item->data = NULL;
+  free_item (item);
+
+  if (msg)
+    gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer), msg);
+
+  switch (type) {
+    case ITEM_TYPE_BUFFER:
+      /* push buffer */
+      GST_DEBUG_OBJECT (jitterbuffer,
+          "Pushing buffer %d, dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
+          seqnum, GST_TIME_ARGS (GST_BUFFER_DTS (outbuf)),
+          GST_TIME_ARGS (GST_BUFFER_PTS (outbuf)));
+      result = gst_pad_push (priv->srcpad, outbuf);
+
+      JBUF_LOCK_CHECK (priv, out_flushing);
+      break;
+    case ITEM_TYPE_LOST:
+    case ITEM_TYPE_EVENT:
+      GST_DEBUG_OBJECT (jitterbuffer, "%sPushing event %" GST_PTR_FORMAT
+          ", seqnum %d", do_push ? "" : "NOT ", outevent, seqnum);
+
+      if (do_push)
+        gst_pad_push_event (priv->srcpad, outevent);
+      else
+        gst_event_unref (outevent);
+
+      result = GST_FLOW_OK;
+
+      JBUF_LOCK_CHECK (priv, out_flushing);
+      break;
+    case ITEM_TYPE_QUERY:
+    {
+      gboolean res;
+
+      res = gst_pad_peer_query (priv->srcpad, outquery);
+
+      JBUF_LOCK_CHECK (priv, out_flushing);
+      result = GST_FLOW_OK;
+      GST_LOG_OBJECT (jitterbuffer, "did query %p, return %d", outquery, res);
+      JBUF_SIGNAL_QUERY (priv, res);
+      break;
+    }
+  }
+  return result;
+
+  /* ERRORS */
+out_flushing:
+  {
+    return priv->srcresult;
+  }
+}
+
+#define GST_FLOW_WAIT GST_FLOW_CUSTOM_SUCCESS
+
+/* Peek a buffer and compare the seqnum to the expected seqnum.
+ * If all is fine, the buffer is pushed.
+ * If something is wrong, we wait for some event
+ */
+static GstFlowReturn
+handle_next_buffer (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstFlowReturn result = GST_FLOW_OK;
+  WfdRTPBufferItem *item;
+  guint seqnum;
+  guint32 next_seqnum;
+  gint gap;
+
+  /* only push buffers when PLAYING and active and not buffering */
+  if (priv->blocked || !priv->active ||
+      wfd_rtp_buffer_is_buffering (priv->jbuf))
+    return GST_FLOW_WAIT;
+
+again:
+  /* peek a buffer, we're just looking at the sequence number.
+   * If all is fine, we'll pop and push it. If the sequence number is wrong we
+   * wait for a timeout or something to change.
+   * The peeked buffer is valid for as long as we hold the jitterbuffer lock. */
+  item = wfd_rtp_buffer_peek (priv->jbuf);
+  if (item == NULL)
+    goto wait;
+
+  /* get the seqnum and the next expected seqnum */
+  seqnum = item->seqnum;
+  if (seqnum == -1)
+    goto do_push;
+
+  next_seqnum = priv->next_seqnum;
+
+  /* get the gap between this and the previous packet. If we don't know the
+   * previous packet seqnum assume no gap. */
+  if (G_UNLIKELY (next_seqnum == -1)) {
+    GST_DEBUG_OBJECT (jitterbuffer, "First buffer #%d", seqnum);
+    result = pop_and_push_next (jitterbuffer, seqnum);
+  } else {
+    /* else calculate GAP */
+    gap = gst_rtp_buffer_compare_seqnum (next_seqnum, seqnum);
+
+    if (G_LIKELY (gap == 0)) {
+    do_push:
+      /* no missing packet, pop and push */
+      result = pop_and_push_next (jitterbuffer, seqnum);
+    } else if (G_UNLIKELY (gap < 0)) {
+      WfdRTPBufferItem *item;
+      /* if we have a packet that we already pushed or considered dropped, pop it
+       * off and get the next packet */
+      GST_DEBUG_OBJECT (jitterbuffer, "Old packet #%d, next #%d dropping",
+          seqnum, next_seqnum);
+      item = wfd_rtp_buffer_pop (priv->jbuf, NULL);
+      free_item (item);
+      goto again;
+    } else {
+      /* the chain function has scheduled timers to request retransmission or
+       * when to consider the packet lost, wait for that */
+      GST_DEBUG_OBJECT (jitterbuffer,
+          "Sequence number GAP detected: expected %d instead of %d (%d missing)",
+          next_seqnum, seqnum, gap);
+      result = GST_FLOW_WAIT;
+    }
+  }
+  return result;
+
+wait:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "no buffer, going to wait");
+    if (priv->eos)
+      result = GST_FLOW_EOS;
+    else
+      result = GST_FLOW_WAIT;
+    return result;
+  }
+}
+
+/* the timeout for when we expected a packet expired */
+static gboolean
+do_expected_timeout (GstWfdRTPBuffer * jitterbuffer, TimerData * timer,
+    GstClockTime now)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstEvent *event;
+  guint delay, delay_ms, avg_rtx_rtt_ms;
+  guint rtx_retry_timeout_ms, rtx_retry_period_ms;
+  GstClockTime rtx_retry_period;
+  GstClockTime rtx_retry_timeout;
+  GstClock *clock;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "expected %d didn't arrive, now %"
+      GST_TIME_FORMAT, timer->seqnum, GST_TIME_ARGS (now));
+
+  if (priv->rtx_retry_timeout == -1) {
+    if (priv->avg_rtx_rtt == 0)
+      rtx_retry_timeout = DEFAULT_AUTO_RTX_TIMEOUT;
+    else
+      /* we want to ask for a retransmission after we waited for a
+       * complete RTT and the additional jitter */
+      rtx_retry_timeout = priv->avg_rtx_rtt + priv->avg_jitter * 2;
+  } else {
+    rtx_retry_timeout = priv->rtx_retry_timeout * GST_MSECOND;
+  }
+
+  if (priv->rtx_retry_period == -1) {
+    /* we retry up to the configured jitterbuffer size but leaving some
+     * room for the retransmission to arrive in time */
+    rtx_retry_period = priv->latency_ns - rtx_retry_timeout;
+  } else {
+    rtx_retry_period = priv->rtx_retry_period * GST_MSECOND;
+  }
+
+  GST_DEBUG_OBJECT (jitterbuffer, "timeout %" GST_TIME_FORMAT ", period %"
+      GST_TIME_FORMAT, GST_TIME_ARGS (rtx_retry_timeout),
+      GST_TIME_ARGS (rtx_retry_period));
+
+  delay = timer->rtx_delay + timer->rtx_retry;
+
+  delay_ms = GST_TIME_AS_MSECONDS (delay);
+  rtx_retry_timeout_ms = GST_TIME_AS_MSECONDS (rtx_retry_timeout);
+  rtx_retry_period_ms = GST_TIME_AS_MSECONDS (rtx_retry_period);
+  avg_rtx_rtt_ms = GST_TIME_AS_MSECONDS (priv->avg_rtx_rtt);
+
+  event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM,
+      gst_structure_new ("GstRTPRetransmissionRequest",
+          "seqnum", G_TYPE_UINT, (guint) timer->seqnum,
+          "running-time", G_TYPE_UINT64, timer->rtx_base,
+          "delay", G_TYPE_UINT, delay_ms,
+          "retry", G_TYPE_UINT, timer->num_rtx_retry,
+          "frequency", G_TYPE_UINT, rtx_retry_timeout_ms,
+          "period", G_TYPE_UINT, rtx_retry_period_ms,
+          "deadline", G_TYPE_UINT, priv->latency_ms,
+          "packet-spacing", G_TYPE_UINT64, priv->packet_spacing,
+          "avg-rtt", G_TYPE_UINT, avg_rtx_rtt_ms, NULL));
+
+  priv->num_rtx_requests++;
+  timer->num_rtx_retry++;
+
+  GST_OBJECT_LOCK (jitterbuffer);
+  if ((clock = GST_ELEMENT_CLOCK (jitterbuffer))) {
+    timer->rtx_last = gst_clock_get_time (clock);
+    timer->rtx_last -= GST_ELEMENT_CAST (jitterbuffer)->base_time;
+  } else {
+    timer->rtx_last = now;
+  }
+  GST_OBJECT_UNLOCK (jitterbuffer);
+
+  /* calculate the timeout for the next retransmission attempt */
+  timer->rtx_retry += rtx_retry_timeout;
+  GST_DEBUG_OBJECT (jitterbuffer, "base %" GST_TIME_FORMAT ", delay %"
+      GST_TIME_FORMAT ", retry %" GST_TIME_FORMAT ", num_retry %u",
+      GST_TIME_ARGS (timer->rtx_base), GST_TIME_ARGS (timer->rtx_delay),
+      GST_TIME_ARGS (timer->rtx_retry), timer->num_rtx_retry);
+
+  if (timer->rtx_retry + timer->rtx_delay > rtx_retry_period) {
+    GST_DEBUG_OBJECT (jitterbuffer, "reschedule as LOST timer");
+    /* too many retransmission request, we now convert the timer
+     * to a lost timer, leave the num_rtx_retry as it is for stats */
+    timer->type = TIMER_TYPE_LOST;
+    timer->rtx_delay = 0;
+    timer->rtx_retry = 0;
+  }
+  reschedule_timer (jitterbuffer, timer, timer->seqnum,
+      timer->rtx_base + timer->rtx_retry, timer->rtx_delay, FALSE);
+
+  JBUF_UNLOCK (priv);
+  gst_pad_push_event (priv->sinkpad, event);
+  JBUF_LOCK (priv);
+
+  return FALSE;
+}
+
+/* a packet is lost */
+static gboolean
+do_lost_timeout (GstWfdRTPBuffer * jitterbuffer, TimerData * timer,
+    GstClockTime now)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstClockTime duration, timestamp;
+  guint seqnum, lost_packets, num_rtx_retry, next_in_seqnum;
+  gboolean late, head;
+  GstEvent *event;
+  WfdRTPBufferItem *item;
+
+  seqnum = timer->seqnum;
+  timestamp = apply_offset (jitterbuffer, timer->timeout);
+  duration = timer->duration;
+  if (duration == GST_CLOCK_TIME_NONE && priv->packet_spacing > 0)
+    duration = priv->packet_spacing;
+  lost_packets = MAX (timer->num, 1);
+  late = timer->num > 0;
+  num_rtx_retry = timer->num_rtx_retry;
+
+  /* we had a gap and thus we lost some packets. Create an event for this.  */
+  if (lost_packets > 1)
+    GST_DEBUG_OBJECT (jitterbuffer, "Packets #%d -> #%d lost", seqnum,
+        seqnum + lost_packets - 1);
+  else
+    GST_DEBUG_OBJECT (jitterbuffer, "Packet #%d lost", seqnum);
+
+  priv->num_late += lost_packets;
+  priv->num_rtx_failed += num_rtx_retry;
+
+  next_in_seqnum = (seqnum + lost_packets) & 0xffff;
+
+  /* we now only accept seqnum bigger than this */
+  if (gst_rtp_buffer_compare_seqnum (priv->next_in_seqnum, next_in_seqnum) > 0)
+    priv->next_in_seqnum = next_in_seqnum;
+
+  /* create paket lost event */
+  event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM,
+      gst_structure_new ("GstRTPPacketLost",
+          "seqnum", G_TYPE_UINT, (guint) seqnum,
+          "timestamp", G_TYPE_UINT64, timestamp,
+          "duration", G_TYPE_UINT64, duration,
+          "late", G_TYPE_BOOLEAN, late,
+          "retry", G_TYPE_UINT, num_rtx_retry, NULL));
+
+  item = alloc_item (event, ITEM_TYPE_LOST, -1, -1, seqnum, lost_packets, -1);
+  wfd_rtp_buffer_insert (priv->jbuf, item, &head, NULL);
+
+  /* remove timer now */
+  remove_timer (jitterbuffer, timer);
+  if (head)
+    JBUF_SIGNAL_EVENT (priv);
+
+  return TRUE;
+}
+
+static gboolean
+do_eos_timeout (GstWfdRTPBuffer * jitterbuffer, TimerData * timer,
+    GstClockTime now)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+
+  GST_INFO_OBJECT (jitterbuffer, "got the NPT timeout");
+  remove_timer (jitterbuffer, timer);
+  if (!priv->eos) {
+    /* there was no EOS in the buffer, put one in there now */
+    queue_event (jitterbuffer, gst_event_new_eos ());
+  }
+  JBUF_SIGNAL_EVENT (priv);
+
+  return TRUE;
+}
+
+static gboolean
+do_deadline_timeout (GstWfdRTPBuffer * jitterbuffer, TimerData * timer,
+    GstClockTime now)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+
+  GST_INFO_OBJECT (jitterbuffer, "got deadline timeout");
+
+  /* timer seqnum might have been obsoleted by caps seqnum-base,
+   * only mess with current ongoing seqnum if still unknown */
+  if (priv->next_seqnum == -1)
+    priv->next_seqnum = timer->seqnum;
+  remove_timer (jitterbuffer, timer);
+  JBUF_SIGNAL_EVENT (priv);
+
+  return TRUE;
+}
+
+static gboolean
+do_timeout (GstWfdRTPBuffer * jitterbuffer, TimerData * timer,
+    GstClockTime now)
+{
+  gboolean removed = FALSE;
+
+  switch (timer->type) {
+    case TIMER_TYPE_EXPECTED:
+      removed = do_expected_timeout (jitterbuffer, timer, now);
+      break;
+    case TIMER_TYPE_LOST:
+      removed = do_lost_timeout (jitterbuffer, timer, now);
+      break;
+    case TIMER_TYPE_DEADLINE:
+      removed = do_deadline_timeout (jitterbuffer, timer, now);
+      break;
+    case TIMER_TYPE_EOS:
+      removed = do_eos_timeout (jitterbuffer, timer, now);
+      break;
+  }
+  return removed;
+}
+
+/* called when we need to wait for the next timeout.
+ *
+ * We loop over the array of recorded timeouts and wait for the earliest one.
+ * When it timed out, do the logic associated with the timer.
+ *
+ * If there are no timers, we wait on a gcond until something new happens.
+ */
+static void
+wait_next_timeout (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv = jitterbuffer->priv;
+  GstClockTime now = 0;
+
+  JBUF_LOCK (priv);
+  while (priv->timer_running) {
+    TimerData *timer = NULL;
+    GstClockTime timer_timeout = -1;
+    gint i, len;
+
+    GST_DEBUG_OBJECT (jitterbuffer, "now %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (now));
+
+    len = priv->timers->len;
+    for (i = 0; i < len; i++) {
+      TimerData *test = &g_array_index (priv->timers, TimerData, i);
+      GstClockTime test_timeout = get_timeout (jitterbuffer, test);
+      gboolean save_best = FALSE;
+
+      GST_DEBUG_OBJECT (jitterbuffer, "%d, %d, %d, %" GST_TIME_FORMAT,
+          i, test->type, test->seqnum, GST_TIME_ARGS (test_timeout));
+
+      /* find the smallest timeout */
+      if (timer == NULL) {
+        save_best = TRUE;
+      } else if (timer_timeout == -1) {
+        /* we already have an immediate timeout, the new timer must be an
+         * immediate timer with smaller seqnum to become the best */
+        if (test_timeout == -1
+            && (gst_rtp_buffer_compare_seqnum (test->seqnum,
+                    timer->seqnum) > 0))
+          save_best = TRUE;
+      } else if (test_timeout == -1) {
+        /* first immediate timer */
+        save_best = TRUE;
+      } else if (test_timeout < timer_timeout) {
+        /* earlier timer */
+        save_best = TRUE;
+      } else if (test_timeout == timer_timeout
+          && (gst_rtp_buffer_compare_seqnum (test->seqnum,
+                  timer->seqnum) > 0)) {
+        /* same timer, smaller seqnum */
+        save_best = TRUE;
+      }
+      if (save_best) {
+        GST_DEBUG_OBJECT (jitterbuffer, "new best %d", i);
+        timer = test;
+        timer_timeout = test_timeout;
+      }
+    }
+    if (timer && !priv->blocked) {
+      GstClock *clock;
+      GstClockTime sync_time;
+      GstClockID id;
+      GstClockReturn ret;
+      GstClockTimeDiff clock_jitter;
+
+      if (timer_timeout == -1 || timer_timeout <= now) {
+        do_timeout (jitterbuffer, timer, now);
+        /* check here, do_timeout could have released the lock */
+        if (!priv->timer_running)
+          break;
+        continue;
+      }
+
+      GST_OBJECT_LOCK (jitterbuffer);
+      clock = GST_ELEMENT_CLOCK (jitterbuffer);
+      if (!clock) {
+        GST_OBJECT_UNLOCK (jitterbuffer);
+        /* let's just push if there is no clock */
+        GST_DEBUG_OBJECT (jitterbuffer, "No clock, timeout right away");
+        now = timer_timeout;
+        continue;
+      }
+
+      /* prepare for sync against clock */
+      sync_time = timer_timeout + GST_ELEMENT_CAST (jitterbuffer)->base_time;
+      /* add latency of peer to get input time */
+      sync_time += priv->peer_latency;
+
+      GST_DEBUG_OBJECT (jitterbuffer, "sync to timestamp %" GST_TIME_FORMAT
+          " with sync time %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (timer_timeout), GST_TIME_ARGS (sync_time));
+
+      /* create an entry for the clock */
+      id = priv->clock_id = gst_clock_new_single_shot_id (clock, sync_time);
+      priv->timer_timeout = timer_timeout;
+      priv->timer_seqnum = timer->seqnum;
+      GST_OBJECT_UNLOCK (jitterbuffer);
+
+      /* release the lock so that the other end can push stuff or unlock */
+      JBUF_UNLOCK (priv);
+
+      ret = gst_clock_id_wait (id, &clock_jitter);
+
+      JBUF_LOCK (priv);
+      if (!priv->timer_running) {
+        gst_clock_id_unref (id);
+        priv->clock_id = NULL;
+        break;
+      }
+
+      if (ret != GST_CLOCK_UNSCHEDULED) {
+        now = timer_timeout + MAX (clock_jitter, 0);
+        GST_DEBUG_OBJECT (jitterbuffer, "sync done, %d, #%d, %" G_GINT64_FORMAT,
+            ret, priv->timer_seqnum, clock_jitter);
+      } else {
+        GST_DEBUG_OBJECT (jitterbuffer, "sync unscheduled");
+      }
+      /* and free the entry */
+      gst_clock_id_unref (id);
+      priv->clock_id = NULL;
+    } else {
+      /* no timers, wait for activity */
+      JBUF_WAIT_TIMER (priv);
+    }
+  }
+  JBUF_UNLOCK (priv);
+
+  GST_DEBUG_OBJECT (jitterbuffer, "we are stopping");
+  return;
+}
+
+/*
+ * This funcion implements the main pushing loop on the source pad.
+ *
+ * It first tries to push as many buffers as possible. If there is a seqnum
+ * mismatch, we wait for the next timeouts.
+ */
+static void
+gst_wfd_rtp_buffer_loop (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+  GstFlowReturn result = GST_FLOW_OK;
+
+  priv = jitterbuffer->priv;
+
+  JBUF_LOCK_CHECK (priv, flushing);
+  do {
+    result = handle_next_buffer (jitterbuffer);
+    if (G_LIKELY (result == GST_FLOW_WAIT)) {
+      /* now wait for the next event */
+      JBUF_WAIT_EVENT (priv, flushing);
+      result = GST_FLOW_OK;
+    }
+  } while (result == GST_FLOW_OK);
+
+  /* store result for upstream */
+  priv->srcresult = result;
+  /* if we get here we need to pause */
+  goto pause;
+
+  /* ERRORS */
+flushing:
+  {
+    result = priv->srcresult;
+    goto pause;
+  }
+pause:
+  {
+    GstEvent *event;
+
+    JBUF_SIGNAL_QUERY (priv, FALSE);
+    JBUF_UNLOCK (priv);
+
+    GST_DEBUG_OBJECT (jitterbuffer, "pausing task, reason %s",
+        gst_flow_get_name (result));
+    gst_pad_pause_task (priv->srcpad);
+    if (result == GST_FLOW_EOS) {
+      event = gst_event_new_eos ();
+      gst_pad_push_event (priv->srcpad, event);
+    }
+    return;
+  }
+}
+
+/* collect the info from the lastest RTCP packet and the jitterbuffer sync, do
+ * some sanity checks and then emit the handle-sync signal with the parameters.
+ * This function must be called with the LOCK */
+static void
+do_handle_sync (GstWfdRTPBuffer * jitterbuffer)
+{
+  GstWfdRTPBufferPrivate *priv;
+  guint64 base_rtptime, base_time;
+  guint32 clock_rate;
+  guint64 last_rtptime;
+  guint64 clock_base;
+  guint64 ext_rtptime, diff;
+  gboolean valid = TRUE, keep = FALSE;
+
+  priv = jitterbuffer->priv;
+
+  /* get the last values from the jitterbuffer */
+  wfd_rtp_buffer_get_sync (priv->jbuf, &base_rtptime, &base_time,
+      &clock_rate, &last_rtptime);
+
+  clock_base = priv->clock_base;
+  ext_rtptime = priv->ext_rtptime;
+
+  GST_DEBUG_OBJECT (jitterbuffer, "ext SR %" G_GUINT64_FORMAT ", base %"
+      G_GUINT64_FORMAT ", clock-rate %" G_GUINT32_FORMAT
+      ", clock-base %" G_GUINT64_FORMAT ", last-rtptime %" G_GUINT64_FORMAT,
+      ext_rtptime, base_rtptime, clock_rate, clock_base, last_rtptime);
+
+  if (base_rtptime == -1 || clock_rate == -1 || base_time == -1) {
+    /* we keep this SR packet for later. When we get a valid RTP packet the
+     * above values will be set and we can try to use the SR packet */
+    GST_DEBUG_OBJECT (jitterbuffer, "keeping for later, no RTP values");
+    keep = TRUE;
+  } else {
+    /* we can't accept anything that happened before we did the last resync */
+    if (base_rtptime > ext_rtptime) {
+      GST_DEBUG_OBJECT (jitterbuffer, "dropping, older than base time");
+      valid = FALSE;
+    } else {
+      /* the SR RTP timestamp must be something close to what we last observed
+       * in the jitterbuffer */
+      if (ext_rtptime > last_rtptime) {
+        /* check how far ahead it is to our RTP timestamps */
+        diff = ext_rtptime - last_rtptime;
+        /* if bigger than 1 second, we drop it */
+        if (diff > clock_rate) {
+          GST_DEBUG_OBJECT (jitterbuffer, "too far ahead");
+          /* should drop this, but some RTSP servers end up with bogus
+           * way too ahead RTCP packet when repeated PAUSE/PLAY,
+           * so still trigger rptbin sync but invalidate RTCP data
+           * (sync might use other methods) */
+          ext_rtptime = -1;
+        }
+        GST_DEBUG_OBJECT (jitterbuffer, "ext last %" G_GUINT64_FORMAT ", diff %"
+            G_GUINT64_FORMAT, last_rtptime, diff);
+      }
+    }
+  }
+
+  if (keep) {
+    GST_DEBUG_OBJECT (jitterbuffer, "keeping RTCP packet for later");
+  } else if (valid) {
+    GstStructure *s;
+
+    s = gst_structure_new ("application/x-rtp-sync",
+        "base-rtptime", G_TYPE_UINT64, base_rtptime,
+        "base-time", G_TYPE_UINT64, base_time,
+        "clock-rate", G_TYPE_UINT, clock_rate,
+        "clock-base", G_TYPE_UINT64, clock_base,
+        "sr-ext-rtptime", G_TYPE_UINT64, ext_rtptime,
+        "sr-buffer", GST_TYPE_BUFFER, priv->last_sr, NULL);
+
+    GST_DEBUG_OBJECT (jitterbuffer, "signaling sync");
+    gst_buffer_replace (&priv->last_sr, NULL);
+    JBUF_UNLOCK (priv);
+    g_signal_emit (jitterbuffer,
+        gst_wfd_rtp_buffer_signals[SIGNAL_HANDLE_SYNC], 0, s);
+    JBUF_LOCK (priv);
+    gst_structure_free (s);
+  } else {
+    GST_DEBUG_OBJECT (jitterbuffer, "dropping RTCP packet");
+    gst_buffer_replace (&priv->last_sr, NULL);
+  }
+}
+
+static GstFlowReturn
+gst_wfd_rtp_buffer_chain_rtcp (GstPad * pad, GstObject * parent,
+    GstBuffer * buffer)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+  GstFlowReturn ret = GST_FLOW_OK;
+  guint32 ssrc;
+  GstRTCPPacket packet;
+  guint64 ext_rtptime;
+  guint32 rtptime;
+  GstRTCPBuffer rtcp = { NULL, };
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (parent);
+
+  if (G_UNLIKELY (!gst_rtcp_buffer_validate (buffer)))
+    goto invalid_buffer;
+
+  priv = jitterbuffer->priv;
+
+  gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp);
+
+  if (!gst_rtcp_buffer_get_first_packet (&rtcp, &packet))
+    goto empty_buffer;
+
+  /* first packet must be SR or RR or else the validate would have failed */
+  switch (gst_rtcp_packet_get_type (&packet)) {
+    case GST_RTCP_TYPE_SR:
+      gst_rtcp_packet_sr_get_sender_info (&packet, &ssrc, NULL, &rtptime,
+          NULL, NULL);
+      break;
+    default:
+      goto ignore_buffer;
+  }
+  gst_rtcp_buffer_unmap (&rtcp);
+
+  GST_DEBUG_OBJECT (jitterbuffer, "received RTCP of SSRC %08x", ssrc);
+
+  JBUF_LOCK (priv);
+  /* convert the RTP timestamp to our extended timestamp, using the same offset
+   * we used in the jitterbuffer */
+  ext_rtptime = priv->jbuf->ext_rtptime;
+  ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
+
+  priv->ext_rtptime = ext_rtptime;
+  gst_buffer_replace (&priv->last_sr, buffer);
+
+  do_handle_sync (jitterbuffer);
+  JBUF_UNLOCK (priv);
+
+done:
+  gst_buffer_unref (buffer);
+
+  return ret;
+
+invalid_buffer:
+  {
+    /* this is not fatal but should be filtered earlier */
+    GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
+        ("Received invalid RTCP payload, dropping"));
+    ret = GST_FLOW_OK;
+    goto done;
+  }
+empty_buffer:
+  {
+    /* this is not fatal but should be filtered earlier */
+    GST_ELEMENT_WARNING (jitterbuffer, STREAM, DECODE, (NULL),
+        ("Received empty RTCP payload, dropping"));
+    gst_rtcp_buffer_unmap (&rtcp);
+    ret = GST_FLOW_OK;
+    goto done;
+  }
+ignore_buffer:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "ignoring RTCP packet");
+    gst_rtcp_buffer_unmap (&rtcp);
+    ret = GST_FLOW_OK;
+    goto done;
+  }
+}
+
+static gboolean
+gst_wfd_rtp_buffer_sink_query (GstPad * pad, GstObject * parent,
+    GstQuery * query)
+{
+  gboolean res = FALSE;
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (parent);
+  priv = jitterbuffer->priv;
+
+  switch (GST_QUERY_TYPE (query)) {
+    case GST_QUERY_CAPS:
+    {
+      GstCaps *filter, *caps;
+
+      gst_query_parse_caps (query, &filter);
+      caps = gst_wfd_rtp_buffer_getcaps (pad, filter);
+      gst_query_set_caps_result (query, caps);
+      gst_caps_unref (caps);
+      res = TRUE;
+      break;
+    }
+    default:
+      if (GST_QUERY_IS_SERIALIZED (query)) {
+        WfdRTPBufferItem *item;
+        gboolean head;
+
+        JBUF_LOCK_CHECK (priv, out_flushing);
+        if (wfd_rtp_buffer_get_mode (priv->jbuf) !=
+            WFD_RTP_BUFFER_MODE_BUFFER) {
+          GST_DEBUG_OBJECT (jitterbuffer, "adding serialized query");
+          item = alloc_item (query, ITEM_TYPE_QUERY, -1, -1, -1, 0, -1);
+          wfd_rtp_buffer_insert (priv->jbuf, item, &head, NULL);
+          if (head)
+            JBUF_SIGNAL_EVENT (priv);
+          JBUF_WAIT_QUERY (priv, out_flushing);
+          res = priv->last_query;
+        } else {
+          GST_DEBUG_OBJECT (jitterbuffer, "refusing query, we are buffering");
+          res = FALSE;
+        }
+        JBUF_UNLOCK (priv);
+      } else {
+        res = gst_pad_query_default (pad, parent, query);
+      }
+      break;
+  }
+  return res;
+  /* ERRORS */
+out_flushing:
+  {
+    GST_DEBUG_OBJECT (jitterbuffer, "we are flushing");
+    JBUF_UNLOCK (priv);
+    return FALSE;
+  }
+
+}
+
+static gboolean
+gst_wfd_rtp_buffer_src_query (GstPad * pad, GstObject * parent,
+    GstQuery * query)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+  gboolean res = FALSE;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (parent);
+  priv = jitterbuffer->priv;
+
+  switch (GST_QUERY_TYPE (query)) {
+    case GST_QUERY_LATENCY:
+    {
+      /* We need to send the query upstream and add the returned latency to our
+       * own */
+      GstClockTime min_latency, max_latency;
+      gboolean us_live;
+      GstClockTime our_latency;
+
+      if ((res = gst_pad_peer_query (priv->sinkpad, query))) {
+        gst_query_parse_latency (query, &us_live, &min_latency, &max_latency);
+
+        GST_DEBUG_OBJECT (jitterbuffer, "Peer latency: min %"
+            GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
+
+        /* store this so that we can safely sync on the peer buffers. */
+        JBUF_LOCK (priv);
+        priv->peer_latency = min_latency;
+        our_latency = priv->latency_ns;
+        JBUF_UNLOCK (priv);
+
+        GST_DEBUG_OBJECT (jitterbuffer, "Our latency: %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (our_latency));
+
+        /* we add some latency but can buffer an infinite amount of time */
+        min_latency += our_latency;
+        max_latency = -1;
+
+        GST_DEBUG_OBJECT (jitterbuffer, "Calculated total latency : min %"
+            GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
+
+        gst_query_set_latency (query, TRUE, min_latency, max_latency);
+      }
+      break;
+    }
+    case GST_QUERY_POSITION:
+    {
+      GstClockTime start, last_out;
+      GstFormat fmt;
+
+      gst_query_parse_position (query, &fmt, NULL);
+      if (fmt != GST_FORMAT_TIME) {
+        res = gst_pad_query_default (pad, parent, query);
+        break;
+      }
+
+      JBUF_LOCK (priv);
+      start = priv->npt_start;
+      last_out = priv->last_out_time;
+      JBUF_UNLOCK (priv);
+
+      GST_DEBUG_OBJECT (jitterbuffer, "npt start %" GST_TIME_FORMAT
+          ", last out %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
+          GST_TIME_ARGS (last_out));
+
+      if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (last_out)) {
+        /* bring 0-based outgoing time to stream time */
+        gst_query_set_position (query, GST_FORMAT_TIME, start + last_out);
+        res = TRUE;
+      } else {
+        res = gst_pad_query_default (pad, parent, query);
+      }
+      break;
+    }
+    case GST_QUERY_CAPS:
+    {
+      GstCaps *filter, *caps;
+
+      gst_query_parse_caps (query, &filter);
+      caps = gst_wfd_rtp_buffer_getcaps (pad, filter);
+      gst_query_set_caps_result (query, caps);
+      gst_caps_unref (caps);
+      res = TRUE;
+      break;
+    }
+    default:
+      res = gst_pad_query_default (pad, parent, query);
+      break;
+  }
+
+  return res;
+}
+
+static void
+gst_wfd_rtp_buffer_set_property (GObject * object,
+    guint prop_id, const GValue * value, GParamSpec * pspec)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (object);
+  priv = jitterbuffer->priv;
+
+  switch (prop_id) {
+    case PROP_LATENCY:
+    {
+      guint new_latency, old_latency;
+
+      new_latency = g_value_get_uint (value);
+
+      JBUF_LOCK (priv);
+      old_latency = priv->latency_ms;
+      priv->latency_ms = new_latency;
+      priv->latency_ns = priv->latency_ms * GST_MSECOND;
+      wfd_rtp_buffer_set_delay (priv->jbuf, priv->latency_ns);
+      JBUF_UNLOCK (priv);
+
+      /* post message if latency changed, this will inform the parent pipeline
+       * that a latency reconfiguration is possible/needed. */
+      if (new_latency != old_latency) {
+        GST_DEBUG_OBJECT (jitterbuffer, "latency changed to: %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (new_latency * GST_MSECOND));
+
+        gst_element_post_message (GST_ELEMENT_CAST (jitterbuffer),
+            gst_message_new_latency (GST_OBJECT_CAST (jitterbuffer)));
+      }
+      break;
+    }
+    case PROP_DROP_ON_LATENCY:
+      JBUF_LOCK (priv);
+      priv->drop_on_latency = g_value_get_boolean (value);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_TS_OFFSET:
+      JBUF_LOCK (priv);
+      priv->ts_offset = g_value_get_int64 (value);
+      priv->ts_discont = TRUE;
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_DO_LOST:
+      JBUF_LOCK (priv);
+      priv->do_lost = g_value_get_boolean (value);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_MODE:
+      JBUF_LOCK (priv);
+      wfd_rtp_buffer_set_mode (priv->jbuf, g_value_get_enum (value));
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_DO_RETRANSMISSION:
+      JBUF_LOCK (priv);
+      priv->do_retransmission = g_value_get_boolean (value);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_DELAY:
+      JBUF_LOCK (priv);
+      priv->rtx_delay = g_value_get_int (value);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_DELAY_REORDER:
+      JBUF_LOCK (priv);
+      priv->rtx_delay_reorder = g_value_get_int (value);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_RETRY_TIMEOUT:
+      JBUF_LOCK (priv);
+      priv->rtx_retry_timeout = g_value_get_int (value);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_RETRY_PERIOD:
+      JBUF_LOCK (priv);
+      priv->rtx_retry_period = g_value_get_int (value);
+      JBUF_UNLOCK (priv);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_wfd_rtp_buffer_get_property (GObject * object,
+    guint prop_id, GValue * value, GParamSpec * pspec)
+{
+  GstWfdRTPBuffer *jitterbuffer;
+  GstWfdRTPBufferPrivate *priv;
+
+  jitterbuffer = GST_WFD_RTP_BUFFER (object);
+  priv = jitterbuffer->priv;
+
+  switch (prop_id) {
+    case PROP_LATENCY:
+      JBUF_LOCK (priv);
+      g_value_set_uint (value, priv->latency_ms);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_DROP_ON_LATENCY:
+      JBUF_LOCK (priv);
+      g_value_set_boolean (value, priv->drop_on_latency);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_TS_OFFSET:
+      JBUF_LOCK (priv);
+      g_value_set_int64 (value, priv->ts_offset);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_DO_LOST:
+      JBUF_LOCK (priv);
+      g_value_set_boolean (value, priv->do_lost);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_MODE:
+      JBUF_LOCK (priv);
+      g_value_set_enum (value, wfd_rtp_buffer_get_mode (priv->jbuf));
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_PERCENT:
+    {
+      gint percent;
+
+      JBUF_LOCK (priv);
+      if (priv->srcresult != GST_FLOW_OK)
+        percent = 100;
+      else
+        percent = wfd_rtp_buffer_get_percent (priv->jbuf);
+
+      g_value_set_int (value, percent);
+      JBUF_UNLOCK (priv);
+      break;
+    }
+    case PROP_DO_RETRANSMISSION:
+      JBUF_LOCK (priv);
+      g_value_set_boolean (value, priv->do_retransmission);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_DELAY:
+      JBUF_LOCK (priv);
+      g_value_set_int (value, priv->rtx_delay);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_DELAY_REORDER:
+      JBUF_LOCK (priv);
+      g_value_set_int (value, priv->rtx_delay_reorder);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_RETRY_TIMEOUT:
+      JBUF_LOCK (priv);
+      g_value_set_int (value, priv->rtx_retry_timeout);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_RTX_RETRY_PERIOD:
+      JBUF_LOCK (priv);
+      g_value_set_int (value, priv->rtx_retry_period);
+      JBUF_UNLOCK (priv);
+      break;
+    case PROP_STATS:
+      g_value_take_boxed (value,
+          gst_wfd_rtp_buffer_create_stats (jitterbuffer));
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static GstStructure *
+gst_wfd_rtp_buffer_create_stats (GstWfdRTPBuffer * jbuf)
+{
+  GstStructure *s;
+
+  JBUF_LOCK (jbuf->priv);
+  s = gst_structure_new ("application/x-rtp-jitterbuffer-stats",
+      "rtx-count", G_TYPE_UINT64, jbuf->priv->num_rtx_requests,
+      "rtx-success-count", G_TYPE_UINT64, jbuf->priv->num_rtx_success,
+      "rtx-per-packet", G_TYPE_DOUBLE, jbuf->priv->avg_rtx_num,
+      "rtx-rtt", G_TYPE_UINT64, jbuf->priv->avg_rtx_rtt, NULL);
+  JBUF_UNLOCK (jbuf->priv);
+
+  return s;
+}
diff --git a/wfdmanager/wfdrtpbuffer/gstwfdrtpbuffer.h b/wfdmanager/wfdrtpbuffer/gstwfdrtpbuffer.h
new file mode 100755 (executable)
index 0000000..cf7c3c1
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Farsight Voice+Video library
+ *
+ *  Copyright 2007 Collabora Ltd, 
+ *  Copyright 2007 Nokia Corporation
+ *   @author: Philippe Kalaf <philippe.kalaf@collabora.co.uk>.
+ *  Copyright 2007 Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef __GST_WFD_RTP_BUFFER_H__
+#define __GST_WFD_RTP_BUFFER_H__
+
+#include <gst/gst.h>
+#include <gst/rtp/gstrtpbuffer.h>
+
+G_BEGIN_DECLS
+
+/* #define's don't like whitespacey bits */
+#define GST_TYPE_WFD_RTP_BUFFER \
+  (gst_wfd_rtp_buffer_get_type())
+#define GST_WFD_RTP_BUFFER(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj), \
+  GST_TYPE_WFD_RTP_BUFFER,GstWfdRTPBuffer))
+#define GST_WFD_RTP_BUFFER_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass), \
+  GST_TYPE_WFD_RTP_BUFFER,GstWfdRTPBufferClass))
+#define GST_IS_WFD_RTP_BUFFER(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_RTP_BUFFER))
+#define GST_IS_WFD_RTP_BUFFER_CLASS(obj) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_RTP_BUFFER))
+#define GST_WFD_RTP_BUFFER_CAST(obj) \
+  ((GstWfdRTPBuffer *)(obj))
+
+typedef struct _GstWfdRTPBuffer GstWfdRTPBuffer;
+typedef struct _GstWfdRTPBufferClass GstWfdRTPBufferClass;
+typedef struct _GstWfdRTPBufferPrivate GstWfdRTPBufferPrivate;
+
+/**
+ * GstWfdRTPBuffer:
+ *
+ * Opaque jitterbuffer structure.
+ */
+struct _GstWfdRTPBuffer
+{
+  GstElement parent;
+
+  /*< private >*/
+  GstWfdRTPBufferPrivate *priv; /* FIXME: remove? */
+};
+
+struct _GstWfdRTPBufferClass
+{
+  GstElementClass parent_class;
+
+  /* signals */
+  GstCaps* (*request_pt_map)   (GstWfdRTPBuffer *buffer, guint pt);
+
+  void     (*handle_sync)      (GstWfdRTPBuffer *buffer, GstStructure *s);
+  void     (*on_npt_stop)      (GstWfdRTPBuffer *buffer);
+
+  /* actions */
+  void     (*clear_pt_map)   (GstWfdRTPBuffer *buffer);
+
+  GstClockTime (*set_active)     (GstWfdRTPBuffer *buffer, gboolean active, guint64 elapsed);
+};
+
+GType gst_wfd_rtp_buffer_get_type (void);
+
+G_END_DECLS
+
+#endif /* __GST_WFD_RTP_BUFFER_H__ */
diff --git a/wfdmanager/wfdrtpbuffer/rtpstats.c b/wfdmanager/wfdrtpbuffer/rtpstats.c
new file mode 100755 (executable)
index 0000000..4da164c
--- /dev/null
@@ -0,0 +1,331 @@
+/* GStreamer
+ * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "rtpstats.h"
+
+/**
+ * rtp_stats_init_defaults:
+ * @stats: an #RTPSessionStats struct
+ *
+ * Initialize @stats with its default values.
+ */
+void
+rtp_stats_init_defaults (RTPSessionStats * stats)
+{
+  rtp_stats_set_bandwidths (stats, -1, -1, -1, -1);
+  stats->min_interval = RTP_STATS_MIN_INTERVAL;
+  stats->bye_timeout = RTP_STATS_BYE_TIMEOUT;
+  stats->nacks_dropped = 0;
+  stats->nacks_sent = 0;
+  stats->nacks_received = 0;
+}
+
+/**
+ * rtp_stats_set_bandwidths:
+ * @stats: an #RTPSessionStats struct
+ * @rtp_bw: RTP bandwidth
+ * @rtcp_bw: RTCP bandwidth
+ * @rs: sender RTCP bandwidth
+ * @rr: receiver RTCP bandwidth
+ *
+ * Configure the bandwidth parameters in the stats. When an input variable is
+ * set to -1, it will be calculated from the other input variables and from the
+ * defaults.
+ */
+void
+rtp_stats_set_bandwidths (RTPSessionStats * stats, guint rtp_bw,
+    gdouble rtcp_bw, guint rs, guint rr)
+{
+  GST_DEBUG ("recalc bandwidths: RTP %u, RTCP %f, RS %u, RR %u", rtp_bw,
+      rtcp_bw, rs, rr);
+
+  /* when given, sender and receive bandwidth add up to the total
+   * rtcp bandwidth */
+  if (rs != -1 && rr != -1)
+    rtcp_bw = rs + rr;
+
+  /* If rtcp_bw is between 0 and 1, it is a fraction of rtp_bw */
+  if (rtcp_bw > 0.0 && rtcp_bw < 1.0) {
+    if (rtp_bw > 0.0)
+      rtcp_bw = rtp_bw * rtcp_bw;
+    else
+      rtcp_bw = -1.0;
+  }
+
+  /* RTCP is 5% of the RTP bandwidth */
+  if (rtp_bw == -1 && rtcp_bw > 1.0)
+    rtp_bw = rtcp_bw * 20;
+  else if (rtp_bw != -1 && rtcp_bw < 0.0)
+    rtcp_bw = rtp_bw / 20;
+  else if (rtp_bw == -1 && rtcp_bw < 0.0) {
+    /* nothing given, take defaults */
+    rtp_bw = RTP_STATS_BANDWIDTH;
+    rtcp_bw = rtp_bw * RTP_STATS_RTCP_FRACTION;
+  }
+
+  stats->bandwidth = rtp_bw;
+  stats->rtcp_bandwidth = rtcp_bw;
+
+  /* now figure out the fractions */
+  if (rs == -1) {
+    /* rs unknown */
+    if (rr == -1) {
+      /* both not given, use defaults */
+      rs = stats->rtcp_bandwidth * RTP_STATS_SENDER_FRACTION;
+      rr = stats->rtcp_bandwidth * RTP_STATS_RECEIVER_FRACTION;
+    } else {
+      /* rr known, calculate rs */
+      if (stats->rtcp_bandwidth > rr)
+        rs = stats->rtcp_bandwidth - rr;
+      else
+        rs = 0;
+    }
+  } else if (rr == -1) {
+    /* rs known, calculate rr */
+    if (stats->rtcp_bandwidth > rs)
+      rr = stats->rtcp_bandwidth - rs;
+    else
+      rr = 0;
+  }
+
+  if (stats->rtcp_bandwidth > 0) {
+    stats->sender_fraction = ((gdouble) rs) / ((gdouble) stats->rtcp_bandwidth);
+    stats->receiver_fraction = 1.0 - stats->sender_fraction;
+  } else {
+    /* no RTCP bandwidth, set dummy values */
+    stats->sender_fraction = 0.0;
+    stats->receiver_fraction = 0.0;
+  }
+  GST_DEBUG ("bandwidths: RTP %u, RTCP %u, RS %f, RR %f", stats->bandwidth,
+      stats->rtcp_bandwidth, stats->sender_fraction, stats->receiver_fraction);
+}
+
+/**
+ * rtp_stats_calculate_rtcp_interval:
+ * @stats: an #RTPSessionStats struct
+ * @sender: if we are a sender
+ * @first: if this is the first time
+ *
+ * Calculate the RTCP interval. The result of this function is the amount of
+ * time to wait (in nanoseconds) before sending a new RTCP message.
+ *
+ * Returns: the RTCP interval.
+ */
+GstClockTime
+rtp_stats_calculate_rtcp_interval (RTPSessionStats * stats, gboolean we_send,
+    gboolean first)
+{
+  gdouble members, senders, n;
+  gdouble avg_rtcp_size, rtcp_bw;
+  gdouble interval;
+  gdouble rtcp_min_time;
+
+  /* Very first call at application start-up uses half the min
+   * delay for quicker notification while still allowing some time
+   * before reporting for randomization and to learn about other
+   * sources so the report interval will converge to the correct
+   * interval more quickly.
+   */
+  rtcp_min_time = stats->min_interval;
+  if (first)
+    rtcp_min_time /= 2.0;
+
+  /* Dedicate a fraction of the RTCP bandwidth to senders unless
+   * the number of senders is large enough that their share is
+   * more than that fraction.
+   */
+  n = members = stats->active_sources;
+  senders = (gdouble) stats->sender_sources;
+  rtcp_bw = stats->rtcp_bandwidth;
+
+  if (senders <= members * stats->sender_fraction) {
+    if (we_send) {
+      rtcp_bw *= stats->sender_fraction;
+      n = senders;
+    } else {
+      rtcp_bw *= stats->receiver_fraction;
+      n -= senders;
+    }
+  }
+
+  /* no bandwidth for RTCP, return NONE to signal that we don't want to send
+   * RTCP packets */
+  if (rtcp_bw <= 0.00001)
+    return GST_CLOCK_TIME_NONE;
+
+  avg_rtcp_size = stats->avg_rtcp_packet_size;
+  /*
+   * The effective number of sites times the average packet size is
+   * the total number of octets sent when each site sends a report.
+   * Dividing this by the effective bandwidth gives the time
+   * interval over which those packets must be sent in order to
+   * meet the bandwidth target, with a minimum enforced.  In that
+   * time interval we send one report so this time is also our
+   * average time between reports.
+   */
+  GST_DEBUG ("avg size %f, n %f, rtcp_bw %f", avg_rtcp_size, n, rtcp_bw);
+  interval = avg_rtcp_size * n / rtcp_bw;
+  if (interval < rtcp_min_time)
+    interval = rtcp_min_time;
+
+  return interval * GST_SECOND;
+}
+
+/**
+ * rtp_stats_add_rtcp_jitter:
+ * @stats: an #RTPSessionStats struct
+ * @interval: an RTCP interval
+ *
+ * Apply a random jitter to the @interval. @interval is typically obtained with
+ * rtp_stats_calculate_rtcp_interval().
+ *
+ * Returns: the new RTCP interval.
+ */
+GstClockTime
+rtp_stats_add_rtcp_jitter (RTPSessionStats * stats, GstClockTime interval)
+{
+  gdouble temp;
+
+  /* see RFC 3550 p 30
+   * To compensate for "unconditional reconsideration" converging to a
+   * value below the intended average.
+   */
+#define COMPENSATION  (2.71828 - 1.5);
+
+  temp = (interval * g_random_double_range (0.5, 1.5)) / COMPENSATION;
+
+  return (GstClockTime) temp;
+}
+
+
+/**
+ * rtp_stats_calculate_bye_interval:
+ * @stats: an #RTPSessionStats struct
+ *
+ * Calculate the BYE interval. The result of this function is the amount of
+ * time to wait (in nanoseconds) before sending a BYE message.
+ *
+ * Returns: the BYE interval.
+ */
+GstClockTime
+rtp_stats_calculate_bye_interval (RTPSessionStats * stats)
+{
+  gdouble members;
+  gdouble avg_rtcp_size, rtcp_bw;
+  gdouble interval;
+  gdouble rtcp_min_time;
+
+  /* no interval when we have less than 50 members */
+  if (stats->active_sources < 50)
+    return 0;
+
+  rtcp_min_time = (stats->min_interval) / 2.0;
+
+  /* Dedicate a fraction of the RTCP bandwidth to senders unless
+   * the number of senders is large enough that their share is
+   * more than that fraction.
+   */
+  members = stats->bye_members;
+  rtcp_bw = stats->rtcp_bandwidth * stats->receiver_fraction;
+
+  /* no bandwidth for RTCP, return NONE to signal that we don't want to send
+   * RTCP packets */
+  if (rtcp_bw <= 0.0001)
+    return GST_CLOCK_TIME_NONE;
+
+  avg_rtcp_size = stats->avg_rtcp_packet_size;
+  /*
+   * The effective number of sites times the average packet size is
+   * the total number of octets sent when each site sends a report.
+   * Dividing this by the effective bandwidth gives the time
+   * interval over which those packets must be sent in order to
+   * meet the bandwidth target, with a minimum enforced.  In that
+   * time interval we send one report so this time is also our
+   * average time between reports.
+   */
+  interval = avg_rtcp_size * members / rtcp_bw;
+  if (interval < rtcp_min_time)
+    interval = rtcp_min_time;
+
+  return interval * GST_SECOND;
+}
+
+/**
+ * rtp_stats_get_packets_lost:
+ * @stats: an #RTPSourceStats struct
+ *
+ * Calculate the total number of RTP packets lost since beginning of
+ * reception. Packets that arrive late are not considered lost, and
+ * duplicates are not taken into account. Hence, the loss may be negative
+ * if there are duplicates.
+ *
+ * Returns: total RTP packets lost.
+ */
+gint64
+rtp_stats_get_packets_lost (const RTPSourceStats * stats)
+{
+  gint64 lost;
+  guint64 extended_max, expected;
+
+  extended_max = stats->cycles + stats->max_seq;
+  expected = extended_max - stats->base_seq + 1;
+  lost = expected - stats->packets_received;
+
+  return lost;
+}
+
+void
+rtp_stats_set_min_interval (RTPSessionStats * stats, gdouble min_interval)
+{
+  stats->min_interval = min_interval;
+}
+
+gboolean
+__g_socket_address_equal (GSocketAddress * a, GSocketAddress * b)
+{
+  GInetSocketAddress *ia, *ib;
+  GInetAddress *iaa, *iab;
+
+  ia = G_INET_SOCKET_ADDRESS (a);
+  ib = G_INET_SOCKET_ADDRESS (b);
+
+  if (g_inet_socket_address_get_port (ia) !=
+      g_inet_socket_address_get_port (ib))
+    return FALSE;
+
+  iaa = g_inet_socket_address_get_address (ia);
+  iab = g_inet_socket_address_get_address (ib);
+
+  return g_inet_address_equal (iaa, iab);
+}
+
+gchar *
+__g_socket_address_to_string (GSocketAddress * addr)
+{
+  GInetSocketAddress *ia;
+  gchar *ret, *tmp;
+
+  ia = G_INET_SOCKET_ADDRESS (addr);
+
+  tmp = g_inet_address_to_string (g_inet_socket_address_get_address (ia));
+  ret = g_strdup_printf ("%s:%u", tmp, g_inet_socket_address_get_port (ia));
+  g_free (tmp);
+
+  return ret;
+}
diff --git a/wfdmanager/wfdrtpbuffer/rtpstats.h b/wfdmanager/wfdrtpbuffer/rtpstats.h
new file mode 100755 (executable)
index 0000000..1f09ffa
--- /dev/null
@@ -0,0 +1,232 @@
+/* GStreamer
+ * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef __RTP_STATS_H__
+#define __RTP_STATS_H__
+
+#include <gst/gst.h>
+#include <gst/net/gstnetaddressmeta.h>
+#include <gio/gio.h>
+
+/**
+ * RTPSenderReport:
+ *
+ * A sender report structure.
+ */
+typedef struct {
+  gboolean is_valid;
+  guint64 ntptime;
+  guint32 rtptime;
+  guint32 packet_count;
+  guint32 octet_count;
+  GstClockTime time;
+} RTPSenderReport;
+
+/**
+ * RTPReceiverReport:
+ *
+ * A receiver report structure.
+ */
+typedef struct {
+  gboolean is_valid;
+  guint32 ssrc; /* who the report is from */
+  guint8  fractionlost;
+  guint32 packetslost;
+  guint32 exthighestseq;
+  guint32 jitter;
+  guint32 lsr;
+  guint32 dlsr;
+  guint32 round_trip;
+} RTPReceiverReport;
+
+/**
+ * RTPPacketInfo:
+ * @send: if this is a packet for sending
+ * @rtp: if this info is about an RTP packet
+ * @is_list: if this is a bufferlist
+ * @data: a #GstBuffer or #GstBufferList
+ * @address: address of the sender of the packet
+ * @current_time: current time according to the system clock
+ * @running_time: time of a packet as buffer running_time
+ * @ntpnstime: time of a packet NTP time in nanoseconds
+ * @header_len: number of overhead bytes per packet
+ * @bytes: bytes of the packet including lowlevel overhead
+ * @payload_len: bytes of the RTP payload
+ * @seqnum: the seqnum of the packet
+ * @pt: the payload type of the packet
+ * @rtptime: the RTP time of the packet
+ *
+ * Structure holding information about the packet.
+ */
+typedef struct {
+  gboolean      send;
+  gboolean      rtp;
+  gboolean      is_list;
+  gpointer      data;
+  GSocketAddress *address;
+  GstClockTime  current_time;
+  GstClockTime  running_time;
+  guint64       ntpnstime;
+  guint         header_len;
+  guint         bytes;
+  guint         packets;
+  guint         payload_len;
+  guint32       ssrc;
+  guint16       seqnum;
+  guint8        pt;
+  guint32       rtptime;
+  guint32       csrc_count;
+  guint32       csrcs[16];
+} RTPPacketInfo;
+
+/**
+ * RTPSourceStats:
+ * @packetsreceived: number of received packets in total
+ * @prevpacketsreceived: number of packets received in previous reporting
+ *                       interval
+ * @octetsreceived: number of payload bytes received
+ * @bytesreceived: number of total bytes received including headers and lower
+ *                 protocol level overhead
+ * @max_seqnr: highest sequence number received
+ * @transit: previous transit time used for calculating @jitter
+ * @jitter: current jitter
+ * @prev_rtptime: previous time when an RTP packet was received
+ * @prev_rtcptime: previous time when an RTCP packet was received
+ * @last_rtptime: time when last RTP packet received
+ * @last_rtcptime: time when last RTCP packet received
+ * @curr_rr: index of current @rr block
+ * @rr: previous and current receiver report block
+ * @curr_sr: index of current @sr block
+ * @sr: previous and current sender report block
+ *
+ * Stats about a source.
+ */
+typedef struct {
+  guint64      packets_received;
+  guint64      octets_received;
+  guint64      bytes_received;
+
+  guint32      prev_expected;
+  guint32      prev_received;
+
+  guint16      max_seq;
+  guint64      cycles;
+  guint32      base_seq;
+  guint32      bad_seq;
+  guint32      transit;
+  guint32      jitter;
+
+  guint64      packets_sent;
+  guint64      octets_sent;
+
+  /* when we received stuff */
+  GstClockTime prev_rtptime;
+  GstClockTime prev_rtcptime;
+  GstClockTime last_rtptime;
+  GstClockTime last_rtcptime;
+
+  /* sender and receiver reports */
+  gint              curr_rr;
+  RTPReceiverReport rr[2];
+  gint              curr_sr;
+  RTPSenderReport   sr[2];
+} RTPSourceStats;
+
+#define RTP_STATS_BANDWIDTH           64000
+#define RTP_STATS_RTCP_FRACTION       0.05
+/*
+ * Minimum average time between RTCP packets from this site (in
+ * seconds).  This time prevents the reports from `clumping' when
+ * sessions are small and the law of large numbers isn't helping
+ * to smooth out the traffic.  It also keeps the report interval
+ * from becoming ridiculously small during transient outages like
+ * a network partition.
+ */
+#define RTP_STATS_MIN_INTERVAL      5.0
+/*
+ * Fraction of the RTCP bandwidth to be shared among active
+ * senders.  (This fraction was chosen so that in a typical
+ * session with one or two active senders, the computed report
+ * time would be roughly equal to the minimum report time so that
+ * we don't unnecessarily slow down receiver reports.) The
+ * receiver fraction must be 1 - the sender fraction.
+ */
+#define RTP_STATS_SENDER_FRACTION       (0.25)
+#define RTP_STATS_RECEIVER_FRACTION     (1.0 - RTP_STATS_SENDER_FRACTION)
+
+/*
+ * When receiving a BYE from a source, remove the source from the database
+ * after this timeout.
+ */
+#define RTP_STATS_BYE_TIMEOUT           (2 * GST_SECOND)
+
+/*
+ * The maximum number of missing packets we tollerate. These are packets with a
+ * sequence number bigger than the last seen packet.
+ */
+#define RTP_MAX_DROPOUT      3000
+/*
+ * The maximum number of misordered packets we tollerate. These are packets with
+ * a sequence number smaller than the last seen packet.
+ */
+#define RTP_MAX_MISORDER     100
+
+/**
+ * RTPSessionStats:
+ *
+ * Stats kept for a session and used to produce RTCP packet timeouts.
+ */
+typedef struct {
+  guint         bandwidth;
+  guint         rtcp_bandwidth;
+  gdouble       sender_fraction;
+  gdouble       receiver_fraction;
+  gdouble       min_interval;
+  GstClockTime  bye_timeout;
+  guint         internal_sources;
+  guint         sender_sources;
+  guint         internal_sender_sources;
+  guint         active_sources;
+  guint         avg_rtcp_packet_size;
+  guint         bye_members;
+  guint         nacks_dropped;
+  guint         nacks_sent;
+  guint         nacks_received;
+} RTPSessionStats;
+
+void           rtp_stats_init_defaults              (RTPSessionStats *stats);
+
+void           rtp_stats_set_bandwidths             (RTPSessionStats *stats,
+                                                     guint rtp_bw,
+                                                     gdouble rtcp_bw,
+                                                     guint rs, guint rr);
+
+GstClockTime   rtp_stats_calculate_rtcp_interval    (RTPSessionStats *stats, gboolean sender, gboolean first);
+GstClockTime   rtp_stats_add_rtcp_jitter            (RTPSessionStats *stats, GstClockTime interval);
+GstClockTime   rtp_stats_calculate_bye_interval     (RTPSessionStats *stats);
+gint64         rtp_stats_get_packets_lost           (const RTPSourceStats *stats);
+
+void           rtp_stats_set_min_interval           (RTPSessionStats *stats,
+                                                     gdouble min_interval);
+
+
+gboolean __g_socket_address_equal (GSocketAddress *a, GSocketAddress *b);
+gchar * __g_socket_address_to_string (GSocketAddress * addr);
+
+#endif /* __RTP_STATS_H__ */
diff --git a/wfdmanager/wfdrtpbuffer/wfdrtpbuffer.c b/wfdmanager/wfdrtpbuffer/wfdrtpbuffer.c
new file mode 100755 (executable)
index 0000000..6874a0a
--- /dev/null
@@ -0,0 +1,1013 @@
+/* GStreamer
+ * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#include <string.h>
+#include <stdlib.h>
+
+#include <gst/rtp/gstrtpbuffer.h>
+#include <gst/rtp/gstrtcpbuffer.h>
+
+#include "wfdrtpbuffer.h"
+
+GST_DEBUG_CATEGORY_STATIC (wfd_rtp_buffer_debug);
+#define GST_CAT_DEFAULT wfd_rtp_buffer_debug
+
+#define MAX_WINDOW     WFD_RTP_BUFFER_MAX_WINDOW
+#define MAX_TIME       (2 * GST_SECOND)
+
+/* signals and args */
+enum
+{
+  LAST_SIGNAL
+};
+
+enum
+{
+  PROP_0
+};
+
+/* GObject vmethods */
+static void wfd_rtp_buffer_finalize (GObject * object);
+
+GType
+wfd_rtp_buffer_mode_get_type (void)
+{
+  static GType jitter_buffer_mode_type = 0;
+  static const GEnumValue jitter_buffer_modes[] = {
+    {WFD_RTP_BUFFER_MODE_NONE, "Only use RTP timestamps", "none"},
+    {WFD_RTP_BUFFER_MODE_SLAVE, "Slave receiver to sender clock", "slave"},
+    {WFD_RTP_BUFFER_MODE_BUFFER, "Do low/high watermark buffering",
+        "buffer"},
+    {WFD_RTP_BUFFER_MODE_SYNCED, "Synchronized sender and receiver clocks",
+        "synced"},
+    {0, NULL, NULL},
+  };
+
+  if (!jitter_buffer_mode_type) {
+    jitter_buffer_mode_type =
+        g_enum_register_static ("WfdRTPBufferMode", jitter_buffer_modes);
+  }
+  return jitter_buffer_mode_type;
+}
+
+/* static guint wfd_rtp_buffer_signals[LAST_SIGNAL] = { 0 }; */
+
+G_DEFINE_TYPE (WfdRTPBuffer, wfd_rtp_buffer, G_TYPE_OBJECT);
+
+static void
+wfd_rtp_buffer_class_init (WfdRTPBufferClass * klass)
+{
+  GObjectClass *gobject_class;
+
+  gobject_class = (GObjectClass *) klass;
+
+  gobject_class->finalize = wfd_rtp_buffer_finalize;
+
+  GST_DEBUG_CATEGORY_INIT (wfd_rtp_buffer_debug, "wfdrtpbuffer", 0,
+      "WFD RTP Buffer");
+}
+
+static void
+wfd_rtp_buffer_init (WfdRTPBuffer * jbuf)
+{
+  jbuf->packets = g_queue_new ();
+  jbuf->mode = WFD_RTP_BUFFER_MODE_SLAVE;
+
+  wfd_rtp_buffer_reset_skew (jbuf);
+}
+
+static void
+wfd_rtp_buffer_finalize (GObject * object)
+{
+  WfdRTPBuffer *jbuf;
+
+  jbuf = WFD_RTP_BUFFER_CAST (object);
+
+  g_queue_free (jbuf->packets);
+
+  G_OBJECT_CLASS (wfd_rtp_buffer_parent_class)->finalize (object);
+}
+
+/**
+ * wfd_rtp_buffer_new:
+ *
+ * Create an #WfdRTPBuffer.
+ *
+ * Returns: a new #WfdRTPBuffer. Use g_object_unref() after usage.
+ */
+WfdRTPBuffer *
+wfd_rtp_buffer_new (void)
+{
+  WfdRTPBuffer *jbuf;
+
+  jbuf = g_object_new (WFD_TYPE_RTP_BUFFER, NULL);
+
+  return jbuf;
+}
+
+/**
+ * wfd_rtp_buffer_get_mode:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Get the current jitterbuffer mode.
+ *
+ * Returns: the current jitterbuffer mode.
+ */
+WfdRTPBufferMode
+wfd_rtp_buffer_get_mode (WfdRTPBuffer * jbuf)
+{
+  return jbuf->mode;
+}
+
+/**
+ * wfd_rtp_buffer_set_mode:
+ * @jbuf: an #WfdRTPBuffer
+ * @mode: a #WfdRTPBufferMode
+ *
+ * Set the buffering and clock slaving algorithm used in the @jbuf.
+ */
+void
+wfd_rtp_buffer_set_mode (WfdRTPBuffer * jbuf, WfdRTPBufferMode mode)
+{
+  jbuf->mode = mode;
+}
+
+GstClockTime
+wfd_rtp_buffer_get_delay (WfdRTPBuffer * jbuf)
+{
+  return jbuf->delay;
+}
+
+void
+wfd_rtp_buffer_set_delay (WfdRTPBuffer * jbuf, GstClockTime delay)
+{
+  jbuf->delay = delay;
+  jbuf->low_level = (delay * 15) / 100;
+  /* the high level is at 90% in order to release packets before we fill up the
+   * buffer up to the latency */
+  jbuf->high_level = (delay * 90) / 100;
+
+  GST_DEBUG ("delay %" GST_TIME_FORMAT ", min %" GST_TIME_FORMAT ", max %"
+      GST_TIME_FORMAT, GST_TIME_ARGS (jbuf->delay),
+      GST_TIME_ARGS (jbuf->low_level), GST_TIME_ARGS (jbuf->high_level));
+}
+
+/**
+ * wfd_rtp_buffer_set_clock_rate:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Set the clock rate in the jitterbuffer.
+ */
+void
+wfd_rtp_buffer_set_clock_rate (WfdRTPBuffer * jbuf, guint32 clock_rate)
+{
+  if (jbuf->clock_rate != clock_rate) {
+    if (jbuf->clock_rate == -1) {
+      GST_DEBUG ("Clock rate changed from %" G_GUINT32_FORMAT " to %"
+          G_GUINT32_FORMAT, jbuf->clock_rate, clock_rate);
+    } else {
+      GST_WARNING ("Clock rate changed from %" G_GUINT32_FORMAT " to %"
+          G_GUINT32_FORMAT, jbuf->clock_rate, clock_rate);
+    }
+    jbuf->clock_rate = clock_rate;
+    wfd_rtp_buffer_reset_skew (jbuf);
+  }
+}
+
+/**
+ * wfd_rtp_buffer_get_clock_rate:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Get the currently configure clock rate in @jbuf.
+ *
+ * Returns: the current clock-rate
+ */
+guint32
+wfd_rtp_buffer_get_clock_rate (WfdRTPBuffer * jbuf)
+{
+  return jbuf->clock_rate;
+}
+
+/**
+ * wfd_rtp_buffer_reset_skew:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Reset the skew calculations in @jbuf.
+ */
+void
+wfd_rtp_buffer_reset_skew (WfdRTPBuffer * jbuf)
+{
+  jbuf->base_time = -1;
+  jbuf->base_rtptime = -1;
+  jbuf->base_extrtp = -1;
+  jbuf->ext_rtptime = -1;
+  jbuf->last_rtptime = -1;
+  jbuf->window_pos = 0;
+  jbuf->window_filling = TRUE;
+  jbuf->window_min = 0;
+  jbuf->skew = 0;
+  jbuf->prev_send_diff = -1;
+  jbuf->prev_out_time = -1;
+  GST_DEBUG ("reset skew correction");
+}
+
+/**
+ * wfd_rtp_buffer_disable_buffering:
+ * @jbuf: an #WfdRTPBuffer
+ * @disabled: the new state
+ *
+ * Enable or disable buffering on @jbuf.
+ */
+void
+wfd_rtp_buffer_disable_buffering (WfdRTPBuffer * jbuf, gboolean disabled)
+{
+  jbuf->buffering_disabled = disabled;
+}
+
+static void
+wfd_rtp_buffer_resync (WfdRTPBuffer * jbuf, GstClockTime time,
+    GstClockTime gstrtptime, guint64 ext_rtptime, gboolean reset_skew)
+{
+  jbuf->base_time = time;
+  jbuf->base_rtptime = gstrtptime;
+  jbuf->base_extrtp = ext_rtptime;
+  jbuf->prev_out_time = -1;
+  jbuf->prev_send_diff = -1;
+  if (reset_skew) {
+    jbuf->window_filling = TRUE;
+    jbuf->window_pos = 0;
+    jbuf->window_min = 0;
+    jbuf->window_size = 0;
+    jbuf->skew = 0;
+  }
+}
+
+static guint64
+get_buffer_level (WfdRTPBuffer * jbuf)
+{
+  WfdRTPBufferItem *high_buf = NULL, *low_buf = NULL;
+  guint64 level;
+
+  /* first first buffer with timestamp */
+  high_buf = (WfdRTPBufferItem *) g_queue_peek_tail_link (jbuf->packets);
+  while (high_buf) {
+    if (high_buf->dts != -1 || high_buf->pts != -1)
+      break;
+
+    high_buf = (WfdRTPBufferItem *) g_list_previous (high_buf);
+  }
+
+  low_buf = (WfdRTPBufferItem *) g_queue_peek_head_link (jbuf->packets);
+  while (low_buf) {
+    if (low_buf->dts != -1 || low_buf->pts != -1)
+      break;
+
+    low_buf = (WfdRTPBufferItem *) g_list_next (low_buf);
+  }
+
+  if (!high_buf || !low_buf || high_buf == low_buf) {
+    level = 0;
+  } else {
+    guint64 high_ts, low_ts;
+
+    high_ts = high_buf->dts != -1 ? high_buf->dts : high_buf->pts;
+    low_ts = low_buf->dts != -1 ? low_buf->dts : low_buf->pts;
+
+    if (high_ts > low_ts)
+      level = high_ts - low_ts;
+    else
+      level = 0;
+
+    GST_LOG_OBJECT (jbuf,
+        "low %" GST_TIME_FORMAT " high %" GST_TIME_FORMAT " level %"
+        G_GUINT64_FORMAT, GST_TIME_ARGS (low_ts), GST_TIME_ARGS (high_ts),
+        level);
+  }
+  return level;
+}
+
+static void
+update_buffer_level (WfdRTPBuffer * jbuf, gint * percent)
+{
+  gboolean post = FALSE;
+  guint64 level;
+
+  level = get_buffer_level (jbuf);
+  GST_DEBUG ("buffer level %" GST_TIME_FORMAT, GST_TIME_ARGS (level));
+
+  if (jbuf->buffering_disabled) {
+    GST_DEBUG ("buffering is disabled");
+    level = jbuf->high_level;
+  }
+
+  if (jbuf->buffering) {
+    post = TRUE;
+    if (level >= jbuf->high_level) {
+      GST_DEBUG ("buffering finished");
+      jbuf->buffering = FALSE;
+    }
+  } else {
+    if (level < jbuf->low_level) {
+      GST_DEBUG ("buffering started");
+      jbuf->buffering = TRUE;
+      post = TRUE;
+    }
+  }
+  if (post) {
+    gint perc;
+
+    if (jbuf->buffering && (jbuf->high_level != 0)) {
+      perc = (level * 100 / jbuf->high_level);
+      perc = MIN (perc, 100);
+    } else {
+      perc = 100;
+    }
+
+    if (percent)
+      *percent = perc;
+
+    GST_DEBUG ("buffering %d", perc);
+  }
+}
+
+/* For the clock skew we use a windowed low point averaging algorithm as can be
+ * found in Fober, Orlarey and Letz, 2005, "Real Time Clock Skew Estimation
+ * over Network Delays":
+ * http://www.grame.fr/Ressources/pub/TR-050601.pdf
+ * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.102.1546
+ *
+ * The idea is that the jitter is composed of:
+ *
+ *  J = N + n
+ *
+ *   N   : a constant network delay.
+ *   n   : random added noise. The noise is concentrated around 0
+ *
+ * In the receiver we can track the elapsed time at the sender with:
+ *
+ *  send_diff(i) = (Tsi - Ts0);
+ *
+ *   Tsi : The time at the sender at packet i
+ *   Ts0 : The time at the sender at the first packet
+ *
+ * This is the difference between the RTP timestamp in the first received packet
+ * and the current packet.
+ *
+ * At the receiver we have to deal with the jitter introduced by the network.
+ *
+ *  recv_diff(i) = (Tri - Tr0)
+ *
+ *   Tri : The time at the receiver at packet i
+ *   Tr0 : The time at the receiver at the first packet
+ *
+ * Both of these values contain a jitter Ji, a jitter for packet i, so we can
+ * write:
+ *
+ *  recv_diff(i) = (Cri + D + ni) - (Cr0 + D + n0))
+ *
+ *    Cri    : The time of the clock at the receiver for packet i
+ *    D + ni : The jitter when receiving packet i
+ *
+ * We see that the network delay is irrelevant here as we can elliminate D:
+ *
+ *  recv_diff(i) = (Cri + ni) - (Cr0 + n0))
+ *
+ * The drift is now expressed as:
+ *
+ *  Drift(i) = recv_diff(i) - send_diff(i);
+ *
+ * We now keep the W latest values of Drift and find the minimum (this is the
+ * one with the lowest network jitter and thus the one which is least affected
+ * by it). We average this lowest value to smooth out the resulting network skew.
+ *
+ * Both the window and the weighting used for averaging influence the accuracy
+ * of the drift estimation. Finding the correct parameters turns out to be a
+ * compromise between accuracy and inertia.
+ *
+ * We use a 2 second window or up to 512 data points, which is statistically big
+ * enough to catch spikes (FIXME, detect spikes).
+ * We also use a rather large weighting factor (125) to smoothly adapt. During
+ * startup, when filling the window, we use a parabolic weighting factor, the
+ * more the window is filled, the faster we move to the detected possible skew.
+ *
+ * Returns: @time adjusted with the clock skew.
+ */
+static GstClockTime
+calculate_skew (WfdRTPBuffer * jbuf, guint32 rtptime, GstClockTime time)
+{
+  guint64 ext_rtptime;
+  guint64 send_diff, recv_diff;
+  gint64 delta;
+  gint64 old;
+  gint pos, i;
+  GstClockTime gstrtptime, out_time;
+  guint64 slope;
+
+  ext_rtptime = gst_rtp_buffer_ext_timestamp (&jbuf->ext_rtptime, rtptime);
+
+  if (jbuf->last_rtptime != -1 && ext_rtptime == jbuf->last_rtptime)
+    return jbuf->prev_out_time;
+
+  gstrtptime =
+      gst_util_uint64_scale_int (ext_rtptime, GST_SECOND, jbuf->clock_rate);
+
+  /* keep track of the last extended rtptime */
+  jbuf->last_rtptime = ext_rtptime;
+
+  /* first time, lock on to time and gstrtptime */
+  if (G_UNLIKELY (jbuf->base_time == -1)) {
+    jbuf->base_time = time;
+    jbuf->prev_out_time = -1;
+    GST_DEBUG ("Taking new base time %" GST_TIME_FORMAT, GST_TIME_ARGS (time));
+  }
+  if (G_UNLIKELY (jbuf->base_rtptime == -1)) {
+    jbuf->base_rtptime = gstrtptime;
+    jbuf->base_extrtp = ext_rtptime;
+    jbuf->prev_send_diff = -1;
+    GST_DEBUG ("Taking new base rtptime %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (gstrtptime));
+  }
+
+  if (G_LIKELY (gstrtptime >= jbuf->base_rtptime))
+    send_diff = gstrtptime - jbuf->base_rtptime;
+  else if (time != -1) {
+    /* elapsed time at sender, timestamps can go backwards and thus be smaller
+     * than our base time, take a new base time in that case. */
+    GST_WARNING ("backward timestamps at server, taking new base time");
+    wfd_rtp_buffer_resync (jbuf, time, gstrtptime, ext_rtptime, FALSE);
+    send_diff = 0;
+  } else {
+    GST_WARNING ("backward timestamps at server but no timestamps");
+    send_diff = 0;
+    /* at least try to get a new timestamp.. */
+    jbuf->base_time = -1;
+  }
+
+  GST_DEBUG ("extrtp %" G_GUINT64_FORMAT ", gstrtp %" GST_TIME_FORMAT ", base %"
+      GST_TIME_FORMAT ", send_diff %" GST_TIME_FORMAT, ext_rtptime,
+      GST_TIME_ARGS (gstrtptime), GST_TIME_ARGS (jbuf->base_rtptime),
+      GST_TIME_ARGS (send_diff));
+
+  /* we don't have an arrival timestamp so we can't do skew detection. we
+   * should still apply a timestamp based on RTP timestamp and base_time */
+  if (time == -1 || jbuf->base_time == -1)
+    goto no_skew;
+
+  /* elapsed time at receiver, includes the jitter */
+  recv_diff = time - jbuf->base_time;
+
+  /* measure the diff */
+  delta = ((gint64) recv_diff) - ((gint64) send_diff);
+
+  /* measure the slope, this gives a rought estimate between the sender speed
+   * and the receiver speed. This should be approximately 8, higher values
+   * indicate a burst (especially when the connection starts) */
+  if (recv_diff > 0)
+    slope = (send_diff * 8) / recv_diff;
+  else
+    slope = 8;
+
+  GST_DEBUG ("time %" GST_TIME_FORMAT ", base %" GST_TIME_FORMAT ", recv_diff %"
+      GST_TIME_FORMAT ", slope %" G_GUINT64_FORMAT, GST_TIME_ARGS (time),
+      GST_TIME_ARGS (jbuf->base_time), GST_TIME_ARGS (recv_diff), slope);
+
+  /* if the difference between the sender timeline and the receiver timeline
+   * changed too quickly we have to resync because the server likely restarted
+   * its timestamps. */
+  if (ABS (delta - jbuf->skew) > GST_SECOND) {
+    GST_WARNING ("delta - skew: %" GST_TIME_FORMAT " too big, reset skew",
+        GST_TIME_ARGS (ABS (delta - jbuf->skew)));
+    wfd_rtp_buffer_resync (jbuf, time, gstrtptime, ext_rtptime, TRUE);
+    send_diff = 0;
+    delta = 0;
+  }
+
+  pos = jbuf->window_pos;
+
+  if (G_UNLIKELY (jbuf->window_filling)) {
+    /* we are filling the window */
+    GST_DEBUG ("filling %d, delta %" G_GINT64_FORMAT, pos, delta);
+    jbuf->window[pos++] = delta;
+    /* calc the min delta we observed */
+    if (G_UNLIKELY (pos == 1 || delta < jbuf->window_min))
+      jbuf->window_min = delta;
+
+    if (G_UNLIKELY (send_diff >= MAX_TIME || pos >= MAX_WINDOW)) {
+      jbuf->window_size = pos;
+
+      /* window filled */
+      GST_DEBUG ("min %" G_GINT64_FORMAT, jbuf->window_min);
+
+      /* the skew is now the min */
+      jbuf->skew = jbuf->window_min;
+      jbuf->window_filling = FALSE;
+    } else {
+      gint perc_time, perc_window, perc;
+
+      /* figure out how much we filled the window, this depends on the amount of
+       * time we have or the max number of points we keep. */
+      perc_time = send_diff * 100 / MAX_TIME;
+      perc_window = pos * 100 / MAX_WINDOW;
+      perc = MAX (perc_time, perc_window);
+
+      /* make a parabolic function, the closer we get to the MAX, the more value
+       * we give to the scaling factor of the new value */
+      perc = perc * perc;
+
+      /* quickly go to the min value when we are filling up, slowly when we are
+       * just starting because we're not sure it's a good value yet. */
+      jbuf->skew =
+          (perc * jbuf->window_min + ((10000 - perc) * jbuf->skew)) / 10000;
+      jbuf->window_size = pos + 1;
+    }
+  } else {
+    /* pick old value and store new value. We keep the previous value in order
+     * to quickly check if the min of the window changed */
+    old = jbuf->window[pos];
+    jbuf->window[pos++] = delta;
+
+    if (G_UNLIKELY (delta <= jbuf->window_min)) {
+      /* if the new value we inserted is smaller or equal to the current min,
+       * it becomes the new min */
+      jbuf->window_min = delta;
+    } else if (G_UNLIKELY (old == jbuf->window_min)) {
+      gint64 min = G_MAXINT64;
+
+      /* if we removed the old min, we have to find a new min */
+      for (i = 0; i < jbuf->window_size; i++) {
+        /* we found another value equal to the old min, we can stop searching now */
+        if (jbuf->window[i] == old) {
+          min = old;
+          break;
+        }
+        if (jbuf->window[i] < min)
+          min = jbuf->window[i];
+      }
+      jbuf->window_min = min;
+    }
+    /* average the min values */
+    jbuf->skew = (jbuf->window_min + (124 * jbuf->skew)) / 125;
+    GST_DEBUG ("delta %" G_GINT64_FORMAT ", new min: %" G_GINT64_FORMAT,
+        delta, jbuf->window_min);
+  }
+  /* wrap around in the window */
+  if (G_UNLIKELY (pos >= jbuf->window_size))
+    pos = 0;
+  jbuf->window_pos = pos;
+
+no_skew:
+  /* the output time is defined as the base timestamp plus the RTP time
+   * adjusted for the clock skew .*/
+  if (jbuf->base_time != -1) {
+    out_time = jbuf->base_time + send_diff;
+    /* skew can be negative and we don't want to make invalid timestamps */
+    if (jbuf->skew < 0 && out_time < -jbuf->skew) {
+      out_time = 0;
+    } else {
+      out_time += jbuf->skew;
+    }
+    /* check if timestamps are not going backwards, we can only check this if we
+     * have a previous out time and a previous send_diff */
+    if (G_LIKELY (jbuf->prev_out_time != -1 && jbuf->prev_send_diff != -1)) {
+      /* now check for backwards timestamps */
+      if (G_UNLIKELY (
+              /* if the server timestamps went up and the out_time backwards */
+              (send_diff > jbuf->prev_send_diff
+                  && out_time < jbuf->prev_out_time) ||
+              /* if the server timestamps went backwards and the out_time forwards */
+              (send_diff < jbuf->prev_send_diff
+                  && out_time > jbuf->prev_out_time) ||
+              /* if the server timestamps did not change */
+              send_diff == jbuf->prev_send_diff)) {
+        GST_DEBUG ("backwards timestamps, using previous time");
+        out_time = jbuf->prev_out_time;
+      }
+    }
+    if (time != -1 && out_time + jbuf->delay < time) {
+      /* if we are going to produce a timestamp that is later than the input
+       * timestamp, we need to reset the jitterbuffer. Likely the server paused
+       * temporarily */
+      GST_DEBUG ("out %" GST_TIME_FORMAT " + %" G_GUINT64_FORMAT " < time %"
+          GST_TIME_FORMAT ", reset jitterbuffer", GST_TIME_ARGS (out_time),
+          jbuf->delay, GST_TIME_ARGS (time));
+      wfd_rtp_buffer_resync (jbuf, time, gstrtptime, ext_rtptime, TRUE);
+      out_time = time;
+      send_diff = 0;
+    }
+  } else
+    out_time = -1;
+
+  jbuf->prev_out_time = out_time;
+  jbuf->prev_send_diff = send_diff;
+
+  GST_DEBUG ("skew %" G_GINT64_FORMAT ", out %" GST_TIME_FORMAT,
+      jbuf->skew, GST_TIME_ARGS (out_time));
+
+  return out_time;
+}
+
+static void
+queue_do_insert (WfdRTPBuffer * jbuf, GList * list, GList * item)
+{
+  GQueue *queue = jbuf->packets;
+
+  /* It's more likely that the packet was inserted at the tail of the queue */
+  if (G_LIKELY (list)) {
+    item->prev = list;
+    item->next = list->next;
+    list->next = item;
+  } else {
+    item->prev = NULL;
+    item->next = queue->head;
+    queue->head = item;
+  }
+  if (item->next)
+    item->next->prev = item;
+  else
+    queue->tail = item;
+  queue->length++;
+}
+
+/**
+ * wfd_rtp_buffer_insert:
+ * @jbuf: an #WfdRTPBuffer
+ * @item: an #WfdRTPBufferItem to insert
+ * @head: TRUE when the head element changed.
+ * @percent: the buffering percent after insertion
+ *
+ * Inserts @item into the packet queue of @jbuf. The sequence number of the
+ * packet will be used to sort the packets. This function takes ownerhip of
+ * @buf when the function returns %TRUE.
+ *
+ * When @head is %TRUE, the new packet was added at the head of the queue and
+ * will be available with the next call to wfd_rtp_buffer_pop() and
+ * wfd_rtp_buffer_peek().
+ *
+ * Returns: %FALSE if a packet with the same number already existed.
+ */
+gboolean
+wfd_rtp_buffer_insert (WfdRTPBuffer * jbuf, WfdRTPBufferItem * item,
+    gboolean * head, gint * percent)
+{
+  GList *list, *event = NULL;
+  guint32 rtptime;
+  guint16 seqnum;
+  GstClockTime dts;
+
+  g_return_val_if_fail (jbuf != NULL, FALSE);
+  g_return_val_if_fail (item != NULL, FALSE);
+
+  list = jbuf->packets->tail;
+
+  /* no seqnum, simply append then */
+  if (item->seqnum == -1)
+    goto append;
+
+  seqnum = item->seqnum;
+
+  /* loop the list to skip strictly larger seqnum buffers */
+  for (; list; list = g_list_previous (list)) {
+    guint16 qseq;
+    gint gap;
+    WfdRTPBufferItem *qitem = (WfdRTPBufferItem *) list;
+
+    if (qitem->seqnum == -1) {
+      /* keep a pointer to the first consecutive event if not already
+       * set. we will insert the packet after the event if we can't find
+       * a packet with lower sequence number before the event. */
+      if (event == NULL)
+        event = list;
+      continue;
+    }
+
+    qseq = qitem->seqnum;
+
+    /* compare the new seqnum to the one in the buffer */
+    gap = gst_rtp_buffer_compare_seqnum (seqnum, qseq);
+
+    /* we hit a packet with the same seqnum, notify a duplicate */
+    if (G_UNLIKELY (gap == 0))
+      goto duplicate;
+
+    /* seqnum > qseq, we can stop looking */
+    if (G_LIKELY (gap < 0))
+      break;
+
+    /* if we've found a packet with greater sequence number, cleanup the
+     * event pointer as the packet will be inserted before the event */
+    event = NULL;
+  }
+
+  /* if event is set it means that packets before the event had smaller
+   * sequence number, so we will insert our packet after the event */
+  if (event)
+    list = event;
+
+  dts = item->dts;
+  if (item->rtptime == -1)
+    goto append;
+
+  rtptime = item->rtptime;
+
+  /* rtp time jumps are checked for during skew calculation, but bypassed
+   * in other mode, so mind those here and reset jb if needed.
+   * Only reset if valid input time, which is likely for UDP input
+   * where we expect this might happen due to async thread effects
+   * (in seek and state change cycles), but not so much for TCP input */
+  if (GST_CLOCK_TIME_IS_VALID (dts) &&
+      jbuf->mode != WFD_RTP_BUFFER_MODE_SLAVE &&
+      jbuf->base_time != -1 && jbuf->last_rtptime != -1) {
+    GstClockTime ext_rtptime = jbuf->ext_rtptime;
+
+    ext_rtptime = gst_rtp_buffer_ext_timestamp (&ext_rtptime, rtptime);
+    if (ext_rtptime > jbuf->last_rtptime + 3 * jbuf->clock_rate ||
+        ext_rtptime + 3 * jbuf->clock_rate < jbuf->last_rtptime) {
+      /* reset even if we don't have valid incoming time;
+       * still better than producing possibly very bogus output timestamp */
+      GST_WARNING ("rtp delta too big, reset skew");
+      wfd_rtp_buffer_reset_skew (jbuf);
+    }
+  }
+
+  switch (jbuf->mode) {
+    case WFD_RTP_BUFFER_MODE_NONE:
+    case WFD_RTP_BUFFER_MODE_BUFFER:
+      /* send 0 as the first timestamp and -1 for the other ones. This will
+       * interpollate them from the RTP timestamps with a 0 origin. In buffering
+       * mode we will adjust the outgoing timestamps according to the amount of
+       * time we spent buffering. */
+      if (jbuf->base_time == -1)
+        dts = 0;
+      else
+        dts = -1;
+      break;
+    case WFD_RTP_BUFFER_MODE_SYNCED:
+      /* synchronized clocks, take first timestamp as base, use RTP timestamps
+       * to interpolate */
+      if (jbuf->base_time != -1)
+        dts = -1;
+      break;
+    case WFD_RTP_BUFFER_MODE_SLAVE:
+    default:
+      break;
+  }
+  /* do skew calculation by measuring the difference between rtptime and the
+   * receive dts, this function will return the skew corrected rtptime. */
+  item->pts = calculate_skew (jbuf, rtptime, dts);
+
+append:
+  queue_do_insert (jbuf, list, (GList *) item);
+
+  /* buffering mode, update buffer stats */
+  if (jbuf->mode == WFD_RTP_BUFFER_MODE_BUFFER)
+    update_buffer_level (jbuf, percent);
+  else if (percent)
+    *percent = -1;
+
+  /* head was changed when we did not find a previous packet, we set the return
+   * flag when requested. */
+  if (G_LIKELY (head))
+    *head = (list == NULL);
+
+  return TRUE;
+
+  /* ERRORS */
+duplicate:
+  {
+    GST_WARNING ("duplicate packet %d found", (gint) seqnum);
+    return FALSE;
+  }
+}
+
+/**
+ * wfd_rtp_buffer_pop:
+ * @jbuf: an #WfdRTPBuffer
+ * @percent: the buffering percent
+ *
+ * Pops the oldest buffer from the packet queue of @jbuf. The popped buffer will
+ * have its timestamp adjusted with the incomming running_time and the detected
+ * clock skew.
+ *
+ * Returns: a #GstBuffer or %NULL when there was no packet in the queue.
+ */
+WfdRTPBufferItem *
+wfd_rtp_buffer_pop (WfdRTPBuffer * jbuf, gint * percent)
+{
+  GList *item = NULL;
+  GQueue *queue;
+
+  g_return_val_if_fail (jbuf != NULL, NULL);
+
+  queue = jbuf->packets;
+
+  item = queue->head;
+  if (item) {
+    queue->head = item->next;
+    if (queue->head)
+      queue->head->prev = NULL;
+    else
+      queue->tail = NULL;
+    queue->length--;
+  }
+
+  /* buffering mode, update buffer stats */
+  if (jbuf->mode == WFD_RTP_BUFFER_MODE_BUFFER)
+    update_buffer_level (jbuf, percent);
+  else if (percent)
+    *percent = -1;
+
+  return (WfdRTPBufferItem *) item;
+}
+
+/**
+ * wfd_rtp_buffer_peek:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Peek the oldest buffer from the packet queue of @jbuf.
+ *
+ * See wfd_rtp_buffer_insert() to check when an older packet was
+ * added.
+ *
+ * Returns: a #GstBuffer or %NULL when there was no packet in the queue.
+ */
+WfdRTPBufferItem *
+wfd_rtp_buffer_peek (WfdRTPBuffer * jbuf)
+{
+  g_return_val_if_fail (jbuf != NULL, NULL);
+
+  return (WfdRTPBufferItem *) jbuf->packets->head;
+}
+
+/**
+ * wfd_rtp_buffer_flush:
+ * @jbuf: an #WfdRTPBuffer
+ * @free_func: function to free each item
+ * @user_data: user data passed to @free_func
+ *
+ * Flush all packets from the jitterbuffer.
+ */
+void
+wfd_rtp_buffer_flush (WfdRTPBuffer * jbuf, GFunc free_func,
+    gpointer user_data)
+{
+  GList *item;
+
+  g_return_if_fail (jbuf != NULL);
+  g_return_if_fail (free_func != NULL);
+
+  while ((item = g_queue_pop_head_link (jbuf->packets)))
+    free_func ((WfdRTPBufferItem *) item, user_data);
+}
+
+/**
+ * wfd_rtp_buffer_is_buffering:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Check if @jbuf is buffering currently. Users of the jitterbuffer should not
+ * pop packets while in buffering mode.
+ *
+ * Returns: the buffering state of @jbuf
+ */
+gboolean
+wfd_rtp_buffer_is_buffering (WfdRTPBuffer * jbuf)
+{
+  return jbuf->buffering && !jbuf->buffering_disabled;
+}
+
+/**
+ * wfd_rtp_buffer_set_buffering:
+ * @jbuf: an #WfdRTPBuffer
+ * @buffering: the new buffering state
+ *
+ * Forces @jbuf to go into the buffering state.
+ */
+void
+wfd_rtp_buffer_set_buffering (WfdRTPBuffer * jbuf, gboolean buffering)
+{
+  jbuf->buffering = buffering;
+}
+
+/**
+ * wfd_rtp_buffer_get_percent:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Get the buffering percent of the jitterbuffer.
+ *
+ * Returns: the buffering percent
+ */
+gint
+wfd_rtp_buffer_get_percent (WfdRTPBuffer * jbuf)
+{
+  gint percent;
+  guint64 level;
+
+  if (G_UNLIKELY (jbuf->high_level == 0))
+    return 100;
+
+  if (G_UNLIKELY (jbuf->buffering_disabled))
+    return 100;
+
+  level = get_buffer_level (jbuf);
+  percent = (level * 100 / jbuf->high_level);
+  percent = MIN (percent, 100);
+
+  return percent;
+}
+
+/**
+ * wfd_rtp_buffer_num_packets:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Get the number of packets currently in "jbuf.
+ *
+ * Returns: The number of packets in @jbuf.
+ */
+guint
+wfd_rtp_buffer_num_packets (WfdRTPBuffer * jbuf)
+{
+  g_return_val_if_fail (jbuf != NULL, 0);
+
+  return jbuf->packets->length;
+}
+
+/**
+ * wfd_rtp_buffer_get_ts_diff:
+ * @jbuf: an #WfdRTPBuffer
+ *
+ * Get the difference between the timestamps of first and last packet in the
+ * jitterbuffer.
+ *
+ * Returns: The difference expressed in the timestamp units of the packets.
+ */
+guint32
+wfd_rtp_buffer_get_ts_diff (WfdRTPBuffer * jbuf)
+{
+  guint64 high_ts, low_ts;
+  WfdRTPBufferItem *high_buf, *low_buf;
+  guint32 result;
+
+  g_return_val_if_fail (jbuf != NULL, 0);
+
+  high_buf = (WfdRTPBufferItem *) g_queue_peek_head_link (jbuf->packets);
+  low_buf = (WfdRTPBufferItem *) g_queue_peek_tail_link (jbuf->packets);
+
+  if (!high_buf || !low_buf || high_buf == low_buf)
+    return 0;
+
+  high_ts = high_buf->rtptime;
+  low_ts = low_buf->rtptime;
+
+  /* it needs to work if ts wraps */
+  if (high_ts >= low_ts) {
+    result = (guint32) (high_ts - low_ts);
+  } else {
+    result = (guint32) (high_ts + G_MAXUINT32 + 1 - low_ts);
+  }
+  return result;
+}
+
+/**
+ * wfd_rtp_buffer_get_sync:
+ * @jbuf: an #WfdRTPBuffer
+ * @rtptime: result RTP time
+ * @timestamp: result GStreamer timestamp
+ * @clock_rate: clock-rate of @rtptime
+ * @last_rtptime: last seen rtptime.
+ *
+ * Calculates the relation between the RTP timestamp and the GStreamer timestamp
+ * used for constructing timestamps.
+ *
+ * For extended RTP timestamp @rtptime with a clock-rate of @clock_rate,
+ * the GStreamer timestamp is currently @timestamp.
+ *
+ * The last seen extended RTP timestamp with clock-rate @clock-rate is returned in
+ * @last_rtptime.
+ */
+void
+wfd_rtp_buffer_get_sync (WfdRTPBuffer * jbuf, guint64 * rtptime,
+    guint64 * timestamp, guint32 * clock_rate, guint64 * last_rtptime)
+{
+  if (rtptime)
+    *rtptime = jbuf->base_extrtp;
+  if (timestamp)
+    *timestamp = jbuf->base_time + jbuf->skew;
+  if (clock_rate)
+    *clock_rate = jbuf->clock_rate;
+  if (last_rtptime)
+    *last_rtptime = jbuf->last_rtptime;
+}
diff --git a/wfdmanager/wfdrtpbuffer/wfdrtpbuffer.h b/wfdmanager/wfdrtpbuffer/wfdrtpbuffer.h
new file mode 100755 (executable)
index 0000000..f704d2a
--- /dev/null
@@ -0,0 +1,177 @@
+/* GStreamer
+ * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef __WFD_RTP_BUFFER_H__
+#define __WFD_RTP_BUFFER_H__
+
+#include <gst/gst.h>
+#include <gst/rtp/gstrtcpbuffer.h>
+
+typedef struct _WfdRTPBuffer WfdRTPBuffer;
+typedef struct _WfdRTPBufferClass WfdRTPBufferClass;
+typedef struct _WfdRTPBufferItem WfdRTPBufferItem;
+
+#define WFD_TYPE_RTP_BUFFER             (wfd_rtp_buffer_get_type())
+#define WFD_RTP_BUFFER(src)             (G_TYPE_CHECK_INSTANCE_CAST((src),WFD_TYPE_RTP_BUFFER,WfdRTPBuffer))
+#define WFD_RTP_BUFFER_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass),WFD_TYPE_RTP_BUFFER,WfdRTPBufferClass))
+#define WFD_IS_RTP_BUFFER(src)          (G_TYPE_CHECK_INSTANCE_TYPE((src),WFD_TYPE_RTP_BUFFER))
+#define WFD_IS_RTP_BUFFER_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),WFD_TYPE_RTP_BUFFER))
+#define WFD_RTP_BUFFER_CAST(src)        ((WfdRTPBuffer *)(src))
+
+/**
+ * WfdRTPBufferMode:
+ *
+ * WFD_RTP_BUFFER_MODE_NONE: don't do any skew correction, outgoing
+ *    timestamps are calculated directly from the RTP timestamps. This mode is
+ *    good for recording but not for real-time applications.
+ * WFD_RTP_BUFFER_MODE_SLAVE: calculate the skew between sender and receiver
+ *    and produce smoothed adjusted outgoing timestamps. This mode is good for
+ *    low latency communications.
+ * WFD_RTP_BUFFER_MODE_BUFFER: buffer packets between low/high watermarks.
+ *    This mode is good for streaming communication.
+ * WFD_RTP_BUFFER_MODE_SYNCED: sender and receiver clocks are synchronized,
+ *    like #WFD_RTP_BUFFER_MODE_SLAVE but skew is assumed to be 0. Good for
+ *    low latency communication when sender and receiver clocks are
+ *    synchronized and there is thus no clock skew.
+ * WFD_RTP_BUFFER_MODE_LAST: last buffer mode.
+ *
+ * The different buffer modes for a jitterbuffer.
+ */
+typedef enum {
+  WFD_RTP_BUFFER_MODE_NONE    = 0,
+  WFD_RTP_BUFFER_MODE_SLAVE   = 1,
+  WFD_RTP_BUFFER_MODE_BUFFER  = 2,
+  /* FIXME 3 is missing because it was used for 'auto' in jitterbuffer */
+  WFD_RTP_BUFFER_MODE_SYNCED  = 4,
+  WFD_RTP_BUFFER_MODE_LAST
+} WfdRTPBufferMode;
+
+#define WFD_TYPE_RTP_BUFFER_MODE (wfd_rtp_buffer_mode_get_type())
+GType wfd_rtp_buffer_mode_get_type (void);
+
+#define WFD_RTP_BUFFER_MAX_WINDOW 512
+/**
+ * WfdRTPBuffer:
+ *
+ * A JitterBuffer in the #RTPSession
+ */
+struct _WfdRTPBuffer {
+  GObject        object;
+
+  GQueue        *packets;
+
+  WfdRTPBufferMode mode;
+
+  GstClockTime   delay;
+
+  /* for buffering */
+  gboolean          buffering;
+  guint64           low_level;
+  guint64           high_level;
+
+  /* for calculating skew */
+  GstClockTime   base_time;
+  GstClockTime   base_rtptime;
+  guint32        clock_rate;
+  GstClockTime   base_extrtp;
+  GstClockTime   prev_out_time;
+  guint64        ext_rtptime;
+  guint64        last_rtptime;
+  gint64         window[WFD_RTP_BUFFER_MAX_WINDOW];
+  guint          window_pos;
+  guint          window_size;
+  gboolean       window_filling;
+  gint64         window_min;
+  gint64         skew;
+  gint64         prev_send_diff;
+  gboolean       buffering_disabled;
+};
+
+struct _WfdRTPBufferClass {
+  GObjectClass   parent_class;
+};
+
+/**
+ * WfdRTPBufferItem:
+ * @data: the data of the item
+ * @next: pointer to next item
+ * @prev: pointer to previous item
+ * @type: the type of @data, used freely by caller
+ * @dts: input DTS
+ * @pts: output PTS
+ * @seqnum: seqnum, the seqnum is used to insert the item in the
+ *   right position in the jitterbuffer and detect duplicates. Use -1 to
+ *   append.
+ * @count: amount of seqnum in this item
+ * @rtptime: rtp timestamp
+ *
+ * An object containing an RTP packet or event.
+ */
+struct _WfdRTPBufferItem {
+  gpointer data;
+  GList *next;
+  GList *prev;
+  guint type;
+  GstClockTime dts;
+  GstClockTime pts;
+  guint seqnum;
+  guint count;
+  guint rtptime;
+};
+
+GType wfd_rtp_buffer_get_type (void);
+
+/* managing lifetime */
+WfdRTPBuffer*      wfd_rtp_buffer_new              (void);
+
+WfdRTPBufferMode   wfd_rtp_buffer_get_mode         (WfdRTPBuffer *jbuf);
+void                  wfd_rtp_buffer_set_mode         (WfdRTPBuffer *jbuf, WfdRTPBufferMode mode);
+
+GstClockTime          wfd_rtp_buffer_get_delay        (WfdRTPBuffer *jbuf);
+void                  wfd_rtp_buffer_set_delay        (WfdRTPBuffer *jbuf, GstClockTime delay);
+
+void                  wfd_rtp_buffer_set_clock_rate   (WfdRTPBuffer *jbuf, guint32 clock_rate);
+guint32               wfd_rtp_buffer_get_clock_rate   (WfdRTPBuffer *jbuf);
+
+void                  wfd_rtp_buffer_reset_skew       (WfdRTPBuffer *jbuf);
+
+gboolean              wfd_rtp_buffer_insert           (WfdRTPBuffer *jbuf,
+                                                          WfdRTPBufferItem *item,
+                                                          gboolean *head, gint *percent);
+
+void                  wfd_rtp_buffer_disable_buffering (WfdRTPBuffer *jbuf, gboolean disabled);
+
+WfdRTPBufferItem * wfd_rtp_buffer_peek             (WfdRTPBuffer *jbuf);
+WfdRTPBufferItem * wfd_rtp_buffer_pop              (WfdRTPBuffer *jbuf, gint *percent);
+
+void                  wfd_rtp_buffer_flush            (WfdRTPBuffer *jbuf,
+                                                          GFunc free_func, gpointer user_data);
+
+gboolean              wfd_rtp_buffer_is_buffering     (WfdRTPBuffer * jbuf);
+void                  wfd_rtp_buffer_set_buffering    (WfdRTPBuffer * jbuf, gboolean buffering);
+gint                  wfd_rtp_buffer_get_percent      (WfdRTPBuffer * jbuf);
+
+guint                 wfd_rtp_buffer_num_packets      (WfdRTPBuffer *jbuf);
+guint32               wfd_rtp_buffer_get_ts_diff      (WfdRTPBuffer *jbuf);
+
+void                  wfd_rtp_buffer_get_sync         (WfdRTPBuffer *jbuf, guint64 *rtptime,
+                                                          guint64 *timestamp, guint32 *clock_rate,
+                                                          guint64 *last_rtptime);
+
+#endif /* __WFD_RTP_BUFFER_H__ */
diff --git a/wfdmanager/wfdsrc/gstwfdsrc.c b/wfdmanager/wfdsrc/gstwfdsrc.c
new file mode 100755 (executable)
index 0000000..62c95e9
--- /dev/null
@@ -0,0 +1,864 @@
+/*
+ * wfdsrc
+ *
+ * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.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.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/**
+* SECTION:element-wfdsrc
+*
+* Makes a connection to an RTSP server and read the data.
+* Device recognition is through wifi direct.
+* wfdsrc strictly follows Wifi display specification.
+*
+* RTSP supports transport over TCP or UDP in unicast or multicast mode. By
+* default wfdsrc will negotiate a connection in the following order:
+* UDP unicast/UDP multicast/TCP. The order cannot be changed but the allowed
+* protocols can be controlled with the #GstWFDSrc:protocols property.
+*
+* wfdsrc currently understands WFD capability negotiation messages
+*
+* wfdsrc will internally instantiate an RTP session manager element
+* that will handle the RTCP messages to and from the server, jitter removal,
+* packet reordering along with providing a clock for the pipeline.
+* This feature is implemented using the gstrtpbin element.
+*
+* wfdsrc acts like a live source and will therefore only generate data in the
+* PLAYING state.
+*
+* <refsect2>
+* <title>Example launch line</title>
+* |[
+* gst-launch wfdsrc location=rtsp://some.server/url ! fakesink
+* ]| Establish a connection to an RTSP server and send the raw RTP packets to a
+* fakesink.
+* </refsect2>
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "gstwfdsrc.h"
+
+GST_DEBUG_CATEGORY_STATIC (wfdsrc_debug);
+#define GST_CAT_DEFAULT (wfdsrc_debug)
+
+/* signals and args */
+enum
+{
+  LAST_SIGNAL
+};
+
+enum
+{
+  PROP_0,
+  PROP_DO_RTCP,
+  PROP_LATENCY,
+  PROP_UDP_BUFFER_SIZE,
+  PROP_UDP_TIMEOUT,
+  PROP_LAST
+};
+
+#define DEFAULT_DO_RTCP          TRUE
+#define DEFAULT_LATENCY_MS       2000
+#define DEFAULT_UDP_BUFFER_SIZE  0x80000
+#define DEFAULT_UDP_TIMEOUT          10000000
+
+
+/* object */
+static void gst_wfd_src_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void gst_wfd_src_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+
+/* wfdbasesrc */
+static GstRTSPResult gst_wfd_src_configure_transport (GstWFDBaseSrc *bsrc,
+    GstRTSPTransport * transport);
+static GstRTSPResult gst_wfd_src_prepare_transport (GstWFDBaseSrc *bsrc,
+    gint rtpport, gint rtcpport);
+static gboolean gst_wfd_src_push_event (GstWFDBaseSrc *bsrc, GstEvent * event);
+static void gst_wfd_src_set_state (GstWFDBaseSrc *src, GstState state);
+static void gst_wfd_src_cleanup (GstWFDBaseSrc *bsrc);
+
+
+//static guint gst_wfd_srcext_signals[LAST_SIGNAL] = { 0 };
+
+#define _do_init \
+    GST_DEBUG_CATEGORY_INIT (wfdsrc_debug, "wfdsrc", 0, "Wi-Fi Display Sink source");
+
+#define gst_wfd_src_parent_class parent_class
+G_DEFINE_TYPE_WITH_CODE (GstWFDSrc, gst_wfd_src, GST_TYPE_WFD_BASE_SRC, _do_init);
+
+static void
+gst_wfd_src_class_init (GstWFDSrcClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstElementClass *gstelement_class;
+  GstWFDBaseSrcClass *gstwfdbasesrc_class;
+
+  gobject_class = (GObjectClass *) klass;
+  gstelement_class = (GstElementClass *) klass;
+  gstwfdbasesrc_class = (GstWFDBaseSrcClass *) klass;
+
+  gobject_class->set_property = gst_wfd_src_set_property;
+  gobject_class->get_property = gst_wfd_src_get_property;
+
+  g_object_class_install_property (gobject_class, PROP_DO_RTCP,
+      g_param_spec_boolean ("do-rtcp", "Do RTCP",
+          "Send RTCP packets, disable for old incompatible server.",
+          DEFAULT_DO_RTCP, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_LATENCY,
+      g_param_spec_uint ("latency", "Buffer latency in ms",
+          "Amount of ms to buffer", 0, G_MAXUINT, DEFAULT_LATENCY_MS,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_UDP_BUFFER_SIZE,
+      g_param_spec_int ("udp-buffer-size", "UDP Buffer Size",
+          "Size of the kernel UDP receive buffer in bytes, 0=default",
+          0, G_MAXINT, DEFAULT_UDP_BUFFER_SIZE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_UDP_TIMEOUT,
+      g_param_spec_uint64 ("timeout", "Timeout",
+          "Fail after timeout microseconds on UDP connections (0 = disabled)",
+          0, G_MAXUINT64, DEFAULT_UDP_TIMEOUT,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+
+  gst_element_class_set_static_metadata (gstelement_class, "Wi-Fi Display Sink source element",
+      "Source/Network",
+      "Negotiate the capability and receive the RTP packets from the Wi-Fi Display source",
+      "YeJin Cho <cho.yejin@samsung.com>");
+
+  gstwfdbasesrc_class->configure_transport = GST_DEBUG_FUNCPTR (gst_wfd_src_configure_transport);
+  gstwfdbasesrc_class->prepare_transport = GST_DEBUG_FUNCPTR (gst_wfd_src_prepare_transport);
+  gstwfdbasesrc_class->push_event = GST_DEBUG_FUNCPTR (gst_wfd_src_push_event);
+  gstwfdbasesrc_class->set_state = GST_DEBUG_FUNCPTR (gst_wfd_src_set_state);
+  gstwfdbasesrc_class->cleanup = GST_DEBUG_FUNCPTR (gst_wfd_src_cleanup);
+}
+
+static void
+gst_wfd_src_init (GstWFDSrc* src)
+{
+  gint i;
+
+  src->do_rtcp = DEFAULT_DO_RTCP;
+  src->latency = DEFAULT_LATENCY_MS;
+  src->udp_buffer_size = DEFAULT_UDP_BUFFER_SIZE;
+  src->udp_timeout = DEFAULT_UDP_TIMEOUT;
+
+  src->session = NULL;
+  src->wfdrtpbuffer = NULL;
+  for (i=0; i<2; i++) {
+    src->channelpad[i] = NULL;
+    src->udpsrc[i] = NULL;
+    src->udpsink[i] = NULL;
+  }
+  src->blockid = 0;
+  src->blockedpad = NULL;
+}
+
+static void
+gst_wfd_src_set_property (GObject * object, guint prop_id, const GValue * value,
+    GParamSpec * pspec)
+{
+  GstWFDSrc *src = GST_WFD_SRC (object);
+
+  switch (prop_id) {
+    case PROP_DO_RTCP:
+      src->do_rtcp = g_value_get_boolean (value);
+      break;
+    case PROP_LATENCY:
+      src->latency = g_value_get_uint (value);
+      break;
+    case PROP_UDP_BUFFER_SIZE:
+      src->udp_buffer_size = g_value_get_int (value);
+      break;
+    case PROP_UDP_TIMEOUT:
+      src->udp_timeout = g_value_get_uint64 (value);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_wfd_src_get_property (GObject * object, guint prop_id, GValue * value,
+    GParamSpec * pspec)
+{
+  GstWFDSrc *src = GST_WFD_SRC (object);
+
+  switch (prop_id) {
+    case PROP_DO_RTCP:
+      g_value_set_boolean (value, src->do_rtcp);
+      break;
+    case PROP_LATENCY:
+      g_value_set_uint (value, src->latency);
+      break;
+    case PROP_UDP_BUFFER_SIZE:
+      g_value_set_int (value, src->udp_buffer_size);
+      break;
+    case PROP_UDP_TIMEOUT:
+      g_value_set_uint64 (value, src->udp_timeout);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+}
+
+static void
+gst_wfd_src_set_state (GstWFDBaseSrc *bsrc, GstState state)
+{
+  GstWFDSrc *src = GST_WFD_SRC (bsrc);
+  gint i;
+
+  GST_DEBUG_OBJECT(src, "try to set %s state", gst_element_state_get_name(state));
+
+  for (i=0; i <2; i++) {
+    if (src->udpsrc[i])
+      gst_element_set_state (src->udpsrc[i], state);
+    if (src->udpsink[i])
+      gst_element_set_state (src->udpsink[i], state);
+  }
+
+  if (src->session)
+    gst_element_set_state (src->session, state);
+
+  if (src->wfdrtpbuffer)
+    gst_element_set_state (src->wfdrtpbuffer, state);
+}
+
+static void
+gst_wfd_src_cleanup (GstWFDBaseSrc *bsrc)
+{
+  GstWFDSrc *src = GST_WFD_SRC (bsrc);
+  gint i;
+
+  GST_DEBUG_OBJECT (src, "cleanup");
+
+  for (i=0; i <2; i++) {
+    if (src->channelpad[i]) {
+      gst_object_unref (src->channelpad[i]);
+      src->channelpad[i] = NULL;
+    }
+    if (src->udpsrc[i]) {
+      gst_element_set_state (src->udpsrc[i], GST_STATE_NULL);
+      gst_bin_remove (GST_BIN_CAST (src), src->udpsrc[i]);
+      gst_object_unref (src->udpsrc[i]);
+      src->udpsrc[i] = NULL;
+    }
+    if (src->udpsink[i]) {
+      gst_element_set_state (src->udpsink[i], GST_STATE_NULL);
+      gst_bin_remove (GST_BIN_CAST (src), src->udpsink[i]);
+      gst_object_unref (src->udpsink[i]);
+      src->udpsink[i] = NULL;
+    }
+  }
+  if (src->session) {
+    gst_element_set_state (src->session, GST_STATE_NULL);
+    gst_bin_remove (GST_BIN_CAST (src), src->session);
+    gst_object_unref (src->session);
+    src->session = NULL;
+  }
+  if (src->wfdrtpbuffer) {
+    gst_element_set_state (src->wfdrtpbuffer, GST_STATE_NULL);
+    gst_bin_remove (GST_BIN_CAST (src), src->wfdrtpbuffer);
+    gst_object_unref (src->wfdrtpbuffer);
+    src->wfdrtpbuffer = NULL;
+  }
+}
+
+
+static GstRTSPResult
+gst_wfd_src_prepare_transport (GstWFDBaseSrc *bsrc,
+    gint rtpport, gint rtcpport)
+{
+  GstWFDSrc *src = GST_WFD_SRC (bsrc);
+  GstStateChangeReturn ret;
+  GstElement *udpsrc0, *udpsrc1;
+  gint tmp_rtp, tmp_rtcp;
+  const gchar *host;
+
+  udpsrc0 = NULL;
+  udpsrc1 = NULL;
+
+  if (bsrc->is_ipv6)
+    host = "udp://[::0]";
+  else
+    host = "udp://0.0.0.0";
+
+  /* try to allocate 2 UDP ports */
+  udpsrc0 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
+  if (udpsrc0 == NULL)
+    goto no_udp_protocol;
+  g_object_set (G_OBJECT (udpsrc0), "port", rtpport, "reuse", FALSE, NULL);
+
+  if (src->udp_buffer_size != 0)
+    g_object_set (G_OBJECT (udpsrc0), "buffer-size", src->udp_buffer_size,
+        NULL);
+
+  GST_DEBUG_OBJECT (src, "starting RTP on port %d", rtpport);
+  ret = gst_element_set_state (udpsrc0, GST_STATE_READY);
+  if (ret == GST_STATE_CHANGE_FAILURE) {
+    GST_ERROR_OBJECT (src, "Unable to make udpsrc from RTP port %d", rtpport);
+    goto no_ports;
+  }
+
+  g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
+  GST_DEBUG_OBJECT (src, "got RTP port %d", tmp_rtp);
+
+  /* check if port is even */
+  if ((tmp_rtp & 0x01) != 0) {
+    GST_DEBUG_OBJECT (src, "RTP port not even");
+    /* port not even, free RTP udpsrc */
+    goto no_ports;
+  }
+
+  /* allocate port+1 for RTCP now */
+  udpsrc1 = gst_element_make_from_uri (GST_URI_SRC, host, NULL, NULL);
+  if (udpsrc1 == NULL)
+    goto no_udp_protocol;
+
+  /* set port */
+  g_object_set (G_OBJECT (udpsrc1), "port", rtcpport, "reuse", FALSE, NULL);
+
+  GST_DEBUG_OBJECT (src, "starting RTCP on port %d", rtcpport);
+  ret = gst_element_set_state (udpsrc1, GST_STATE_READY);
+  if (ret == GST_STATE_CHANGE_FAILURE) {
+    GST_ERROR_OBJECT (src, "Unable to make udpsrc from RTCP port %d", rtcpport);
+    goto no_ports;
+  }
+
+  /* all fine, do port check */
+  g_object_get (G_OBJECT (udpsrc0), "port", &tmp_rtp, NULL);
+  g_object_get (G_OBJECT (udpsrc1), "port", &tmp_rtcp, NULL);
+
+  /* this should not happen... */
+  if (rtpport != tmp_rtp || rtcpport != tmp_rtcp)
+    goto port_error;
+
+  /* we keep these elements, we configure all in configure_transport when the
+   * server told us to really use the UDP ports. */
+  src->udpsrc[0] = gst_object_ref_sink (udpsrc0);
+  src->udpsrc[1] = gst_object_ref_sink (udpsrc1);
+  gst_element_set_locked_state (src->udpsrc[0], TRUE);
+  gst_element_set_locked_state (src->udpsrc[1], TRUE);
+
+  return GST_RTSP_OK;
+
+  /* ERRORS */
+no_udp_protocol:
+  {
+    GST_DEBUG_OBJECT (src, "could not get UDP source");
+    goto cleanup;
+  }
+no_ports:
+  {
+    GST_DEBUG_OBJECT (src, "could not allocate UDP port pair");
+    goto cleanup;
+  }
+port_error:
+  {
+    GST_DEBUG_OBJECT (src, "ports don't match rtp: %d<->%d, rtcp: %d<->%d",
+        tmp_rtp, rtpport, tmp_rtcp, rtcpport);
+    goto cleanup;
+  }
+cleanup:
+  {
+    if (udpsrc0) {
+      gst_element_set_state (udpsrc0, GST_STATE_NULL);
+      gst_object_unref (udpsrc0);
+    }
+    if (udpsrc1) {
+      gst_element_set_state (udpsrc1, GST_STATE_NULL);
+      gst_object_unref (udpsrc1);
+    }
+    return GST_RTSP_ERROR;
+  }
+}
+
+static void
+on_bye_ssrc (GObject * session, GObject * source, GstWFDSrc *src)
+{
+  GST_DEBUG_OBJECT (src, "source in session received BYE");
+
+  //gst_wfdsrc_do_stream_eos (src, manager);
+}
+
+static void
+on_new_ssrc (GObject * session, GObject * source, GstWFDSrc *src)
+{
+  GST_DEBUG_OBJECT (src, "source in session received NEW");
+}
+
+static void
+on_timeout (GObject * session, GObject * source, GstWFDSrc *src)
+{
+  GST_DEBUG_OBJECT (src, "source in session timed out");
+
+  //gst_wfdsrc_do_stream_eos (src, manager);
+}
+
+static void
+on_ssrc_active (GObject * session, GObject * source, GstWFDSrc *src)
+{
+  GST_DEBUG_OBJECT (src, "source in session  is active");
+}
+
+
+static GstCaps *
+request_pt_map_for_wfdrtpbuffer (GstElement * wfdrtpbuffer, guint pt, GstWFDSrc *src)
+{
+  GstCaps *caps;
+
+  GST_DEBUG_OBJECT (src, "getting pt map for pt %d", pt);
+
+  GST_WFD_BASE_STATE_LOCK (src);
+  caps = GST_WFD_BASE_SRC_CAST(src)->caps;
+  if (caps)
+    gst_caps_ref (caps);
+  GST_WFD_BASE_STATE_UNLOCK (src);
+
+  return caps;
+}
+
+static GstCaps *
+request_pt_map_for_session (GstElement * session, guint session_id, guint pt, GstWFDSrc *src)
+{
+  GstCaps *caps;
+
+  GST_DEBUG_OBJECT (src, "getting pt map for pt %d in session %d", pt, session_id);
+
+  GST_WFD_BASE_STATE_LOCK (src);
+  caps = GST_WFD_BASE_SRC_CAST(src)->caps;
+  if (caps)
+    gst_caps_ref (caps);
+  GST_WFD_BASE_STATE_UNLOCK (src);
+
+  return caps;
+}
+
+static gboolean
+gst_wfd_src_configure_manager (GstWFDSrc *src)
+{
+  GstPad *pad = NULL;
+
+  /* construct wfdsrc */
+  src->session = gst_element_factory_make ("rtpsession", "wfdsrc_session");
+  if (G_UNLIKELY (src->session == NULL)) {
+    GST_ERROR_OBJECT (src, "could not create gstrtpsession element");
+    return FALSE;
+  }  else {
+    g_signal_connect (src->session, "on-bye-ssrc", (GCallback) on_bye_ssrc,
+        src);
+    g_signal_connect (src->session, "on-bye-timeout", (GCallback) on_timeout,
+        src);
+    g_signal_connect (src->session, "on-timeout", (GCallback) on_timeout,
+        src);
+    g_signal_connect (src->session, "on-ssrc-active",
+        (GCallback) on_ssrc_active, src);
+    g_signal_connect (src->session, "on-new-ssrc", (GCallback) on_new_ssrc,
+        src);
+    g_signal_connect (src->session, "request-pt-map",
+        (GCallback) request_pt_map_for_session, src);
+
+    g_object_set (G_OBJECT(src->session), "rtcp-min-interval", (guint64)1000000000, NULL);
+
+    src->channelpad[0] = gst_element_get_request_pad (src->session, "recv_rtp_sink");
+    if (G_UNLIKELY (src->channelpad[0]  == NULL)) {
+      GST_ERROR_OBJECT (src, "could not create rtp channel pad");
+      return FALSE;
+    }
+
+    src->channelpad[1] = gst_element_get_request_pad (src->session, "recv_rtcp_sink");
+    if (G_UNLIKELY (src->channelpad[1]  == NULL)) {
+      GST_ERROR_OBJECT (src, "could not create rtcp channel pad");
+      return FALSE;
+    }
+
+    /* we manage session element */
+    gst_element_set_locked_state (src->session, TRUE);
+
+    if (!gst_bin_add(GST_BIN_CAST(src), src->session)) {
+      GST_ERROR_OBJECT (src, "failed to add rtpsession to wfdsrc");
+      return FALSE;
+    }
+  }
+
+  src->wfdrtpbuffer = gst_element_factory_make ("wfdrtpbuffer", "wfdsrc_wfdrtpbuffer");
+  if (G_UNLIKELY (src->wfdrtpbuffer == NULL)) {
+    GST_ERROR_OBJECT (src, "could not create wfdrtpbuffer element");
+    return FALSE;
+  } else {
+    /* configure latency and packet lost */
+    g_object_set (src->wfdrtpbuffer, "latency", src->latency, NULL);
+
+    g_signal_connect (src->wfdrtpbuffer, "request-pt-map",
+        (GCallback) request_pt_map_for_wfdrtpbuffer, src);
+
+    /* we manage wfdrtpbuffer element */
+    gst_element_set_locked_state (src->wfdrtpbuffer, TRUE);
+
+    if (!gst_bin_add(GST_BIN_CAST(src), src->wfdrtpbuffer)) {
+      GST_ERROR_OBJECT (src, "failed to add wfdrtpbuffer to wfdsrc");
+      return FALSE;
+    }
+  }
+
+  if (!gst_element_link_many(src->session, src->wfdrtpbuffer, NULL)) {
+    GST_ERROR_OBJECT (src, "failed to link elements for wfdsrc");
+    return FALSE;
+  }
+
+  if (!gst_element_sync_state_with_parent(src->session)) {
+    GST_ERROR_OBJECT (src, "failed for %s to sync state with wfdsrc", GST_ELEMENT_NAME(src->session));
+    return FALSE;
+  }
+
+  if (!gst_element_sync_state_with_parent(src->wfdrtpbuffer)) {
+    GST_ERROR_OBJECT (src, "failed for %s to sync state with wfdsrc", GST_ELEMENT_NAME(src->wfdrtpbuffer));
+    return FALSE;
+  }
+
+  /* set ghost pad */
+  pad = gst_element_get_static_pad (src->wfdrtpbuffer, "src");
+  if (G_UNLIKELY (pad == NULL)) {
+    GST_ERROR_OBJECT (src, "failed to get src pad of wfdrtpbuffer for setting ghost pad of wfdsrc");
+    return FALSE;
+  }
+
+  if (!gst_wfd_base_src_set_target(GST_WFD_BASE_SRC(src), pad)) {
+    GST_ERROR_OBJECT (src, "failed to set target pad of ghost pad");
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+static gboolean
+gst_wfd_src_configure_udp_sinks (GstWFDSrc *src, GstRTSPTransport * transport)
+{
+  GstPad *pad = NULL;
+  GSocket *socket = NULL;
+  gint rtp_port = -1, rtcp_port = -1;
+  gboolean do_rtcp;
+  const gchar *destination =  NULL;
+  gchar *uri = NULL;
+
+  /* get transport info */
+  gst_wfd_base_src_get_transport_info (GST_WFD_BASE_SRC(src), transport, &destination,
+      &rtp_port, &rtcp_port);
+
+  /* it's possible that the server does not want us to send RTCP in which case
+   * the port is -1 */
+  do_rtcp = (rtcp_port != -1 && src->session != NULL && src->do_rtcp);
+
+  /* we need a destination when we have RTCP RR */
+  if (destination == NULL && do_rtcp)
+    goto no_destination;
+
+  if (do_rtcp) {
+    GstPad *rtcppad = NULL;
+
+    GST_DEBUG_OBJECT (src, "configure RTCP UDP sink for %s:%d", destination,
+        rtcp_port);
+
+    uri = g_strdup_printf ("udp://%s:%d", destination, rtcp_port);
+    src->udpsink[1] = gst_element_make_from_uri (GST_URI_SINK, uri, NULL, NULL);
+    g_free (uri);
+    if (src->udpsink[1] == NULL)
+      goto no_sink_element;
+
+    /* don't join multicast group, we will have the source socket do that */
+    /* no sync or async state changes needed */
+    g_object_set (G_OBJECT (src->udpsink[1]), "auto-multicast", FALSE,
+        "loop", FALSE, "sync", FALSE, "async", FALSE, NULL);
+
+    if (src->udpsrc[1]) {
+      /* configure socket, we give it the same UDP socket as the udpsrc for RTCP
+       * because some servers check the port number of where it sends RTCP to identify
+       * the RTCP packets it receives */
+      g_object_get (G_OBJECT (src->udpsrc[1]), "used-socket", &socket, NULL);
+      GST_DEBUG_OBJECT (src, "RTCP UDP src has sock %p", socket);
+      /* configure socket and make sure udpsink does not close it when shutting
+       * down, it belongs to udpsrc after all. */
+      g_object_set (G_OBJECT (src->udpsink[1]), "socket", socket,
+          "close-socket", FALSE, NULL);
+      g_object_unref (socket);
+    }
+
+    /* we don't want to consider this a sink */
+    GST_OBJECT_FLAG_UNSET (src->udpsink[1], GST_ELEMENT_FLAG_SINK);
+
+    /* we keep this playing always */
+    gst_element_set_locked_state (src->udpsink[1], TRUE);
+    gst_element_set_state (src->udpsink[1], GST_STATE_PLAYING);
+
+    gst_object_ref (src->udpsink[1]);
+    gst_bin_add (GST_BIN_CAST (src), src->udpsink[1]);
+
+    rtcppad = gst_element_get_static_pad (src->udpsink[1], "sink");
+
+    /* get session RTCP pad */
+    pad = gst_element_get_request_pad (src->session, "send_rtcp_src");
+
+    /* and link */
+    if (pad && rtcppad) {
+      gst_pad_link_full (pad, rtcppad, GST_PAD_LINK_CHECK_NOTHING);
+      gst_object_unref (pad);
+      gst_object_unref (rtcppad);
+    }
+  }
+
+  return TRUE;
+
+  /* ERRORS */
+no_destination:
+  {
+    GST_DEBUG_OBJECT (src, "no destination address specified");
+    return FALSE;
+  }
+no_sink_element:
+  {
+    GST_DEBUG_OBJECT (src, "no UDP sink element found");
+    return FALSE;
+  }
+}
+
+static void
+pad_blocked (GstPad * pad, gboolean blocked, GstWFDSrc *src)
+{
+  GST_DEBUG_OBJECT (src, "pad %s:%s blocked, activating streams",
+      GST_DEBUG_PAD_NAME (pad));
+
+  if (src->udpsrc[0]) {
+    /* remove timeout, we are streaming now and timeouts will be handled by
+     * the session manager and jitter buffer */
+    g_object_set (G_OBJECT (src->udpsrc[0]), "timeout", (guint64) 0, NULL);
+  }
+
+  /* activate the streams */
+  gst_wfd_base_src_activate (GST_WFD_BASE_SRC(src));
+
+  /* unblock all pads */
+  if (src->blockedpad && src->blockid != 0) {
+    GST_DEBUG_OBJECT (src, "unblocking blocked pad");
+    gst_pad_remove_probe (src->blockedpad, src->blockid);
+    src->blockid = 0;
+    src->blockedpad = NULL;
+  }
+}
+
+static gboolean
+gst_wfd_src_configure_udp (GstWFDSrc *src)
+{
+  GstPad *outpad;
+
+  /* we manage the UDP elements now. For unicast, the UDP sources where
+   * allocated in the stream when we suggested a transport. */
+  if (src->udpsrc[0]) {
+    GstCaps *caps;
+
+    gst_element_set_locked_state (src->udpsrc[0], TRUE);
+    gst_bin_add (GST_BIN_CAST (src), src->udpsrc[0]);
+
+    GST_DEBUG_OBJECT (src, "setting up UDP source");
+
+    /* configure a timeout on the UDP port. When the timeout message is
+     * posted */
+    g_object_set (G_OBJECT (src->udpsrc[0]), "timeout",
+        src->udp_timeout * 1000, NULL);
+
+    caps = gst_caps_new_simple ("application/x-rtp",
+                    "media", G_TYPE_STRING, "video", "payload", G_TYPE_INT, 33,
+                    "clock-rate", G_TYPE_INT, 90000, NULL);
+    g_object_set (src->udpsrc[0], "caps", caps, NULL);
+    gst_caps_unref (caps);
+
+    /* get output pad of the UDP source. */
+    outpad = gst_element_get_static_pad (src->udpsrc[0], "src");
+
+    /* save it so we can unblock */
+    src->blockedpad = outpad;
+
+    /* configure pad block on the pad. As soon as there is dataflow on the
+     * UDP source, we know that UDP is not blocked by a firewall and we can
+     * configure all the streams to let the application autoplug decoders. */
+    src->blockid =
+        gst_pad_add_probe (src->blockedpad,
+        GST_PAD_PROBE_TYPE_BLOCK | GST_PAD_PROBE_TYPE_BUFFER |
+        GST_PAD_PROBE_TYPE_BUFFER_LIST, (GstPadProbeCallback)pad_blocked, src, NULL);
+
+    if (src->channelpad[0]) {
+      GST_DEBUG_OBJECT (src, "connecting UDP source 0 to session");
+      /* configure for UDP delivery, we need to connect the UDP pads to
+       * the session plugin. */
+      gst_pad_link_full (outpad, src->channelpad[0],
+          GST_PAD_LINK_CHECK_NOTHING);
+      /* we connected to pad-added signal to get pads from the manager */
+    } else {
+      /* leave unlinked */
+    }
+  }
+
+  /* RTCP port */
+  if (src->udpsrc[1]) {
+    GstCaps *caps;
+
+    gst_element_set_locked_state (src->udpsrc[1], TRUE);
+    gst_bin_add (GST_BIN_CAST (src), src->udpsrc[1]);
+
+    caps = gst_caps_new_empty_simple ("application/x-rtcp");
+    g_object_set (src->udpsrc[1], "caps", caps, NULL);
+    gst_caps_unref (caps);
+
+    if (src->channelpad[1]) {
+      GstPad *pad;
+
+      GST_DEBUG_OBJECT (src, "connecting UDP source 1 to session");
+
+      pad = gst_element_get_static_pad (src->udpsrc[1], "src");
+      gst_pad_link_full (pad, src->channelpad[1],
+          GST_PAD_LINK_CHECK_NOTHING);
+      gst_object_unref (pad);
+    } else {
+      /* leave unlinked */
+    }
+  }
+
+  return TRUE;
+}
+
+static GstRTSPResult
+gst_wfd_src_configure_transport (GstWFDBaseSrc *bsrc,
+    GstRTSPTransport * transport)
+{
+  GstWFDSrc *src = GST_WFD_SRC (bsrc);
+  const gchar * mime;
+
+  g_return_val_if_fail(transport,  GST_RTSP_EINVAL);
+
+  GST_DEBUG_OBJECT (src, "configuring transport");
+
+  /* get the proper mime type for this manager now */
+  if (gst_rtsp_transport_get_mime (transport->trans, &mime) < 0)
+    goto unknown_transport;
+  if (!mime)
+    goto unknown_transport;
+
+  /* configure the final mime type */
+  GST_DEBUG_OBJECT (src, "setting mime to %s", mime);
+
+  if (!gst_wfd_src_configure_manager (src))
+    goto no_manager;
+
+  switch (transport->lower_transport) {
+    case GST_RTSP_LOWER_TRANS_TCP:
+    case GST_RTSP_LOWER_TRANS_UDP_MCAST:
+     goto transport_failed;
+    case GST_RTSP_LOWER_TRANS_UDP:
+      if (!gst_wfd_src_configure_udp (src))
+        goto transport_failed;
+      if (!gst_wfd_src_configure_udp_sinks (src, transport))
+        goto transport_failed;
+      break;
+    default:
+      goto unknown_transport;
+  }
+
+  return GST_RTSP_OK;
+
+  /* ERRORS */
+unknown_transport:
+  {
+    GST_DEBUG_OBJECT (src, "unknown transport");
+    return GST_RTSP_ERROR;
+  }
+no_manager:
+  {
+    GST_DEBUG_OBJECT (src, "cannot configure manager");
+    return GST_RTSP_ERROR;
+  }
+transport_failed:
+  {
+    GST_DEBUG_OBJECT (src, "failed to configure transport");
+    return GST_RTSP_ERROR;
+  }
+}
+
+static gboolean
+gst_wfd_src_push_event (GstWFDBaseSrc *bsrc, GstEvent * event)
+{
+  GstWFDSrc *src = GST_WFD_SRC (bsrc);
+  gboolean res = TRUE;
+
+  if (src->udpsrc[0]) {
+    gst_event_ref (event);
+    res = gst_element_send_event (src->udpsrc[0], event);
+  } else if (src->channelpad[0]) {
+    gst_event_ref (event);
+    if (GST_PAD_IS_SRC (src->channelpad[0]))
+      res = gst_pad_push_event (src->channelpad[0], event);
+    else
+      res = gst_pad_send_event (src->channelpad[0], event);
+  }
+
+  if (src->udpsrc[1]) {
+    gst_event_ref (event);
+    res &= gst_element_send_event (src->udpsrc[1], event);
+  } else if (src->channelpad[1]) {
+    gst_event_ref (event);
+    if (GST_PAD_IS_SRC (src->channelpad[1]))
+      res &= gst_pad_push_event (src->channelpad[1], event);
+    else
+      res &= gst_pad_send_event (src->channelpad[1], event);
+  }
+
+  gst_event_unref (event);
+
+  return res;
+}
diff --git a/wfdmanager/wfdsrc/gstwfdsrc.h b/wfdmanager/wfdsrc/gstwfdsrc.h
new file mode 100755 (executable)
index 0000000..6d7d278
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * wfdrtspsrc
+ *
+ * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: JongHyuk Choi <jhchoi.choi@samsung.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.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+
+
+#ifndef __GST_WFD_SRC_H__
+#define __GST_WFD_SRC_H__
+
+#include <gst/gst.h>
+#include "../wfdbase/gstwfdbasesrc.h"
+
+G_BEGIN_DECLS
+#define GST_TYPE_WFD_SRC (gst_wfd_src_get_type())
+#define GST_WFD_SRC(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_WFD_SRC,GstWFDSrc))
+#define GST_WFD_SRC_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_WFD_SRC,GstWFDSrcClass))
+#define GST_WFD_SRC_GET_CLASS(obj)     (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_WFD_SRC, GstWFDSrcClass))
+#define GST_IS_WFD_SRC(obj)  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_SRC))
+#define GST_IS_WFD_SRC_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_SRC))
+#define GST_WFD_SRC_CAST(obj)   ((GstWFDSrc *)(obj))
+
+typedef struct _GstWFDSrc GstWFDSrc;
+typedef struct _GstWFDSrcClass GstWFDSrcClass;
+//typedef struct _GstWFDSrcPrivate GstWFDSrcPrivate;
+
+#define RETRANSMITTED_RTP_PORT 19120
+#define RTCP_FB_PORT 19121
+
+
+struct _GstWFDSrc {
+  GstWFDBaseSrc parent;
+
+  /* properties */
+  gboolean          do_rtcp;
+  guint             latency;
+  gint              udp_buffer_size;
+  guint64           udp_timeout;
+
+  GstPad       *channelpad[3];
+  GstElement   *udpsrc[2];
+  GstElement   *udpsink[2];
+  GstElement      *session;
+  GstElement      *wfdrtpbuffer;
+
+  GstPad       *blockedpad;
+  gulong        blockid;
+};
+
+struct _GstWFDSrcClass {
+  GstWFDBaseSrcClass parent_class;
+};
+
+GType gst_wfd_src_get_type(void);
+
+G_END_DECLS
+
+#endif /* __GST_WFD_SRC_H__ */
+
diff --git a/wfdtsdemux/Makefile.am b/wfdtsdemux/Makefile.am
new file mode 100755 (executable)
index 0000000..3619c05
--- /dev/null
@@ -0,0 +1,42 @@
+plugin_LTLIBRARIES = libgstwfdtsdemux.la
+
+libgstwfdtsdemux_la_SOURCES = \
+       gstwfdh264parser.c \
+       wfdnalutils.c \
+       gstwfdtssection.c \
+       gstwfdtsdescriptor.c \
+       wfdtspacketizer.c \
+       wfdtsbase.c     \
+       wfdtsparse.c \
+       wfdtsdemux.c    \
+       gstwfdtsdemux.c \
+       wfdpesparse.c
+
+libgstwfdtsdemux_la_CFLAGS = \
+       $(GST_PLUGINS_BASE_CFLAGS) \
+       $(GST_BASE_CFLAGS) $(GST_CFLAGS) \
+       -DWFD_SPEC
+libgstwfdtsdemux_la_LIBADD = \
+       $(GST_PLUGINS_BASE_LIBS) \
+       -lgsttag-@GST_MAJORMINOR@ \
+       -lgstpbutils-@GST_MAJORMINOR@ \
+       $(GST_BASE_LIBS) \
+       $(GST_LIBS)
+libgstwfdtsdemux_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+libgstwfdtsdemux_la_LIBTOOLFLAGS = $(GST_PLUGIN_LIBTOOLFLAGS)
+
+noinst_HEADERS = \
+       gstwfdh264parser.h \
+       gstwfdts-private.h \
+       wfdnalutils.h \
+       gstwfdtssection.h \
+       gstwfdtsdescriptor.h \
+       gstwfdtsdefs.h   \
+       gstwfdtsdesc.h   \
+       wfdtsbase.h     \
+       wfdtspacketizer.h \
+       wfdtsparse.h \
+       wfdtsdemux.h    \
+       wfdpesparse.h
+
+
diff --git a/wfdtsdemux/gstwfdh264parser.c b/wfdtsdemux/gstwfdh264parser.c
new file mode 100755 (executable)
index 0000000..453b438
--- /dev/null
@@ -0,0 +1,2038 @@
+/* Gstreamer
+ * Copyright (C) <2011> Intel Corporation
+ * Copyright (C) <2011> Collabora Ltd.
+ * Copyright (C) <2011> Thibault Saunier <thibault.saunier@collabora.com>
+ *
+ * Some bits C-c,C-v'ed and s/4/3 from h264parse and videoparsers/h264parse.c:
+ *    Copyright (C) <2010> Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>
+ *    Copyright (C) <2010> Collabora Multimedia
+ *    Copyright (C) <2010> Nokia Corporation
+ *
+ *    (C) 2005 Michal Benes <michal.benes@itonis.tv>
+ *    (C) 2008 Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+/**
+ * SECTION:gstwfdh264parser
+ * @short_description: Convenience library for h264 video
+ * bitstream parsing.
+ *
+ * It offers you bitstream parsing in AVC mode or not. To identify Nals in a bitstream and
+ * parse its headers, you should call:
+ * <itemizedlist>
+ *   <listitem>
+ *      #gst_wfd_h264_parser_identify_nalu to identify the following nalu in not AVC bitstreams
+ *   </listitem>
+ *   <listitem>
+ *      #gst_wfd_h264_parser_identify_nalu_avc to identify the nalu in AVC bitstreams
+ *   </listitem>
+ * </itemizedlist>
+ *
+ * Then, depending on the #GstWFDH264NalUnitType of the newly parsed #GstWFDH264NalUnit, you should
+ * call the differents functions to parse the structure:
+ * <itemizedlist>
+ *   <listitem>
+ *      From #GST_H264_NAL_SLICE to #GST_H264_NAL_SLICE_IDR: #gst_wfd_h264_parser_parse_slice_hdr
+ *   </listitem>
+ *   <listitem>
+ *      #GST_H264_NAL_SEI: #gst_wfd_h264_parser_parse_sei
+ *   </listitem>
+ *   <listitem>
+ *      #GST_H264_NAL_SPS: #gst_wfd_h264_parser_parse_sps
+ *   </listitem>
+ *   <listitem>
+ *      #GST_H264_NAL_PPS: #gst_wfd_h264_parser_parse_pps
+ *   </listitem>
+ *   <listitem>
+ *      Any other: #gst_wfd_h264_parser_parse_nal
+ *   </listitem>
+ * </itemizedlist>
+ *
+ * Note: You should always call gst_wfd_h264_parser_parse_nal if you don't actually need
+ * #GstWFDH264NalUnitType to be parsed for your personnal use, in order to guarantee that the
+ * #GstWFDH264NalParser is always up to date.
+ *
+ * For more details about the structures, look at the ITU-T H.264 and ISO/IEC 14496-10 â€“ MPEG-4
+ * Part 10 specifications, you can download them from:
+ *
+ * <itemizedlist>
+ *   <listitem>
+ *     ITU-T H.264: http://www.itu.int/rec/T-REC-H.264
+ *   </listitem>
+ *   <listitem>
+ *     ISO/IEC 14496-10: http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=56538
+ *   </listitem>
+ * </itemizedlist>
+ */
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#include "wfdnalutils.h"
+#include "gstwfdh264parser.h"
+
+#include <gst/base/gstbytereader.h>
+#include <gst/base/gstbitreader.h>
+#include <string.h>
+
+GST_DEBUG_CATEGORY (wfd_h264_parser_debug);
+#define GST_CAT_DEFAULT wfd_h264_parser_debug
+
+static gboolean initialized = FALSE;
+#define INITIALIZE_DEBUG_CATEGORY \
+  if (!initialized) { \
+    GST_DEBUG_CATEGORY_INIT (wfd_h264_parser_debug, "codecparsers_h264", 0, \
+        "h264 parser library"); \
+    initialized = TRUE; \
+  }
+
+/**** Default scaling_lists according to Table 7-2 *****/
+static const guint8 default_4x4_intra[16] = {
+  6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32,
+  32, 37, 37, 42
+};
+
+static const guint8 default_4x4_inter[16] = {
+  10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27,
+  27, 30, 30, 34
+};
+
+static const guint8 default_8x8_intra[64] = {
+  6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18,
+  18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27,
+  27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 33,
+  33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42
+};
+
+static const guint8 default_8x8_inter[64] = {
+  9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19,
+  19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 24, 24, 24,
+  24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 28,
+  28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35
+};
+
+static const guint8 zigzag_8x8[64] = {
+  0, 1, 8, 16, 9, 2, 3, 10,
+  17, 24, 32, 25, 18, 11, 4, 5,
+  12, 19, 26, 33, 40, 48, 41, 34,
+  27, 20, 13, 6, 7, 14, 21, 28,
+  35, 42, 49, 56, 57, 50, 43, 36,
+  29, 22, 15, 23, 30, 37, 44, 51,
+  58, 59, 52, 45, 38, 31, 39, 46,
+  53, 60, 61, 54, 47, 55, 62, 63
+};
+
+static const guint8 zigzag_4x4[16] = {
+  0, 1, 4, 8,
+  5, 2, 3, 6,
+  9, 12, 13, 10,
+  7, 11, 14, 15,
+};
+
+typedef struct
+{
+  guint par_n, par_d;
+} PAR;
+
+/* Table E-1 - Meaning of sample aspect ratio indicator (1..16) */
+static PAR aspect_ratios[17] = {
+  {0, 0},
+  {1, 1},
+  {12, 11},
+  {10, 11},
+  {16, 11},
+  {40, 33},
+  {24, 11},
+  {20, 11},
+  {32, 11},
+  {80, 33},
+  {18, 11},
+  {15, 11},
+  {64, 33},
+  {160, 99},
+  {4, 3},
+  {3, 2},
+  {2, 1}
+};
+
+/*****  Utils ****/
+#define EXTENDED_SAR 255
+
+static GstWFDH264SPS *
+gst_wfd_h264_parser_get_sps (GstWFDH264NalParser * nalparser, guint8 sps_id)
+{
+  GstWFDH264SPS *sps;
+
+  sps = &nalparser->sps[sps_id];
+
+  if (sps->valid)
+    return sps;
+
+  return NULL;
+}
+
+static GstWFDH264PPS *
+gst_wfd_h264_parser_get_pps (GstWFDH264NalParser * nalparser, guint8 pps_id)
+{
+  GstWFDH264PPS *pps;
+
+  pps = &nalparser->pps[pps_id];
+
+  if (pps->valid)
+    return pps;
+
+  return NULL;
+}
+
+static gboolean
+gst_wfd_h264_parse_nalu_header (GstWFDH264NalUnit * nalu)
+{
+  guint8 *data = nalu->data + nalu->offset;
+
+  if (nalu->size < 1)
+    return FALSE;
+
+  nalu->type = (data[0] & 0x1f);
+  nalu->ref_idc = (data[0] & 0x60) >> 5;
+  nalu->idr_pic_flag = (nalu->type == 5 ? 1 : 0);
+
+  GST_DEBUG ("Nal type %u, ref_idc %u", nalu->type, nalu->ref_idc);
+  return TRUE;
+}
+
+/*
+ * gst_wfd_h264_pps_copy:
+ * @dst_pps: The destination #GstWFDH264PPS to copy into
+ * @src_pps: The source #GstWFDH264PPS to copy from
+ *
+ * Copies @src_pps into @dst_pps.
+ *
+ * Returns: %TRUE if everything went fine, %FALSE otherwise
+ */
+static gboolean
+gst_wfd_h264_pps_copy (GstWFDH264PPS * dst_pps, const GstWFDH264PPS * src_pps)
+{
+  g_return_val_if_fail (dst_pps != NULL, FALSE);
+  g_return_val_if_fail (src_pps != NULL, FALSE);
+
+  gst_wfd_h264_pps_clear (dst_pps);
+
+  *dst_pps = *src_pps;
+
+  if (src_pps->slice_group_id)
+    dst_pps->slice_group_id = g_memdup (src_pps->slice_group_id,
+        src_pps->pic_size_in_map_units_minus1 + 1);
+
+  return TRUE;
+}
+
+/****** Parsing functions *****/
+
+static gboolean
+gst_wfd_h264_parse_hrd_parameters (GstWFDH264HRDParams * hrd, WFDNalReader * nr)
+{
+  guint sched_sel_idx;
+
+  GST_DEBUG ("parsing \"HRD Parameters\"");
+
+  READ_UE_ALLOWED (nr, hrd->cpb_cnt_minus1, 0, 31);
+  READ_UINT8 (nr, hrd->bit_rate_scale, 4);
+  READ_UINT8 (nr, hrd->cpb_size_scale, 4);
+
+  for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1; sched_sel_idx++) {
+    READ_UE (nr, hrd->bit_rate_value_minus1[sched_sel_idx]);
+    READ_UE (nr, hrd->cpb_size_value_minus1[sched_sel_idx]);
+    READ_UINT8 (nr, hrd->cbr_flag[sched_sel_idx], 1);
+  }
+
+  READ_UINT8 (nr, hrd->initial_cpb_removal_delay_length_minus1, 5);
+  READ_UINT8 (nr, hrd->cpb_removal_delay_length_minus1, 5);
+  READ_UINT8 (nr, hrd->dpb_output_delay_length_minus1, 5);
+  READ_UINT8 (nr, hrd->time_offset_length, 5);
+
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing \"HRD Parameters\"");
+  return FALSE;
+}
+
+static gboolean
+gst_wfd_h264_parse_vui_parameters (GstWFDH264SPS * sps, WFDNalReader * nr)
+{
+  GstWFDH264VUIParams *vui = &sps->vui_parameters;
+
+  GST_DEBUG ("parsing \"VUI Parameters\"");
+
+  /* set default values for fields that might not be present in the bitstream
+     and have valid defaults */
+  vui->aspect_ratio_idc = 0;
+  vui->video_format = 5;
+  vui->video_full_range_flag = 0;
+  vui->colour_primaries = 2;
+  vui->transfer_characteristics = 2;
+  vui->matrix_coefficients = 2;
+  vui->chroma_sample_loc_type_top_field = 0;
+  vui->chroma_sample_loc_type_bottom_field = 0;
+  vui->low_delay_hrd_flag = 0;
+  vui->par_n = 0;
+  vui->par_d = 0;
+
+  READ_UINT8 (nr, vui->aspect_ratio_info_present_flag, 1);
+  if (vui->aspect_ratio_info_present_flag) {
+    READ_UINT8 (nr, vui->aspect_ratio_idc, 8);
+    if (vui->aspect_ratio_idc == EXTENDED_SAR) {
+      READ_UINT16 (nr, vui->sar_width, 16);
+      READ_UINT16 (nr, vui->sar_height, 16);
+      vui->par_n = vui->sar_width;
+      vui->par_d = vui->sar_height;
+    } else if (vui->aspect_ratio_idc <= 16) {
+      vui->par_n = aspect_ratios[vui->aspect_ratio_idc].par_n;
+      vui->par_d = aspect_ratios[vui->aspect_ratio_idc].par_d;
+    }
+  }
+
+  READ_UINT8 (nr, vui->overscan_info_present_flag, 1);
+  if (vui->overscan_info_present_flag)
+    READ_UINT8 (nr, vui->overscan_appropriate_flag, 1);
+
+  READ_UINT8 (nr, vui->video_signal_type_present_flag, 1);
+  if (vui->video_signal_type_present_flag) {
+
+    READ_UINT8 (nr, vui->video_format, 3);
+    READ_UINT8 (nr, vui->video_full_range_flag, 1);
+    READ_UINT8 (nr, vui->colour_description_present_flag, 1);
+    if (vui->colour_description_present_flag) {
+      READ_UINT8 (nr, vui->colour_primaries, 8);
+      READ_UINT8 (nr, vui->transfer_characteristics, 8);
+      READ_UINT8 (nr, vui->matrix_coefficients, 8);
+    }
+  }
+
+  READ_UINT8 (nr, vui->chroma_loc_info_present_flag, 1);
+  if (vui->chroma_loc_info_present_flag) {
+    READ_UE_ALLOWED (nr, vui->chroma_sample_loc_type_top_field, 0, 5);
+    READ_UE_ALLOWED (nr, vui->chroma_sample_loc_type_bottom_field, 0, 5);
+  }
+
+  READ_UINT8 (nr, vui->timing_info_present_flag, 1);
+  if (vui->timing_info_present_flag) {
+    READ_UINT32 (nr, vui->num_units_in_tick, 32);
+    if (vui->num_units_in_tick == 0)
+      GST_WARNING ("num_units_in_tick = 0 detected in stream "
+          "(incompliant to H.264 E.2.1).");
+
+    READ_UINT32 (nr, vui->time_scale, 32);
+    if (vui->time_scale == 0)
+      GST_WARNING ("time_scale = 0 detected in stream "
+          "(incompliant to H.264 E.2.1).");
+
+    READ_UINT8 (nr, vui->fixed_frame_rate_flag, 1);
+  }
+
+  READ_UINT8 (nr, vui->nal_hrd_parameters_present_flag, 1);
+  if (vui->nal_hrd_parameters_present_flag) {
+    if (!gst_wfd_h264_parse_hrd_parameters (&vui->nal_hrd_parameters, nr))
+      goto error;
+  }
+
+  READ_UINT8 (nr, vui->vcl_hrd_parameters_present_flag, 1);
+  if (vui->vcl_hrd_parameters_present_flag) {
+    if (!gst_wfd_h264_parse_hrd_parameters (&vui->vcl_hrd_parameters, nr))
+      goto error;
+  }
+
+  if (vui->nal_hrd_parameters_present_flag ||
+      vui->vcl_hrd_parameters_present_flag)
+    READ_UINT8 (nr, vui->low_delay_hrd_flag, 1);
+
+  READ_UINT8 (nr, vui->pic_struct_present_flag, 1);
+  READ_UINT8 (nr, vui->bitstream_restriction_flag, 1);
+  if (vui->bitstream_restriction_flag) {
+    READ_UINT8 (nr, vui->motion_vectors_over_pic_boundaries_flag, 1);
+    READ_UE (nr, vui->max_bytes_per_pic_denom);
+    READ_UE_ALLOWED (nr, vui->max_bits_per_mb_denom, 0, 16);
+    READ_UE_ALLOWED (nr, vui->log2_max_mv_length_horizontal, 0, 16);
+    READ_UE_ALLOWED (nr, vui->log2_max_mv_length_vertical, 0, 16);
+    READ_UE (nr, vui->num_reorder_frames);
+    READ_UE (nr, vui->max_dec_frame_buffering);
+  }
+
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing \"VUI Parameters\"");
+  return FALSE;
+}
+
+static gboolean
+gst_wfd_h264_parser_parse_scaling_list (WFDNalReader * nr,
+    guint8 scaling_lists_4x4[6][16], guint8 scaling_lists_8x8[6][64],
+    const guint8 fallback_4x4_inter[16], const guint8 fallback_4x4_intra[16],
+    const guint8 fallback_8x8_inter[64], const guint8 fallback_8x8_intra[64],
+    guint8 n_lists)
+{
+  guint i;
+
+  static const guint8 *default_lists[12] = {
+    default_4x4_intra, default_4x4_intra, default_4x4_intra,
+    default_4x4_inter, default_4x4_inter, default_4x4_inter,
+    default_8x8_intra, default_8x8_inter,
+    default_8x8_intra, default_8x8_inter,
+    default_8x8_intra, default_8x8_inter
+  };
+
+  GST_DEBUG ("parsing scaling lists");
+
+  for (i = 0; i < 12; i++) {
+    gboolean use_default = FALSE;
+
+    if (i < n_lists) {
+      guint8 scaling_list_present_flag;
+
+      READ_UINT8 (nr, scaling_list_present_flag, 1);
+      if (scaling_list_present_flag) {
+        guint8 *scaling_list;
+        guint size;
+        guint j;
+        guint8 last_scale, next_scale;
+
+        if (i < 6) {
+          scaling_list = scaling_lists_4x4[i];
+          size = 16;
+        } else {
+          scaling_list = scaling_lists_8x8[i - 6];
+          size = 64;
+        }
+
+        last_scale = 8;
+        next_scale = 8;
+        for (j = 0; j < size; j++) {
+          if (next_scale != 0) {
+            gint32 delta_scale;
+
+            READ_SE (nr, delta_scale);
+            next_scale = (last_scale + delta_scale) & 0xff;
+          }
+          if (j == 0 && next_scale == 0) {
+            /* Use default scaling lists (7.4.2.1.1.1) */
+            memcpy (scaling_list, default_lists[i], size);
+            break;
+          }
+          last_scale = scaling_list[j] =
+              (next_scale == 0) ? last_scale : next_scale;
+        }
+      } else
+        use_default = TRUE;
+    } else
+      use_default = TRUE;
+
+    if (use_default) {
+      switch (i) {
+        case 0:
+          memcpy (scaling_lists_4x4[0], fallback_4x4_intra, 16);
+          break;
+        case 1:
+          memcpy (scaling_lists_4x4[1], scaling_lists_4x4[0], 16);
+          break;
+        case 2:
+          memcpy (scaling_lists_4x4[2], scaling_lists_4x4[1], 16);
+          break;
+        case 3:
+          memcpy (scaling_lists_4x4[3], fallback_4x4_inter, 16);
+          break;
+        case 4:
+          memcpy (scaling_lists_4x4[4], scaling_lists_4x4[3], 16);
+          break;
+        case 5:
+          memcpy (scaling_lists_4x4[5], scaling_lists_4x4[4], 16);
+          break;
+        case 6:
+          memcpy (scaling_lists_8x8[0], fallback_8x8_intra, 64);
+          break;
+        case 7:
+          memcpy (scaling_lists_8x8[1], fallback_8x8_inter, 64);
+          break;
+        case 8:
+          memcpy (scaling_lists_8x8[2], scaling_lists_8x8[0], 64);
+          break;
+        case 9:
+          memcpy (scaling_lists_8x8[3], scaling_lists_8x8[1], 64);
+          break;
+        case 10:
+          memcpy (scaling_lists_8x8[4], scaling_lists_8x8[2], 64);
+          break;
+        case 11:
+          memcpy (scaling_lists_8x8[5], scaling_lists_8x8[3], 64);
+          break;
+
+        default:
+          break;
+      }
+    }
+  }
+
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing scaling lists");
+  return FALSE;
+}
+
+static gboolean
+slice_parse_ref_pic_list_modification_1 (GstWFDH264SliceHdr * slice,
+    WFDNalReader * nr, guint list)
+{
+  GstWFDH264RefPicListModification *entries;
+  guint8 *ref_pic_list_modification_flag, *n_ref_pic_list_modification;
+  guint32 modification_of_pic_nums_idc;
+  guint i = 0;
+
+  if (list == 0) {
+    entries = slice->ref_pic_list_modification_l0;
+    ref_pic_list_modification_flag = &slice->ref_pic_list_modification_flag_l0;
+    n_ref_pic_list_modification = &slice->n_ref_pic_list_modification_l0;
+  } else {
+    entries = slice->ref_pic_list_modification_l1;
+    ref_pic_list_modification_flag = &slice->ref_pic_list_modification_flag_l1;
+    n_ref_pic_list_modification = &slice->n_ref_pic_list_modification_l1;
+  }
+
+  READ_UINT8 (nr, *ref_pic_list_modification_flag, 1);
+  if (*ref_pic_list_modification_flag) {
+    while (1) {
+      READ_UE (nr, modification_of_pic_nums_idc);
+      if (modification_of_pic_nums_idc == 3)
+        break;
+      if (modification_of_pic_nums_idc == 0 ||
+          modification_of_pic_nums_idc == 1) {
+        READ_UE_ALLOWED (nr, entries[i].value.abs_diff_pic_num_minus1, 0,
+            slice->max_pic_num - 1);
+      } else if (modification_of_pic_nums_idc == 2) {
+        READ_UE (nr, entries[i].value.long_term_pic_num);
+      }
+      entries[i++].modification_of_pic_nums_idc = modification_of_pic_nums_idc;
+    }
+  }
+  *n_ref_pic_list_modification = i;
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing \"Reference picture list %u modification\"",
+      list);
+  return FALSE;
+}
+
+static gboolean
+slice_parse_ref_pic_list_modification (GstWFDH264SliceHdr * slice, WFDNalReader * nr)
+{
+  if (!GST_H264_IS_I_SLICE (slice) && !GST_H264_IS_SI_SLICE (slice)) {
+    if (!slice_parse_ref_pic_list_modification_1 (slice, nr, 0))
+      return FALSE;
+  }
+
+  if (GST_H264_IS_B_SLICE (slice)) {
+    if (!slice_parse_ref_pic_list_modification_1 (slice, nr, 1))
+      return FALSE;
+  }
+  return TRUE;
+}
+
+static gboolean
+gst_wfd_h264_slice_parse_dec_ref_pic_marking (GstWFDH264SliceHdr * slice,
+    GstWFDH264NalUnit * nalu, WFDNalReader * nr)
+{
+  GstWFDH264DecRefPicMarking *dec_ref_pic_m;
+
+  GST_DEBUG ("parsing \"Decoded reference picture marking\"");
+
+  dec_ref_pic_m = &slice->dec_ref_pic_marking;
+
+  if (nalu->idr_pic_flag) {
+    READ_UINT8 (nr, dec_ref_pic_m->no_output_of_prior_pics_flag, 1);
+    READ_UINT8 (nr, dec_ref_pic_m->long_term_reference_flag, 1);
+  } else {
+    READ_UINT8 (nr, dec_ref_pic_m->adaptive_ref_pic_marking_mode_flag, 1);
+    if (dec_ref_pic_m->adaptive_ref_pic_marking_mode_flag) {
+      guint32 mem_mgmt_ctrl_op;
+      GstWFDH264RefPicMarking *refpicmarking;
+
+      dec_ref_pic_m->n_ref_pic_marking = 0;
+      while (1) {
+        refpicmarking =
+            &dec_ref_pic_m->ref_pic_marking[dec_ref_pic_m->n_ref_pic_marking];
+
+        READ_UE (nr, mem_mgmt_ctrl_op);
+        if (mem_mgmt_ctrl_op == 0)
+          break;
+
+        refpicmarking->memory_management_control_operation = mem_mgmt_ctrl_op;
+
+        if (mem_mgmt_ctrl_op == 1 || mem_mgmt_ctrl_op == 3)
+          READ_UE (nr, refpicmarking->difference_of_pic_nums_minus1);
+
+        if (mem_mgmt_ctrl_op == 2)
+          READ_UE (nr, refpicmarking->long_term_pic_num);
+
+        if (mem_mgmt_ctrl_op == 3 || mem_mgmt_ctrl_op == 6)
+          READ_UE (nr, refpicmarking->long_term_frame_idx);
+
+        if (mem_mgmt_ctrl_op == 4)
+          READ_UE (nr, refpicmarking->max_long_term_frame_idx_plus1);
+
+        dec_ref_pic_m->n_ref_pic_marking++;
+      }
+    }
+  }
+
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing \"Decoded reference picture marking\"");
+  return FALSE;
+}
+
+static gboolean
+gst_wfd_h264_slice_parse_pred_weight_table (GstWFDH264SliceHdr * slice,
+    WFDNalReader * nr, guint8 chroma_array_type)
+{
+  GstWFDH264PredWeightTable *p;
+  gint16 default_luma_weight, default_chroma_weight;
+  gint i;
+
+  GST_DEBUG ("parsing \"Prediction weight table\"");
+
+  p = &slice->pred_weight_table;
+
+  READ_UE_ALLOWED (nr, p->luma_log2_weight_denom, 0, 7);
+  /* set default values */
+  default_luma_weight = 1 << p->luma_log2_weight_denom;
+  for (i = 0; i < G_N_ELEMENTS (p->luma_weight_l0); i++)
+    p->luma_weight_l0[i] = default_luma_weight;
+  memset (p->luma_offset_l0, 0, sizeof (p->luma_offset_l0));
+  if (GST_H264_IS_B_SLICE (slice)) {
+    for (i = 0; i < G_N_ELEMENTS (p->luma_weight_l1); i++)
+      p->luma_weight_l1[i] = default_luma_weight;
+    memset (p->luma_offset_l1, 0, sizeof (p->luma_offset_l1));
+  }
+
+  if (chroma_array_type != 0) {
+    READ_UE_ALLOWED (nr, p->chroma_log2_weight_denom, 0, 7);
+    /* set default values */
+    default_chroma_weight = 1 << p->chroma_log2_weight_denom;
+    for (i = 0; i < G_N_ELEMENTS (p->chroma_weight_l0); i++) {
+      p->chroma_weight_l0[i][0] = default_chroma_weight;
+      p->chroma_weight_l0[i][1] = default_chroma_weight;
+    }
+    memset (p->chroma_offset_l0, 0, sizeof (p->chroma_offset_l0));
+    if (GST_H264_IS_B_SLICE (slice)) {
+      for (i = 0; i < G_N_ELEMENTS (p->chroma_weight_l1); i++) {
+        p->chroma_weight_l1[i][0] = default_chroma_weight;
+        p->chroma_weight_l1[i][1] = default_chroma_weight;
+      }
+      memset (p->chroma_offset_l1, 0, sizeof (p->chroma_offset_l1));
+    }
+  }
+
+  for (i = 0; i <= slice->num_ref_idx_l0_active_minus1; i++) {
+    guint8 luma_weight_l0_flag;
+
+    READ_UINT8 (nr, luma_weight_l0_flag, 1);
+    if (luma_weight_l0_flag) {
+      READ_SE_ALLOWED (nr, p->luma_weight_l0[i], -128, 127);
+      READ_SE_ALLOWED (nr, p->luma_offset_l0[i], -128, 127);
+    }
+    if (chroma_array_type != 0) {
+      guint8 chroma_weight_l0_flag;
+      gint j;
+
+      READ_UINT8 (nr, chroma_weight_l0_flag, 1);
+      if (chroma_weight_l0_flag) {
+        for (j = 0; j < 2; j++) {
+          READ_SE_ALLOWED (nr, p->chroma_weight_l0[i][j], -128, 127);
+          READ_SE_ALLOWED (nr, p->chroma_offset_l0[i][j], -128, 127);
+        }
+      }
+    }
+  }
+
+  if (GST_H264_IS_B_SLICE (slice)) {
+    for (i = 0; i <= slice->num_ref_idx_l1_active_minus1; i++) {
+      guint8 luma_weight_l1_flag;
+
+      READ_UINT8 (nr, luma_weight_l1_flag, 1);
+      if (luma_weight_l1_flag) {
+        READ_SE_ALLOWED (nr, p->luma_weight_l1[i], -128, 127);
+        READ_SE_ALLOWED (nr, p->luma_offset_l1[i], -128, 127);
+      }
+      if (chroma_array_type != 0) {
+        guint8 chroma_weight_l1_flag;
+        gint j;
+
+        READ_UINT8 (nr, chroma_weight_l1_flag, 1);
+        if (chroma_weight_l1_flag) {
+          for (j = 0; j < 2; j++) {
+            READ_SE_ALLOWED (nr, p->chroma_weight_l1[i][j], -128, 127);
+            READ_SE_ALLOWED (nr, p->chroma_offset_l1[i][j], -128, 127);
+          }
+        }
+      }
+    }
+  }
+
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing \"Prediction weight table\"");
+  return FALSE;
+}
+
+static GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_buffering_period (GstWFDH264NalParser * nalparser,
+    GstWFDH264BufferingPeriod * per, WFDNalReader * nr)
+{
+  GstWFDH264SPS *sps;
+  guint8 sps_id;
+
+  GST_DEBUG ("parsing \"Buffering period\"");
+
+  READ_UE_ALLOWED (nr, sps_id, 0, GST_H264_MAX_SPS_COUNT - 1);
+  sps = gst_wfd_h264_parser_get_sps (nalparser, sps_id);
+  if (!sps) {
+    GST_WARNING ("couldn't find associated sequence parameter set with id: %d",
+        sps_id);
+    return GST_H264_PARSER_BROKEN_LINK;
+  }
+  per->sps = sps;
+
+  if (sps->vui_parameters_present_flag) {
+    GstWFDH264VUIParams *vui = &sps->vui_parameters;
+
+    if (vui->nal_hrd_parameters_present_flag) {
+      GstWFDH264HRDParams *hrd = &vui->nal_hrd_parameters;
+      const guint8 nbits = hrd->initial_cpb_removal_delay_length_minus1 + 1;
+      guint8 sched_sel_idx;
+
+      for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1;
+          sched_sel_idx++) {
+        READ_UINT8 (nr, per->nal_initial_cpb_removal_delay[sched_sel_idx],
+            nbits);
+        READ_UINT8 (nr,
+            per->nal_initial_cpb_removal_delay_offset[sched_sel_idx], nbits);
+      }
+    }
+
+    if (vui->vcl_hrd_parameters_present_flag) {
+      GstWFDH264HRDParams *hrd = &vui->vcl_hrd_parameters;
+      const guint8 nbits = hrd->initial_cpb_removal_delay_length_minus1 + 1;
+      guint8 sched_sel_idx;
+
+      for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1;
+          sched_sel_idx++) {
+        READ_UINT8 (nr, per->vcl_initial_cpb_removal_delay[sched_sel_idx],
+            nbits);
+        READ_UINT8 (nr,
+            per->vcl_initial_cpb_removal_delay_offset[sched_sel_idx], nbits);
+      }
+    }
+  }
+
+  return GST_H264_PARSER_OK;
+
+error:
+  GST_WARNING ("error parsing \"Buffering period\"");
+  return GST_H264_PARSER_ERROR;
+}
+
+static gboolean
+gst_wfd_h264_parse_clock_timestamp (GstWFDH264ClockTimestamp * tim,
+    GstWFDH264VUIParams * vui, WFDNalReader * nr)
+{
+  guint8 full_timestamp_flag;
+  guint8 time_offset_length;
+
+  GST_DEBUG ("parsing \"Clock timestamp\"");
+
+  /* defalt values */
+  tim->time_offset = 0;
+
+  READ_UINT8 (nr, tim->ct_type, 2);
+  READ_UINT8 (nr, tim->nuit_field_based_flag, 1);
+  READ_UINT8 (nr, tim->counting_type, 5);
+  READ_UINT8 (nr, full_timestamp_flag, 1);
+  READ_UINT8 (nr, tim->discontinuity_flag, 1);
+  READ_UINT8 (nr, tim->cnt_dropped_flag, 1);
+  READ_UINT8 (nr, tim->n_frames, 8);
+
+  if (full_timestamp_flag) {
+    tim->seconds_flag = TRUE;
+    READ_UINT8 (nr, tim->seconds_value, 6);
+
+    tim->minutes_flag = TRUE;
+    READ_UINT8 (nr, tim->minutes_value, 6);
+
+    tim->hours_flag = TRUE;
+    READ_UINT8 (nr, tim->hours_value, 5);
+  } else {
+    READ_UINT8 (nr, tim->seconds_flag, 1);
+    if (tim->seconds_flag) {
+      READ_UINT8 (nr, tim->seconds_value, 6);
+      READ_UINT8 (nr, tim->minutes_flag, 1);
+      if (tim->minutes_flag) {
+        READ_UINT8 (nr, tim->minutes_value, 6);
+        READ_UINT8 (nr, tim->hours_flag, 1);
+        if (tim->hours_flag)
+          READ_UINT8 (nr, tim->hours_value, 5);
+      }
+    }
+  }
+
+  time_offset_length = 0;
+  if (vui->nal_hrd_parameters_present_flag)
+    time_offset_length = vui->nal_hrd_parameters.time_offset_length;
+  else if (vui->vcl_hrd_parameters_present_flag)
+    time_offset_length = vui->vcl_hrd_parameters.time_offset_length;
+
+  if (time_offset_length > 0)
+    READ_UINT32 (nr, tim->time_offset, time_offset_length);
+
+  return TRUE;
+
+error:
+  GST_WARNING ("error parsing \"Clock timestamp\"");
+  return FALSE;
+}
+
+static GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_pic_timing (GstWFDH264NalParser * nalparser,
+    GstWFDH264PicTiming * tim, WFDNalReader * nr)
+{
+  GST_DEBUG ("parsing \"Picture timing\"");
+  if (!nalparser->last_sps || !nalparser->last_sps->valid) {
+    GST_WARNING ("didn't get the associated sequence paramater set for the "
+        "current access unit");
+    goto error;
+  }
+
+  /* default values */
+  tim->cpb_removal_delay = 0;
+  tim->dpb_output_delay = 0;
+  tim->pic_struct_present_flag = FALSE;
+  memset (tim->clock_timestamp_flag, 0, 3);
+
+  if (nalparser->last_sps->vui_parameters_present_flag) {
+    GstWFDH264VUIParams *vui = &nalparser->last_sps->vui_parameters;
+
+    if (vui->nal_hrd_parameters_present_flag) {
+      READ_UINT32 (nr, tim->cpb_removal_delay,
+          vui->nal_hrd_parameters.cpb_removal_delay_length_minus1 + 1);
+      READ_UINT32 (nr, tim->dpb_output_delay,
+          vui->nal_hrd_parameters.dpb_output_delay_length_minus1 + 1);
+    } else if (vui->vcl_hrd_parameters_present_flag) {
+      READ_UINT32 (nr, tim->cpb_removal_delay,
+          vui->vcl_hrd_parameters.cpb_removal_delay_length_minus1 + 1);
+      READ_UINT32 (nr, tim->dpb_output_delay,
+          vui->vcl_hrd_parameters.dpb_output_delay_length_minus1 + 1);
+    }
+
+    if (vui->pic_struct_present_flag) {
+      const guint8 num_clock_ts_table[9] = {
+        1, 1, 1, 2, 2, 3, 3, 2, 3
+      };
+      guint8 num_clock_num_ts;
+      guint i;
+
+      tim->pic_struct_present_flag = TRUE;
+      READ_UINT8 (nr, tim->pic_struct, 4);
+      CHECK_ALLOWED ((gint8) tim->pic_struct, 0, 8);
+
+      num_clock_num_ts = num_clock_ts_table[tim->pic_struct];
+      for (i = 0; i < num_clock_num_ts; i++) {
+        READ_UINT8 (nr, tim->clock_timestamp_flag[i], 1);
+        if (tim->clock_timestamp_flag[i]) {
+          if (!gst_wfd_h264_parse_clock_timestamp (&tim->clock_timestamp[i], vui,
+                  nr))
+            goto error;
+        }
+      }
+    }
+  }
+
+  return GST_H264_PARSER_OK;
+
+error:
+  GST_WARNING ("error parsing \"Picture timing\"");
+  return GST_H264_PARSER_ERROR;
+}
+
+static GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_recovery_point (GstWFDH264NalParser * nalparser,
+    GstWFDH264RecoveryPoint * rp, WFDNalReader * nr)
+{
+  GstWFDH264SPS *const sps = nalparser->last_sps;
+
+  GST_DEBUG ("parsing \"Recovery point\"");
+  if (!sps || !sps->valid) {
+    GST_WARNING ("didn't get the associated sequence paramater set for the "
+        "current access unit");
+    goto error;
+  }
+
+  READ_UE_ALLOWED (nr, rp->recovery_frame_cnt, 0, sps->max_frame_num - 1);
+  READ_UINT8 (nr, rp->exact_match_flag, 1);
+  READ_UINT8 (nr, rp->broken_link_flag, 1);
+  READ_UINT8 (nr, rp->changing_slice_group_idc, 2);
+
+  return GST_H264_PARSER_OK;
+
+error:
+  GST_WARNING ("error parsing \"Recovery point\"");
+  return GST_H264_PARSER_ERROR;
+}
+
+static GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_sei_message (GstWFDH264NalParser * nalparser,
+    WFDNalReader * nr, GstWFDH264SEIMessage * sei)
+{
+  guint32 payloadSize;
+  guint8 payload_type_byte, payload_size_byte;
+  guint remaining, payload_size;
+  GstWFDH264ParserResult res;
+
+  GST_DEBUG ("parsing \"Sei message\"");
+
+  sei->payloadType = 0;
+  do {
+    READ_UINT8 (nr, payload_type_byte, 8);
+    sei->payloadType += payload_type_byte;
+  } while (payload_type_byte == 0xff);
+
+  payloadSize = 0;
+  do {
+    READ_UINT8 (nr, payload_size_byte, 8);
+    payloadSize += payload_size_byte;
+  }
+  while (payload_size_byte == 0xff);
+
+  remaining = wfd_nal_reader_get_remaining (nr);
+  payload_size = payloadSize * 8 < remaining ? payloadSize * 8 : remaining;
+
+  GST_DEBUG ("SEI message received: payloadType  %u, payloadSize = %u bits",
+      sei->payloadType, payload_size);
+
+  switch (sei->payloadType) {
+    case GST_H264_SEI_BUF_PERIOD:
+      /* size not set; might depend on emulation_prevention_three_byte */
+      res = gst_wfd_h264_parser_parse_buffering_period (nalparser,
+          &sei->payload.buffering_period, nr);
+      break;
+    case GST_H264_SEI_PIC_TIMING:
+      /* size not set; might depend on emulation_prevention_three_byte */
+      res = gst_wfd_h264_parser_parse_pic_timing (nalparser,
+          &sei->payload.pic_timing, nr);
+      break;
+    case GST_H264_SEI_RECOVERY_POINT:
+      res = gst_wfd_h264_parser_parse_recovery_point (nalparser,
+          &sei->payload.recovery_point, nr);
+      break;
+    default:
+      /* Just consume payloadSize bytes, which does not account for
+         emulation prevention bytes */
+      if (!wfd_nal_reader_skip_long (nr, payload_size))
+        goto error;
+      res = GST_H264_PARSER_OK;
+      break;
+  }
+
+  /* When SEI message doesn't end at byte boundary,
+   * check remaining bits fit the specification.
+   */
+  if (!wfd_nal_reader_is_byte_aligned (nr)) {
+    guint8 bit_equal_to_one;
+    READ_UINT8 (nr, bit_equal_to_one, 1);
+    if (!bit_equal_to_one)
+      GST_WARNING ("Bit non equal to one.");
+
+    while (!wfd_nal_reader_is_byte_aligned (nr)) {
+      guint8 bit_equal_to_zero;
+      READ_UINT8 (nr, bit_equal_to_zero, 1);
+      if (bit_equal_to_zero)
+        GST_WARNING ("Bit non equal to zero.");
+    }
+  }
+
+  return res;
+
+error:
+  GST_WARNING ("error parsing \"Sei message\"");
+  return GST_H264_PARSER_ERROR;
+}
+
+/******** API *************/
+
+/**
+ * gst_wfd_h264_nal_parser_new:
+ *
+ * Creates a new #GstWFDH264NalParser. It should be freed with
+ * gst_wfd_h264_nal_parser_free after use.
+ *
+ * Returns: a new #GstWFDH264NalParser
+ */
+GstWFDH264NalParser *
+gst_wfd_h264_nal_parser_new (void)
+{
+  GstWFDH264NalParser *nalparser;
+
+  nalparser = g_slice_new0 (GstWFDH264NalParser);
+  INITIALIZE_DEBUG_CATEGORY;
+
+  return nalparser;
+}
+
+/**
+ * gst_wfd_h264_nal_parser_free:
+ * @nalparser: the #GstWFDH264NalParser to free
+ *
+ * Frees @nalparser and sets it to %NULL
+ */
+void
+gst_wfd_h264_nal_parser_free (GstWFDH264NalParser * nalparser)
+{
+  guint i;
+
+  for (i = 0; i < GST_H264_MAX_PPS_COUNT; i++)
+    gst_wfd_h264_pps_clear (&nalparser->pps[i]);
+  g_slice_free (GstWFDH264NalParser, nalparser);
+
+  nalparser = NULL;
+}
+
+/**
+ * gst_wfd_h264_parser_identify_nalu_unchecked:
+ * @nalparser: a #GstWFDH264NalParser
+ * @data: The data to parse
+ * @offset: the offset from which to parse @data
+ * @size: the size of @data
+ * @nalu: The #GstWFDH264NalUnit where to store parsed nal headers
+ *
+ * Parses @data and fills @nalu from the next nalu data from @data.
+ *
+ * This differs from @gst_wfd_h264_parser_identify_nalu in that it doesn't
+ * check whether the packet is complete or not.
+ *
+ * Note: Only use this function if you already know the provided @data
+ * is a complete NALU, else use @gst_wfd_h264_parser_identify_nalu.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_identify_nalu_unchecked (GstWFDH264NalParser * nalparser,
+    const guint8 * data, guint offset, gsize size, GstWFDH264NalUnit * nalu)
+{
+  gint off1;
+
+  if (size < offset + 4) {
+    GST_DEBUG ("Can't parse, buffer has too small size %" G_GSIZE_FORMAT
+        ", offset %u", size, offset);
+    return GST_H264_PARSER_ERROR;
+  }
+
+  off1 = scan_for_start_codes (data + offset, size - offset);
+
+  if (off1 < 0) {
+    GST_DEBUG ("No start code prefix in this buffer");
+    return GST_H264_PARSER_NO_NAL;
+  }
+
+  if (offset + off1 == size - 1) {
+    GST_DEBUG ("Missing data to identify nal unit");
+
+    return GST_H264_PARSER_ERROR;
+  }
+
+  nalu->sc_offset = offset + off1;
+
+
+  nalu->offset = offset + off1 + 3;
+  nalu->data = (guint8 *) data;
+  nalu->size = size - nalu->offset;
+
+  if (!gst_wfd_h264_parse_nalu_header (nalu)) {
+    GST_WARNING ("error parsing \"NAL unit header\"");
+    nalu->size = 0;
+    return GST_H264_PARSER_BROKEN_DATA;
+  }
+
+  nalu->valid = TRUE;
+
+  /* sc might have 2 or 3 0-bytes */
+  if (nalu->sc_offset > 0 && data[nalu->sc_offset - 1] == 00
+      && (nalu->type == GST_H264_NAL_SPS || nalu->type == GST_H264_NAL_PPS
+          || nalu->type == GST_H264_NAL_AU_DELIMITER))
+    nalu->sc_offset--;
+
+  if (nalu->type == GST_H264_NAL_SEQ_END ||
+      nalu->type == GST_H264_NAL_STREAM_END) {
+    GST_DEBUG ("end-of-seq or end-of-stream nal found");
+    nalu->size = 1;
+    return GST_H264_PARSER_OK;
+  }
+
+  return GST_H264_PARSER_OK;
+}
+
+/**
+ * gst_wfd_h264_parser_identify_nalu:
+ * @nalparser: a #GstWFDH264NalParser
+ * @data: The data to parse
+ * @offset: the offset from which to parse @data
+ * @size: the size of @data
+ * @nalu: The #GstWFDH264NalUnit where to store parsed nal headers
+ *
+ * Parses @data and fills @nalu from the next nalu data from @data
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_identify_nalu (GstWFDH264NalParser * nalparser,
+    const guint8 * data, guint offset, gsize size, GstWFDH264NalUnit * nalu)
+{
+  GstWFDH264ParserResult res;
+  gint off2;
+
+  res =
+      gst_wfd_h264_parser_identify_nalu_unchecked (nalparser, data, offset, size,
+      nalu);
+
+  if (res != GST_H264_PARSER_OK || nalu->size == 1)
+    goto beach;
+
+  off2 = scan_for_start_codes (data + nalu->offset, size - nalu->offset);
+  if (off2 < 0) {
+    GST_DEBUG ("Nal start %d, No end found", nalu->offset);
+
+    return GST_H264_PARSER_NO_NAL_END;
+  }
+
+  /* Mini performance improvement:
+   * We could have a way to store how many 0s were skipped to avoid
+   * parsing them again on the next NAL */
+  while (off2 > 0 && data[nalu->offset + off2 - 1] == 00)
+    off2--;
+
+  nalu->size = off2;
+  if (nalu->size < 2)
+    return GST_H264_PARSER_BROKEN_DATA;
+
+  GST_DEBUG ("Complete nal found. Off: %d, Size: %d", nalu->offset, nalu->size);
+
+beach:
+  return res;
+}
+
+
+/**
+ * gst_wfd_h264_parser_identify_nalu_avc:
+ * @nalparser: a #GstWFDH264NalParser
+ * @data: The data to parse, must be the beging of the Nal unit
+ * @offset: the offset from which to parse @data
+ * @size: the size of @data
+ * @nal_length_size: the size in bytes of the AVC nal length prefix.
+ * @nalu: The #GstWFDH264NalUnit where to store parsed nal headers
+ *
+ * Parses @data and sets @nalu.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_identify_nalu_avc (GstWFDH264NalParser * nalparser,
+    const guint8 * data, guint offset, gsize size, guint8 nal_length_size,
+    GstWFDH264NalUnit * nalu)
+{
+  GstBitReader br;
+
+  if (size < offset + nal_length_size) {
+    GST_DEBUG ("Can't parse, buffer has too small size %" G_GSIZE_FORMAT
+        ", offset %u", size, offset);
+    return GST_H264_PARSER_ERROR;
+  }
+
+  size = size - offset;
+  gst_bit_reader_init (&br, data + offset, size);
+
+  nalu->size = gst_bit_reader_get_bits_uint32_unchecked (&br,
+      nal_length_size * 8);
+  nalu->sc_offset = offset;
+  nalu->offset = offset + nal_length_size;
+
+  if (size < nalu->size + nal_length_size) {
+    nalu->size = 0;
+
+    return GST_H264_PARSER_NO_NAL_END;
+  }
+
+  nalu->data = (guint8 *) data;
+
+  if (!gst_wfd_h264_parse_nalu_header (nalu)) {
+    GST_WARNING ("error parsing \"NAL unit header\"");
+    nalu->size = 0;
+    return GST_H264_PARSER_BROKEN_DATA;
+  }
+
+  nalu->valid = TRUE;
+
+  return GST_H264_PARSER_OK;
+}
+
+/**
+ * gst_wfd_h264_parser_parse_nal:
+ * @nalparser: a #GstWFDH264NalParser
+ * @nalu: The #GstWFDH264NalUnit to parse
+ *
+ * This function should be called in the case one doesn't need to
+ * parse a specific structure. It is necessary to do so to make
+ * sure @nalparser is up to date.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_nal (GstWFDH264NalParser * nalparser, GstWFDH264NalUnit * nalu)
+{
+  GstWFDH264SPS sps;
+  GstWFDH264PPS pps;
+
+  switch (nalu->type) {
+    case GST_H264_NAL_SPS:
+      memset(&sps, 0, sizeof(GstWFDH264SPS));
+      return gst_wfd_h264_parser_parse_sps (nalparser, nalu, &sps, FALSE);
+      break;
+    case GST_H264_NAL_PPS:
+      memset(&pps, 0, sizeof(GstWFDH264PPS));
+      return gst_wfd_h264_parser_parse_pps (nalparser, nalu, &pps);
+  }
+
+  return GST_H264_PARSER_OK;
+}
+
+/**
+ * gst_wfd_h264_parser_parse_sps:
+ * @nalparser: a #GstWFDH264NalParser
+ * @nalu: The #GST_H264_NAL_SPS #GstWFDH264NalUnit to parse
+ * @sps: The #GstWFDH264SPS to fill.
+ * @parse_vui_params: Whether to parse the vui_params or not
+ *
+ * Parses @data, and fills the @sps structure.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_sps (GstWFDH264NalParser * nalparser, GstWFDH264NalUnit * nalu,
+    GstWFDH264SPS * sps, gboolean parse_vui_params)
+{
+  GstWFDH264ParserResult res = gst_wfd_h264_parse_sps (nalu, sps, parse_vui_params);
+
+  if (res == GST_H264_PARSER_OK) {
+    GST_DEBUG ("adding sequence parameter set with id: %d to array", sps->id);
+
+    nalparser->sps[sps->id] = *sps;
+    nalparser->last_sps = &nalparser->sps[sps->id];
+  }
+
+
+
+  return res;
+}
+
+/* Parse seq_parameter_set_data() */
+static gboolean
+gst_wfd_h264_parse_sps_data (WFDNalReader * nr, GstWFDH264SPS * sps,
+    gboolean parse_vui_params)
+{
+  gint width, height;
+  guint subwc[] = { 1, 2, 2, 1 };
+  guint subhc[] = { 1, 2, 1, 1 };
+  GstWFDH264VUIParams *vui = NULL;
+
+  /* set default values for fields that might not be present in the bitstream
+     and have valid defaults */
+  sps->chroma_format_idc = 1;
+  sps->separate_colour_plane_flag = 0;
+  sps->bit_depth_luma_minus8 = 0;
+  sps->bit_depth_chroma_minus8 = 0;
+  memset (sps->scaling_lists_4x4, 16, 96);
+  memset (sps->scaling_lists_8x8, 16, 384);
+  memset (&sps->vui_parameters, 0, sizeof (sps->vui_parameters));
+  sps->mb_adaptive_frame_field_flag = 0;
+  sps->frame_crop_left_offset = 0;
+  sps->frame_crop_right_offset = 0;
+  sps->frame_crop_top_offset = 0;
+  sps->frame_crop_bottom_offset = 0;
+  sps->delta_pic_order_always_zero_flag = 0;
+
+  READ_UINT8 (nr, sps->profile_idc, 8);
+  READ_UINT8 (nr, sps->constraint_set0_flag, 1);
+  READ_UINT8 (nr, sps->constraint_set1_flag, 1);
+  READ_UINT8 (nr, sps->constraint_set2_flag, 1);
+  READ_UINT8 (nr, sps->constraint_set3_flag, 1);
+
+  /* skip reserved_zero_4bits */
+  if (!wfd_nal_reader_skip (nr, 4))
+    goto error;
+
+  READ_UINT8 (nr, sps->level_idc, 8);
+
+  READ_UE_ALLOWED (nr, sps->id, 0, GST_H264_MAX_SPS_COUNT - 1);
+
+  if (sps->profile_idc == 100 || sps->profile_idc == 110 ||
+      sps->profile_idc == 122 || sps->profile_idc == 244 ||
+      sps->profile_idc == 44 || sps->profile_idc == 83 ||
+      sps->profile_idc == 86) {
+    READ_UE_ALLOWED (nr, sps->chroma_format_idc, 0, 3);
+    if (sps->chroma_format_idc == 3)
+      READ_UINT8 (nr, sps->separate_colour_plane_flag, 1);
+
+    READ_UE_ALLOWED (nr, sps->bit_depth_luma_minus8, 0, 6);
+    READ_UE_ALLOWED (nr, sps->bit_depth_chroma_minus8, 0, 6);
+    READ_UINT8 (nr, sps->qpprime_y_zero_transform_bypass_flag, 1);
+
+    READ_UINT8 (nr, sps->scaling_matrix_present_flag, 1);
+    if (sps->scaling_matrix_present_flag) {
+      guint8 n_lists;
+
+      n_lists = (sps->chroma_format_idc != 3) ? 8 : 12;
+      if (!gst_wfd_h264_parser_parse_scaling_list (nr,
+              sps->scaling_lists_4x4, sps->scaling_lists_8x8,
+              default_4x4_inter, default_4x4_intra,
+              default_8x8_inter, default_8x8_intra, n_lists))
+        goto error;
+    }
+  }
+
+  READ_UE_ALLOWED (nr, sps->log2_max_frame_num_minus4, 0, 12);
+
+  sps->max_frame_num = 1 << (sps->log2_max_frame_num_minus4 + 4);
+
+  READ_UE_ALLOWED (nr, sps->pic_order_cnt_type, 0, 2);
+  if (sps->pic_order_cnt_type == 0) {
+    READ_UE_ALLOWED (nr, sps->log2_max_pic_order_cnt_lsb_minus4, 0, 12);
+  } else if (sps->pic_order_cnt_type == 1) {
+    guint i;
+
+    READ_UINT8 (nr, sps->delta_pic_order_always_zero_flag, 1);
+    READ_SE (nr, sps->offset_for_non_ref_pic);
+    READ_SE (nr, sps->offset_for_top_to_bottom_field);
+    READ_UE_ALLOWED (nr, sps->num_ref_frames_in_pic_order_cnt_cycle, 0, 255);
+
+    for (i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++)
+      READ_SE (nr, sps->offset_for_ref_frame[i]);
+  }
+
+  READ_UE (nr, sps->num_ref_frames);
+  READ_UINT8 (nr, sps->gaps_in_frame_num_value_allowed_flag, 1);
+  READ_UE (nr, sps->pic_width_in_mbs_minus1);
+  READ_UE (nr, sps->pic_height_in_map_units_minus1);
+  READ_UINT8 (nr, sps->frame_mbs_only_flag, 1);
+
+  if (!sps->frame_mbs_only_flag)
+    READ_UINT8 (nr, sps->mb_adaptive_frame_field_flag, 1);
+
+  READ_UINT8 (nr, sps->direct_8x8_inference_flag, 1);
+  READ_UINT8 (nr, sps->frame_cropping_flag, 1);
+  if (sps->frame_cropping_flag) {
+    READ_UE (nr, sps->frame_crop_left_offset);
+    READ_UE (nr, sps->frame_crop_right_offset);
+    READ_UE (nr, sps->frame_crop_top_offset);
+    READ_UE (nr, sps->frame_crop_bottom_offset);
+  }
+
+  READ_UINT8 (nr, sps->vui_parameters_present_flag, 1);
+  if (sps->vui_parameters_present_flag && parse_vui_params) {
+    if (!gst_wfd_h264_parse_vui_parameters (sps, nr))
+      goto error;
+    vui = &sps->vui_parameters;
+  }
+
+  /* calculate ChromaArrayType */
+  if (sps->separate_colour_plane_flag)
+    sps->chroma_array_type = 0;
+  else
+    sps->chroma_array_type = sps->chroma_format_idc;
+
+  /* Calculate  width and height */
+  width = (sps->pic_width_in_mbs_minus1 + 1);
+  width *= 16;
+  height = (sps->pic_height_in_map_units_minus1 + 1);
+  height *= 16 * (2 - sps->frame_mbs_only_flag);
+  GST_LOG ("initial width=%d, height=%d", width, height);
+  if (width < 0 || height < 0) {
+    GST_WARNING ("invalid width/height in SPS");
+    goto error;
+  }
+
+  sps->width = width;
+  sps->height = height;
+
+  if (sps->frame_cropping_flag) {
+    const guint crop_unit_x = subwc[sps->chroma_format_idc];
+    const guint crop_unit_y =
+        subhc[sps->chroma_format_idc] * (2 - sps->frame_mbs_only_flag);
+
+    width -= (sps->frame_crop_left_offset + sps->frame_crop_right_offset)
+        * crop_unit_x;
+    height -= (sps->frame_crop_top_offset + sps->frame_crop_bottom_offset)
+        * crop_unit_y;
+
+    sps->crop_rect_width = width;
+    sps->crop_rect_height = height;
+    sps->crop_rect_x = sps->frame_crop_left_offset * crop_unit_x;
+    sps->crop_rect_y = sps->frame_crop_top_offset * crop_unit_y;
+
+    GST_LOG ("crop_rectangle x=%u y=%u width=%u, height=%u", sps->crop_rect_x,
+        sps->crop_rect_y, width, height);
+  }
+  sps->fps_num = 0;
+  sps->fps_den = 1;
+
+  if (vui && vui->timing_info_present_flag) {
+    /* derive framerate */
+    /* FIXME verify / also handle other cases */
+    GST_LOG ("Framerate: %u %u %u %u", parse_vui_params,
+        vui->fixed_frame_rate_flag, sps->frame_mbs_only_flag,
+        vui->pic_struct_present_flag);
+
+    if (parse_vui_params && vui->fixed_frame_rate_flag) {
+      sps->fps_num = vui->time_scale;
+      sps->fps_den = vui->num_units_in_tick;
+      /* picture is a frame = 2 fields */
+      sps->fps_den *= 2;
+      GST_LOG ("framerate %d/%d", sps->fps_num, sps->fps_den);
+    }
+  } else {
+    GST_LOG ("No VUI, unknown framerate");
+  }
+  return TRUE;
+
+error:
+  return FALSE;
+}
+
+/**
+ * gst_wfd_h264_parse_sps:
+ * @nalu: The #GST_H264_NAL_SPS #GstWFDH264NalUnit to parse
+ * @sps: The #GstWFDH264SPS to fill.
+ * @parse_vui_params: Whether to parse the vui_params or not
+ *
+ * Parses @data, and fills the @sps structure.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parse_sps (GstWFDH264NalUnit * nalu, GstWFDH264SPS * sps,
+    gboolean parse_vui_params)
+{
+  WFDNalReader nr;
+
+  INITIALIZE_DEBUG_CATEGORY;
+  GST_DEBUG ("parsing SPS");
+
+  wfd_nal_reader_init (&nr, nalu->data + nalu->offset + 1, nalu->size - 1);
+
+  if (!gst_wfd_h264_parse_sps_data (&nr, sps, parse_vui_params))
+    goto error;
+
+  sps->valid = TRUE;
+
+  return GST_H264_PARSER_OK;
+
+error:
+  GST_WARNING ("error parsing \"Sequence parameter set\"");
+  sps->valid = FALSE;
+  return GST_H264_PARSER_ERROR;
+}
+
+/**
+ * gst_wfd_h264_parse_pps:
+ * @nalparser: a #GstWFDH264NalParser
+ * @nalu: The #GST_H264_NAL_PPS #GstWFDH264NalUnit to parse
+ * @pps: The #GstWFDH264PPS to fill.
+ *
+ * Parses @data, and fills the @pps structure.
+ *
+ * The resulting @pps data structure shall be deallocated with the
+ * gst_wfd_h264_pps_clear() function when it is no longer needed, or prior
+ * to parsing a new PPS NAL unit.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parse_pps (GstWFDH264NalParser * nalparser, GstWFDH264NalUnit * nalu,
+    GstWFDH264PPS * pps)
+{
+  WFDNalReader nr;
+  GstWFDH264SPS *sps;
+  gint sps_id;
+  guint8 pic_scaling_matrix_present_flag;
+  gint qp_bd_offset;
+
+  INITIALIZE_DEBUG_CATEGORY;
+  GST_DEBUG ("parsing PPS");
+
+  wfd_nal_reader_init (&nr, nalu->data + nalu->offset + 1, nalu->size - 1);
+
+  READ_UE_ALLOWED (&nr, pps->id, 0, GST_H264_MAX_PPS_COUNT - 1);
+  READ_UE_ALLOWED (&nr, sps_id, 0, GST_H264_MAX_SPS_COUNT - 1);
+
+  sps = gst_wfd_h264_parser_get_sps (nalparser, sps_id);
+  if (!sps) {
+    GST_WARNING ("couldn't find associated sequence parameter set with id: %d",
+        sps_id);
+    return GST_H264_PARSER_BROKEN_LINK;
+  }
+  pps->sequence = sps;
+  qp_bd_offset = 6 * (sps->bit_depth_luma_minus8 +
+      sps->separate_colour_plane_flag);
+
+  /* set default values for fields that might not be present in the bitstream
+     and have valid defaults */
+  pps->slice_group_id = NULL;
+  pps->transform_8x8_mode_flag = 0;
+  memcpy (&pps->scaling_lists_4x4, &sps->scaling_lists_4x4, 96);
+  memcpy (&pps->scaling_lists_8x8, &sps->scaling_lists_8x8, 384);
+
+  READ_UINT8 (&nr, pps->entropy_coding_mode_flag, 1);
+  READ_UINT8 (&nr, pps->pic_order_present_flag, 1);
+  READ_UE_ALLOWED (&nr, pps->num_slice_groups_minus1, 0, 7);
+  if (pps->num_slice_groups_minus1 > 0) {
+    READ_UE_ALLOWED (&nr, pps->slice_group_map_type, 0, 6);
+
+    if (pps->slice_group_map_type == 0) {
+      gint i;
+
+      for (i = 0; i <= pps->num_slice_groups_minus1; i++)
+        READ_UE (&nr, pps->run_length_minus1[i]);
+    } else if (pps->slice_group_map_type == 2) {
+      gint i;
+
+      for (i = 0; i < pps->num_slice_groups_minus1; i++) {
+        READ_UE (&nr, pps->top_left[i]);
+        READ_UE (&nr, pps->bottom_right[i]);
+      }
+    } else if (pps->slice_group_map_type >= 3 && pps->slice_group_map_type <= 5) {
+      READ_UINT8 (&nr, pps->slice_group_change_direction_flag, 1);
+      READ_UE (&nr, pps->slice_group_change_rate_minus1);
+    } else if (pps->slice_group_map_type == 6) {
+      gint bits;
+      gint i;
+
+      READ_UE (&nr, pps->pic_size_in_map_units_minus1);
+      bits = g_bit_storage (pps->num_slice_groups_minus1);
+
+      pps->slice_group_id =
+          g_new (guint8, pps->pic_size_in_map_units_minus1 + 1);
+      for (i = 0; i <= pps->pic_size_in_map_units_minus1; i++)
+        READ_UINT8 (&nr, pps->slice_group_id[i], bits);
+    }
+  }
+
+  READ_UE_ALLOWED (&nr, pps->num_ref_idx_l0_active_minus1, 0, 31);
+  READ_UE_ALLOWED (&nr, pps->num_ref_idx_l1_active_minus1, 0, 31);
+  READ_UINT8 (&nr, pps->weighted_pred_flag, 1);
+  READ_UINT8 (&nr, pps->weighted_bipred_idc, 2);
+  READ_SE_ALLOWED (&nr, pps->pic_init_qp_minus26, -(26 + qp_bd_offset), 25);
+  READ_SE_ALLOWED (&nr, pps->pic_init_qs_minus26, -26, 25);
+  READ_SE_ALLOWED (&nr, pps->chroma_qp_index_offset, -12, 12);
+  pps->second_chroma_qp_index_offset = pps->chroma_qp_index_offset;
+  READ_UINT8 (&nr, pps->deblocking_filter_control_present_flag, 1);
+  READ_UINT8 (&nr, pps->constrained_intra_pred_flag, 1);
+  READ_UINT8 (&nr, pps->redundant_pic_cnt_present_flag, 1);
+
+  if (!wfd_nal_reader_has_more_data (&nr))
+    goto done;
+
+  READ_UINT8 (&nr, pps->transform_8x8_mode_flag, 1);
+
+  READ_UINT8 (&nr, pic_scaling_matrix_present_flag, 1);
+  if (pic_scaling_matrix_present_flag) {
+    guint8 n_lists;
+
+    n_lists = 6 + ((sps->chroma_format_idc != 3) ? 2 : 6) *
+        pps->transform_8x8_mode_flag;
+
+    if (sps->scaling_matrix_present_flag) {
+      if (!gst_wfd_h264_parser_parse_scaling_list (&nr,
+              pps->scaling_lists_4x4, pps->scaling_lists_8x8,
+              sps->scaling_lists_4x4[3], sps->scaling_lists_4x4[0],
+              sps->scaling_lists_8x8[3], sps->scaling_lists_8x8[0], n_lists))
+        goto error;
+    } else {
+      if (!gst_wfd_h264_parser_parse_scaling_list (&nr,
+              pps->scaling_lists_4x4, pps->scaling_lists_8x8,
+              default_4x4_inter, default_4x4_intra,
+              default_8x8_inter, default_8x8_intra, n_lists))
+        goto error;
+    }
+  }
+
+  READ_SE_ALLOWED (&nr, pps->second_chroma_qp_index_offset, -12, 12);
+
+done:
+  pps->valid = TRUE;
+  return GST_H264_PARSER_OK;
+
+error:
+  GST_WARNING ("error parsing \"Picture parameter set\"");
+  pps->valid = FALSE;
+  gst_wfd_h264_pps_clear (pps);
+  return GST_H264_PARSER_ERROR;
+}
+
+/**
+ * gst_wfd_h264_parser_parse_pps:
+ * @nalparser: a #GstWFDH264NalParser
+ * @nalu: The #GST_H264_NAL_PPS #GstWFDH264NalUnit to parse
+ * @pps: The #GstWFDH264PPS to fill.
+ *
+ * Parses @data, and fills the @pps structure.
+ *
+ * The resulting @pps data structure shall be deallocated with the
+ * gst_wfd_h264_pps_clear() function when it is no longer needed, or prior
+ * to parsing a new PPS NAL unit.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_pps (GstWFDH264NalParser * nalparser,
+    GstWFDH264NalUnit * nalu, GstWFDH264PPS * pps)
+{
+  GstWFDH264ParserResult res = gst_wfd_h264_parse_pps (nalparser, nalu, pps);
+
+  if (res == GST_H264_PARSER_OK) {
+    GST_DEBUG ("adding picture parameter set with id: %d to array", pps->id);
+
+    if (!gst_wfd_h264_pps_copy (&nalparser->pps[pps->id], pps))
+      return GST_H264_PARSER_ERROR;
+    nalparser->last_pps = &nalparser->pps[pps->id];
+  }
+
+  return res;
+}
+
+/**
+ * gst_wfd_h264_pps_clear:
+ * @pps: The #GstWFDH264PPS to free
+ *
+ * Clears all @pps internal resources.
+ *
+ * Since: 1.4
+ */
+void
+gst_wfd_h264_pps_clear (GstWFDH264PPS * pps)
+{
+  g_return_if_fail (pps != NULL);
+
+  g_free (pps->slice_group_id);
+  pps->slice_group_id = NULL;
+}
+
+/**
+ * gst_wfd_h264_parser_parse_slice_hdr:
+ * @nalparser: a #GstWFDH264NalParser
+ * @nalu: The #GST_H264_NAL_SLICE #GstWFDH264NalUnit to parse
+ * @slice: The #GstWFDH264SliceHdr to fill.
+ * @parse_pred_weight_table: Whether to parse the pred_weight_table or not
+ * @parse_dec_ref_pic_marking: Whether to parse the dec_ref_pic_marking or not
+ *
+ * Parses @data, and fills the @slice structure.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_slice_hdr (GstWFDH264NalParser * nalparser,
+    GstWFDH264NalUnit * nalu, GstWFDH264SliceHdr * slice,
+    gboolean parse_pred_weight_table, gboolean parse_dec_ref_pic_marking)
+{
+  WFDNalReader nr;
+  gint pps_id;
+  GstWFDH264PPS *pps;
+  GstWFDH264SPS *sps;
+
+  if (!nalu->size) {
+    GST_DEBUG ("Invalid Nal Unit");
+    return GST_H264_PARSER_ERROR;
+  }
+
+
+  wfd_nal_reader_init (&nr, nalu->data + nalu->offset + 1, nalu->size - 1);
+
+  READ_UE (&nr, slice->first_mb_in_slice);
+  READ_UE (&nr, slice->type);
+
+  GST_DEBUG ("parsing \"Slice header\", slice type %u", slice->type);
+
+  READ_UE_ALLOWED (&nr, pps_id, 0, GST_H264_MAX_PPS_COUNT - 1);
+  pps = gst_wfd_h264_parser_get_pps (nalparser, pps_id);
+
+  if (!pps) {
+    GST_WARNING ("couldn't find associated picture parameter set with id: %d",
+        pps_id);
+
+    return GST_H264_PARSER_BROKEN_LINK;
+  }
+
+  slice->pps = pps;
+  sps = pps->sequence;
+  if (!sps) {
+    GST_WARNING ("couldn't find associated sequence parameter set with id: %d",
+        pps->id);
+    return GST_H264_PARSER_BROKEN_LINK;
+  }
+
+  /* set default values for fields that might not be present in the bitstream
+     and have valid defaults */
+  slice->field_pic_flag = 0;
+  slice->bottom_field_flag = 0;
+  slice->delta_pic_order_cnt_bottom = 0;
+  slice->delta_pic_order_cnt[0] = 0;
+  slice->delta_pic_order_cnt[1] = 0;
+  slice->redundant_pic_cnt = 0;
+  slice->num_ref_idx_l0_active_minus1 = pps->num_ref_idx_l0_active_minus1;
+  slice->num_ref_idx_l1_active_minus1 = pps->num_ref_idx_l1_active_minus1;
+  slice->disable_deblocking_filter_idc = 0;
+  slice->slice_alpha_c0_offset_div2 = 0;
+  slice->slice_beta_offset_div2 = 0;
+
+  if (sps->separate_colour_plane_flag)
+    READ_UINT8 (&nr, slice->colour_plane_id, 2);
+
+  READ_UINT16 (&nr, slice->frame_num, sps->log2_max_frame_num_minus4 + 4);
+
+  if (!sps->frame_mbs_only_flag) {
+    READ_UINT8 (&nr, slice->field_pic_flag, 1);
+    if (slice->field_pic_flag)
+      READ_UINT8 (&nr, slice->bottom_field_flag, 1);
+  }
+
+  /* calculate MaxPicNum */
+  if (slice->field_pic_flag)
+    slice->max_pic_num = 2 * sps->max_frame_num;
+  else
+    slice->max_pic_num = sps->max_frame_num;
+
+  if (nalu->idr_pic_flag)
+    READ_UE_ALLOWED (&nr, slice->idr_pic_id, 0, G_MAXUINT16);
+
+  if (sps->pic_order_cnt_type == 0) {
+    READ_UINT16 (&nr, slice->pic_order_cnt_lsb,
+        sps->log2_max_pic_order_cnt_lsb_minus4 + 4);
+
+    if (pps->pic_order_present_flag && !slice->field_pic_flag)
+      READ_SE (&nr, slice->delta_pic_order_cnt_bottom);
+  }
+
+  if (sps->pic_order_cnt_type == 1 && !sps->delta_pic_order_always_zero_flag) {
+    READ_SE (&nr, slice->delta_pic_order_cnt[0]);
+    if (pps->pic_order_present_flag && !slice->field_pic_flag)
+      READ_SE (&nr, slice->delta_pic_order_cnt[1]);
+  }
+
+  if (pps->redundant_pic_cnt_present_flag)
+    READ_UE_ALLOWED (&nr, slice->redundant_pic_cnt, 0, G_MAXINT8);
+
+  if (GST_H264_IS_B_SLICE (slice))
+    READ_UINT8 (&nr, slice->direct_spatial_mv_pred_flag, 1);
+
+  if (GST_H264_IS_P_SLICE (slice) || GST_H264_IS_SP_SLICE (slice) ||
+      GST_H264_IS_B_SLICE (slice)) {
+    guint8 num_ref_idx_active_override_flag;
+
+    READ_UINT8 (&nr, num_ref_idx_active_override_flag, 1);
+    if (num_ref_idx_active_override_flag) {
+      READ_UE_ALLOWED (&nr, slice->num_ref_idx_l0_active_minus1, 0, 31);
+
+      if (GST_H264_IS_B_SLICE (slice))
+        READ_UE_ALLOWED (&nr, slice->num_ref_idx_l1_active_minus1, 0, 31);
+    }
+  }
+
+  if (!slice_parse_ref_pic_list_modification (slice, &nr))
+    goto error;
+
+  if ((pps->weighted_pred_flag && (GST_H264_IS_P_SLICE (slice)
+              || GST_H264_IS_SP_SLICE (slice)))
+      || (pps->weighted_bipred_idc == 1 && GST_H264_IS_B_SLICE (slice))) {
+    if (!gst_wfd_h264_slice_parse_pred_weight_table (slice, &nr,
+            sps->chroma_array_type))
+      goto error;
+  }
+
+  if (nalu->ref_idc != 0) {
+    if (!gst_wfd_h264_slice_parse_dec_ref_pic_marking (slice, nalu, &nr))
+      goto error;
+  }
+
+  if (pps->entropy_coding_mode_flag && !GST_H264_IS_I_SLICE (slice) &&
+      !GST_H264_IS_SI_SLICE (slice))
+    READ_UE_ALLOWED (&nr, slice->cabac_init_idc, 0, 2);
+
+  READ_SE_ALLOWED (&nr, slice->slice_qp_delta, -87, 77);
+
+  if (GST_H264_IS_SP_SLICE (slice) || GST_H264_IS_SI_SLICE (slice)) {
+    guint8 sp_for_switch_flag;
+
+    if (GST_H264_IS_SP_SLICE (slice))
+      READ_UINT8 (&nr, sp_for_switch_flag, 1);
+    READ_SE_ALLOWED (&nr, slice->slice_qs_delta, -51, 51);
+  }
+
+  if (pps->deblocking_filter_control_present_flag) {
+    READ_UE_ALLOWED (&nr, slice->disable_deblocking_filter_idc, 0, 2);
+    if (slice->disable_deblocking_filter_idc != 1) {
+      READ_SE_ALLOWED (&nr, slice->slice_alpha_c0_offset_div2, -6, 6);
+      READ_SE_ALLOWED (&nr, slice->slice_beta_offset_div2, -6, 6);
+    }
+  }
+
+  if (pps->num_slice_groups_minus1 > 0 &&
+      pps->slice_group_map_type >= 3 && pps->slice_group_map_type <= 5) {
+    /* Ceil(Log2(PicSizeInMapUnits / SliceGroupChangeRate + 1))  [7-33] */
+    guint32 PicWidthInMbs = sps->pic_width_in_mbs_minus1 + 1;
+    guint32 PicHeightInMapUnits = sps->pic_height_in_map_units_minus1 + 1;
+    guint32 PicSizeInMapUnits = PicWidthInMbs * PicHeightInMapUnits;
+    guint32 SliceGroupChangeRate = pps->slice_group_change_rate_minus1 + 1;
+    const guint n = ceil_log2 (PicSizeInMapUnits / SliceGroupChangeRate + 1);
+    READ_UINT16 (&nr, slice->slice_group_change_cycle, n);
+  }
+
+  slice->header_size = wfd_nal_reader_get_pos (&nr);
+  slice->n_emulation_prevention_bytes = wfd_nal_reader_get_epb_count (&nr);
+
+  return GST_H264_PARSER_OK;
+
+error:
+  GST_WARNING ("error parsing \"Slice header\"");
+  return GST_H264_PARSER_ERROR;
+}
+
+/**
+ * gst_wfd_h264_parser_parse_sei:
+ * @nalparser: a #GstWFDH264NalParser
+ * @nalu: The #GST_H264_NAL_SEI #GstWFDH264NalUnit to parse
+ * @messages: The GArray of #GstWFDH264SEIMessage to fill. The caller must free it when done.
+ *
+ * Parses @data, create and fills the @messages array.
+ *
+ * Returns: a #GstWFDH264ParserResult
+ */
+GstWFDH264ParserResult
+gst_wfd_h264_parser_parse_sei (GstWFDH264NalParser * nalparser, GstWFDH264NalUnit * nalu,
+    GArray ** messages)
+{
+  WFDNalReader nr;
+  GstWFDH264SEIMessage sei;
+  GstWFDH264ParserResult res;
+
+  GST_DEBUG ("parsing SEI nal");
+  wfd_nal_reader_init (&nr, nalu->data + nalu->offset + 1, nalu->size - 1);
+  *messages = g_array_new (FALSE, FALSE, sizeof (GstWFDH264SEIMessage));
+
+  do {
+    res = gst_wfd_h264_parser_parse_sei_message (nalparser, &nr, &sei);
+    if (res == GST_H264_PARSER_OK)
+      g_array_append_val (*messages, sei);
+    else
+      break;
+  } while (wfd_nal_reader_has_more_data (&nr));
+
+  return res;
+}
+
+/**
+ * gst_wfd_h264_quant_matrix_8x8_get_zigzag_from_raster:
+ * @out_quant: (out): The resulting quantization matrix
+ * @quant: The source quantization matrix
+ *
+ * Converts quantization matrix @quant from raster scan order to
+ * zigzag scan order and store the resulting factors into @out_quant.
+ *
+ * Note: it is an error to pass the same table in both @quant and
+ * @out_quant arguments.
+ *
+ * Since: 1.4
+ */
+void
+gst_wfd_h264_quant_matrix_8x8_get_zigzag_from_raster (guint8 out_quant[64],
+    const guint8 quant[64])
+{
+  guint i;
+
+  g_return_if_fail (out_quant != quant);
+
+  for (i = 0; i < 64; i++)
+    out_quant[i] = quant[zigzag_8x8[i]];
+}
+
+/**
+ * gst_wfd_h264_quant_matrix_8x8_get_raster_from_zigzag:
+ * @out_quant: (out): The resulting quantization matrix
+ * @quant: The source quantization matrix
+ *
+ * Converts quantization matrix @quant from zigzag scan order to
+ * raster scan order and store the resulting factors into @out_quant.
+ *
+ * Note: it is an error to pass the same table in both @quant and
+ * @out_quant arguments.
+ *
+ * Since: 1.4
+ */
+void
+gst_wfd_h264_quant_matrix_8x8_get_raster_from_zigzag (guint8 out_quant[64],
+    const guint8 quant[64])
+{
+  guint i;
+
+  g_return_if_fail (out_quant != quant);
+
+  for (i = 0; i < 64; i++)
+    out_quant[zigzag_8x8[i]] = quant[i];
+}
+
+/**
+ * gst_wfd_h264_quant_matrix_4x4_get_zigzag_from_raster:
+ * @out_quant: (out): The resulting quantization matrix
+ * @quant: The source quantization matrix
+ *
+ * Converts quantization matrix @quant from raster scan order to
+ * zigzag scan order and store the resulting factors into @out_quant.
+ *
+ * Note: it is an error to pass the same table in both @quant and
+ * @out_quant arguments.
+ *
+ * Since: 1.4
+ */
+void
+gst_wfd_h264_quant_matrix_4x4_get_zigzag_from_raster (guint8 out_quant[16],
+    const guint8 quant[16])
+{
+  guint i;
+
+  g_return_if_fail (out_quant != quant);
+
+  for (i = 0; i < 16; i++)
+    out_quant[i] = quant[zigzag_4x4[i]];
+}
+
+/**
+ * gst_wfd_h264_quant_matrix_4x4_get_raster_from_zigzag:
+ * @out_quant: (out): The resulting quantization matrix
+ * @quant: The source quantization matrix
+ *
+ * Converts quantization matrix @quant from zigzag scan order to
+ * raster scan order and store the resulting factors into @out_quant.
+ *
+ * Note: it is an error to pass the same table in both @quant and
+ * @out_quant arguments.
+ *
+ * Since: 1.4
+ */
+void
+gst_wfd_h264_quant_matrix_4x4_get_raster_from_zigzag (guint8 out_quant[16],
+    const guint8 quant[16])
+{
+  guint i;
+
+  g_return_if_fail (out_quant != quant);
+
+  for (i = 0; i < 16; i++)
+    out_quant[zigzag_4x4[i]] = quant[i];
+}
+
+/**
+ * gst_wfd_h264_video_calculate_framerate:
+ * @sps: Current Sequence Parameter Set
+ * @field_pic_flag: Current @field_pic_flag, obtained from latest slice header
+ * @pic_struct: @pic_struct value if available, 0 otherwise
+ * @fps_num: (out): The resulting fps numerator
+ * @fps_den: (out): The resulting fps denominator
+ *
+ * Calculate framerate of a video sequence using @sps VUI information,
+ * @field_pic_flag from a slice header and @pic_struct from #GstWFDH264PicTiming SEI
+ * message.
+ *
+ * If framerate is variable or can't be determined, @fps_num will be set to 0
+ * and @fps_den to 1.
+ */
+void
+gst_wfd_h264_video_calculate_framerate (const GstWFDH264SPS * sps,
+    guint field_pic_flag, guint pic_struct, gint * fps_num, gint * fps_den)
+{
+  gint num = 0;
+  gint den = 1;
+
+  /* To calculate framerate, we use this formula:
+   *          time_scale                1                         1
+   * fps = -----------------  x  ---------------  x  ------------------------
+   *       num_units_in_tick     DeltaTfiDivisor     (field_pic_flag ? 2 : 1)
+   *
+   * See H264 specification E2.1 for more details.
+   */
+
+  if (sps) {
+    if (sps->vui_parameters_present_flag) {
+      const GstWFDH264VUIParams *vui = &sps->vui_parameters;
+      if (vui->timing_info_present_flag && vui->fixed_frame_rate_flag) {
+        int delta_tfi_divisor = 1;
+        num = vui->time_scale;
+        den = vui->num_units_in_tick;
+
+        if (vui->pic_struct_present_flag) {
+          switch (pic_struct) {
+            case 1:
+            case 2:
+              delta_tfi_divisor = 1;
+              break;
+            case 0:
+            case 3:
+            case 4:
+              delta_tfi_divisor = 2;
+              break;
+            case 5:
+            case 6:
+              delta_tfi_divisor = 3;
+              break;
+            case 7:
+              delta_tfi_divisor = 4;
+              break;
+            case 8:
+              delta_tfi_divisor = 6;
+              break;
+          }
+        } else {
+          delta_tfi_divisor = field_pic_flag ? 1 : 2;
+        }
+        den *= delta_tfi_divisor;
+
+        /* Picture is two fields ? */
+        den *= (field_pic_flag ? 2 : 1);
+      }
+    }
+  }
+
+  *fps_num = num;
+  *fps_den = den;
+}
diff --git a/wfdtsdemux/gstwfdh264parser.h b/wfdtsdemux/gstwfdh264parser.h
new file mode 100755 (executable)
index 0000000..92b2f92
--- /dev/null
@@ -0,0 +1,802 @@
+/* Gstreamer
+ * Copyright (C) <2011> Intel Corporation
+ * Copyright (C) <2011> Collabora Ltd.
+ * Copyright (C) <2011> Thibault Saunier <thibault.saunier@collabora.com>
+ *
+ * Some bits C-c,C-v'ed and s/4/3 from h264parse and videoparsers/h264parse.c:
+ *    Copyright (C) <2010> Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>
+ *    Copyright (C) <2010> Collabora Multimedia
+ *    Copyright (C) <2010> Nokia Corporation
+ *
+ *    (C) 2005 Michal Benes <michal.benes@itonis.tv>
+ *    (C) 2008 Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef __GST_WFD_H264_PARSER_H__
+#define __GST_WFD_H264_PARSER_H__
+
+#include <gst/gst.h>
+
+G_BEGIN_DECLS
+
+#define GST_H264_MAX_SPS_COUNT   32
+#define GST_H264_MAX_PPS_COUNT   256
+
+#define GST_H264_IS_P_SLICE(slice)  (((slice)->type % 5) == GST_H264_P_SLICE)
+#define GST_H264_IS_B_SLICE(slice)  (((slice)->type % 5) == GST_H264_B_SLICE)
+#define GST_H264_IS_I_SLICE(slice)  (((slice)->type % 5) == GST_H264_I_SLICE)
+#define GST_H264_IS_SP_SLICE(slice) (((slice)->type % 5) == GST_H264_SP_SLICE)
+#define GST_H264_IS_SI_SLICE(slice) (((slice)->type % 5) == GST_H264_SI_SLICE)
+
+/**
+ * GstWFDH264Profile:
+ * @GST_H264_PROFILE_BASELINE: Baseline profile (A.2.1)
+ * @GST_H264_PROFILE_MAIN: Main profile (A.2.2)
+ * @GST_H264_PROFILE_EXTENDED: Extended profile (A.2.3)
+ * @GST_H264_PROFILE_HIGH: High profile (A.2.4)
+ * @GST_H264_PROFILE_HIGH10: High 10 profile (A.2.5) or High 10 Intra
+ *   profile (A.2.8), depending on constraint_set3_flag
+ * @GST_H264_PROFILE_HIGH_422: High 4:2:2 profile (A.2.6) or High
+ *   4:2:2 Intra profile (A.2.9), depending on constraint_set3_flag
+ * @GST_H264_PROFILE_HIGH_444: High 4:4:4 Predictive profile (A.2.7)
+ *   or High 4:4:4 Intra profile (A.2.10), depending on the value of
+ *   constraint_set3_flag
+ * @GST_H264_PROFILE_MULTIVIEW_HIGH: Multiview High profile (H.10.1.1)
+ * @GST_H264_PROFILE_STEREO_HIGH: Stereo High profile (H.10.1.2)
+ * @GST_H264_PROFILE_SCALABLE_BASELINE: Scalable Baseline profile (G.10.1.1)
+ * @GST_H264_PROFILE_SCALABLE_HIGH: Scalable High profile (G.10.1.2)
+ *   or Scalable High Intra profile (G.10.1.3), depending on the value
+ *   of constraint_set3_flag
+ *
+ * H.264 Profiles.
+ *
+ * Since: 1.2
+ */
+typedef enum {
+  GST_H264_PROFILE_BASELINE             = 66,
+  GST_H264_PROFILE_MAIN                 = 77,
+  GST_H264_PROFILE_EXTENDED             = 88,
+  GST_H264_PROFILE_HIGH                 = 100,
+  GST_H264_PROFILE_HIGH10               = 110,
+  GST_H264_PROFILE_HIGH_422             = 122,
+  GST_H264_PROFILE_HIGH_444             = 244,
+  GST_H264_PROFILE_MULTIVIEW_HIGH       = 118,
+  GST_H264_PROFILE_STEREO_HIGH          = 128,
+  GST_H264_PROFILE_SCALABLE_BASELINE    = 83,
+  GST_H264_PROFILE_SCALABLE_HIGH        = 86
+} GstWFDH264Profile;
+
+/**
+ * GstWFDH264NalUnitType:
+ * @GST_H264_NAL_UNKNOWN: Unknown nal type
+ * @GST_H264_NAL_SLICE: Slice nal
+ * @GST_H264_NAL_SLICE_DPA: DPA slice nal
+ * @GST_H264_NAL_SLICE_DPB: DPB slice nal
+ * @GST_H264_NAL_SLICE_DPC: DPC slice nal
+ * @GST_H264_NAL_SLICE_IDR: DPR slice nal
+ * @GST_H264_NAL_SEI: Supplemental enhancement information (SEI) nal unit
+ * @GST_H264_NAL_SPS: Sequence parameter set (SPS) nal unit
+ * @GST_H264_NAL_PPS: Picture parameter set (PPS) nal unit
+ * @GST_H264_NAL_AU_DELIMITER: Access unit (AU) delimiter nal unit
+ * @GST_H264_NAL_SEQ_END: End of sequence nal unit
+ * @GST_H264_NAL_STREAM_END: End of stream nal unit
+ * @GST_H264_NAL_FILLER_DATA: Filler data nal lunit
+ * @GST_H264_NAL_SPS_EXT: Sequence parameter set (SPS) extension NAL unit
+ * @GST_H264_NAL_PREFIX_UNIT: Prefix NAL unit
+ * @GST_H264_NAL_SUBSET_SPS: Subset sequence parameter set (SPS) NAL unit
+ * @GST_H264_NAL_SLICE_AUX: Auxiliary coded picture without partitioning NAL unit
+ * @GST_H264_NAL_SLICE_EXT: Coded slice extension NAL unit
+ *
+ * Indicates the type of H264 Nal Units
+ */
+typedef enum
+{
+  GST_H264_NAL_UNKNOWN      = 0,
+  GST_H264_NAL_SLICE        = 1,
+  GST_H264_NAL_SLICE_DPA    = 2,
+  GST_H264_NAL_SLICE_DPB    = 3,
+  GST_H264_NAL_SLICE_DPC    = 4,
+  GST_H264_NAL_SLICE_IDR    = 5,
+  GST_H264_NAL_SEI          = 6,
+  GST_H264_NAL_SPS          = 7,
+  GST_H264_NAL_PPS          = 8,
+  GST_H264_NAL_AU_DELIMITER = 9,
+  GST_H264_NAL_SEQ_END      = 10,
+  GST_H264_NAL_STREAM_END   = 11,
+  GST_H264_NAL_FILLER_DATA  = 12,
+  GST_H264_NAL_SPS_EXT      = 13,
+  GST_H264_NAL_PREFIX_UNIT  = 14,
+  GST_H264_NAL_SUBSET_SPS   = 15,
+  GST_H264_NAL_SLICE_AUX    = 19,
+  GST_H264_NAL_SLICE_EXT    = 20
+} GstWFDH264NalUnitType;
+
+/**
+ * GstWFDH264ParserResult:
+ * @GST_H264_PARSER_OK: The parsing succeded
+ * @GST_H264_PARSER_BROKEN_DATA: The data to parse is broken
+ * @GST_H264_PARSER_BROKEN_LINK: The link to structure needed for the parsing couldn't be found
+ * @GST_H264_PARSER_ERROR: An error accured when parsing
+ * @GST_H264_PARSER_NO_NAL: No nal found during the parsing
+ * @GST_H264_PARSER_NO_NAL_END: Start of the nal found, but not the end.
+ *
+ * The result of parsing H264 data.
+ */
+typedef enum
+{
+  GST_H264_PARSER_OK,
+  GST_H264_PARSER_BROKEN_DATA,
+  GST_H264_PARSER_BROKEN_LINK,
+  GST_H264_PARSER_ERROR,
+  GST_H264_PARSER_NO_NAL,
+  GST_H264_PARSER_NO_NAL_END
+} GstWFDH264ParserResult;
+
+/**
+ * GstWFDH264SEIPayloadType:
+ * @GST_H264_SEI_BUF_PERIOD: Buffering Period SEI Message
+ * @GST_H264_SEI_PIC_TIMING: Picture Timing SEI Message
+ * @GST_H264_SEI_RECOVERY_POINT: Recovery Point SEI Message (D.2.7)
+ * ...
+ *
+ * The type of SEI message.
+ */
+typedef enum
+{
+  GST_H264_SEI_BUF_PERIOD = 0,
+  GST_H264_SEI_PIC_TIMING = 1,
+  GST_H264_SEI_RECOVERY_POINT = 6,
+      /* and more...  */
+} GstWFDH264SEIPayloadType;
+
+/**
+ * GstWFDH264SEIPicStructType:
+ * @GST_H264_SEI_PIC_STRUCT_FRAME: Picture is a frame
+ * @GST_H264_SEI_PIC_STRUCT_TOP_FIELD: Top field of frame
+ * @GST_H264_SEI_PIC_STRUCT_BOTTOM_FIELD: Botom field of frame
+ * @GST_H264_SEI_PIC_STRUCT_TOP_BOTTOM: Top bottom field of frame
+ * @GST_H264_SEI_PIC_STRUCT_BOTTOM_TOP: bottom top field of frame
+ * @GST_H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP: top bottom top field of frame
+ * @GST_H264_SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM: bottom top bottom field of frame
+ * @GST_H264_SEI_PIC_STRUCT_FRAME_DOUBLING: indicates that the frame should
+ *  be displayed two times consecutively
+ * @GST_H264_SEI_PIC_STRUCT_FRAME_TRIPLING: indicates that the frame should be
+ *  displayed three times consecutively
+ *
+ * SEI pic_struct type
+ */
+typedef enum
+{
+  GST_H264_SEI_PIC_STRUCT_FRAME             = 0,
+  GST_H264_SEI_PIC_STRUCT_TOP_FIELD         = 1,
+  GST_H264_SEI_PIC_STRUCT_BOTTOM_FIELD      = 2,
+  GST_H264_SEI_PIC_STRUCT_TOP_BOTTOM        = 3,
+  GST_H264_SEI_PIC_STRUCT_BOTTOM_TOP        = 4,
+  GST_H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP    = 5,
+  GST_H264_SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM = 6,
+  GST_H264_SEI_PIC_STRUCT_FRAME_DOUBLING    = 7,
+  GST_H264_SEI_PIC_STRUCT_FRAME_TRIPLING    = 8
+} GstWFDH264SEIPicStructType;
+
+/**
+ * GstWFDH264SliceType:
+ *
+ * Type of Picture slice
+ */
+
+typedef enum
+{
+  GST_H264_P_SLICE    = 0,
+  GST_H264_B_SLICE    = 1,
+  GST_H264_I_SLICE    = 2,
+  GST_H264_SP_SLICE   = 3,
+  GST_H264_SI_SLICE   = 4,
+  GST_H264_S_P_SLICE  = 5,
+  GST_H264_S_B_SLICE  = 6,
+  GST_H264_S_I_SLICE  = 7,
+  GST_H264_S_SP_SLICE = 8,
+  GST_H264_S_SI_SLICE = 9
+} GstWFDH264SliceType;
+
+typedef struct _GstWFDH264NalParser              GstWFDH264NalParser;
+
+typedef struct _GstWFDH264NalUnit                GstWFDH264NalUnit;
+
+typedef struct _GstWFDH264SPS                    GstWFDH264SPS;
+typedef struct _GstWFDH264PPS                    GstWFDH264PPS;
+typedef struct _GstWFDH264HRDParams              GstWFDH264HRDParams;
+typedef struct _GstWFDH264VUIParams              GstWFDH264VUIParams;
+
+typedef struct _GstWFDH264RefPicListModification GstWFDH264RefPicListModification;
+typedef struct _GstWFDH264DecRefPicMarking       GstWFDH264DecRefPicMarking;
+typedef struct _GstWFDH264RefPicMarking          GstWFDH264RefPicMarking;
+typedef struct _GstWFDH264PredWeightTable        GstWFDH264PredWeightTable;
+typedef struct _GstWFDH264SliceHdr               GstWFDH264SliceHdr;
+
+typedef struct _GstWFDH264ClockTimestamp         GstWFDH264ClockTimestamp;
+typedef struct _GstWFDH264PicTiming              GstWFDH264PicTiming;
+typedef struct _GstWFDH264BufferingPeriod        GstWFDH264BufferingPeriod;
+typedef struct _GstWFDH264RecoveryPoint          GstWFDH264RecoveryPoint;
+typedef struct _GstWFDH264SEIMessage             GstWFDH264SEIMessage;
+
+/**
+ * GstWFDH264NalUnit:
+ * @ref_idc: not equal to 0 specifies that the content of the NAL unit
+ *  contains a sequence parameter set, a sequence parameter set
+ *  extension, a subset sequence parameter set, a picture parameter
+ *  set, a slice of a reference picture, a slice data partition of a
+ *  reference picture, or a prefix NAL unit preceding a slice of a
+ *  reference picture.
+ * @type: A #GstWFDH264NalUnitType
+ * @idr_pic_flag: calculated idr_pic_flag
+ * @size: The size of the nal unit starting from @offset, thus
+ *  including the header bytes. e.g. @type (nal_unit_type)
+ * @offset: The offset of the actual start of the nal unit, thus
+ *  including the header bytes
+ * @sc_offset: The offset of the start code of the nal unit
+ * @valid: If the nal unit is valid, which means it has
+ * already been parsed
+ * @data: The data from which the Nalu has been parsed
+ *
+ * Structure defining the Nal unit headers
+ */
+struct _GstWFDH264NalUnit
+{
+  guint16 ref_idc;
+  guint16 type;
+
+  /* calculated values */
+  guint8 idr_pic_flag;
+  guint size;
+  guint offset;
+  guint sc_offset;
+  gboolean valid;
+
+  guint8 *data;
+};
+
+/**
+ * GstWFDH264HRDParams:
+ * @cpb_cnt_minus1: plus 1 specifies the number of alternative
+ *    CPB specifications in the bitstream
+ * @bit_rate_scale: specifies the maximum input bit rate of the
+ * SchedSelIdx-th CPB
+ * @cpb_size_scale: specifies the CPB size of the SchedSelIdx-th CPB
+ * @guint32 bit_rate_value_minus1: specifies the maximum input bit rate for the
+ * SchedSelIdx-th CPB
+ * @cpb_size_value_minus1: is used together with cpb_size_scale to specify the
+ * SchedSelIdx-th CPB size
+ * @cbr_flag: Specifies if running in itermediate bitrate mode or constant
+ * @initial_cpb_removal_delay_length_minus1: specifies the length in bits of
+ * the cpb_removal_delay syntax element
+ * @cpb_removal_delay_length_minus1: specifies the length in bits of the
+ * dpb_output_delay syntax element
+ * @dpb_output_delay_length_minus1: >0 specifies the length in bits of the time_offset syntax element.
+ * =0 specifies that the time_offset syntax element is not present
+ * @time_offset_length: Length of the time offset
+ *
+ * Defines the HRD parameters
+ */
+struct _GstWFDH264HRDParams
+{
+  guint8 cpb_cnt_minus1;
+  guint8 bit_rate_scale;
+  guint8 cpb_size_scale;
+
+  guint32 bit_rate_value_minus1[32];
+  guint32 cpb_size_value_minus1[32];
+  guint8 cbr_flag[32];
+
+  guint8 initial_cpb_removal_delay_length_minus1;
+  guint8 cpb_removal_delay_length_minus1;
+  guint8 dpb_output_delay_length_minus1;
+  guint8 time_offset_length;
+};
+
+/**
+ * GstWFDH264VUIParams:
+ * @aspect_ratio_info_present_flag: %TRUE specifies that aspect_ratio_idc is present.
+ *  %FALSE specifies that aspect_ratio_idc is not present
+ * @aspect_ratio_idc specifies the value of the sample aspect ratio of the luma samples
+ * @sar_width indicates the horizontal size of the sample aspect ratio
+ * @sar_height indicates the vertical size of the sample aspect ratio
+ * @overscan_info_present_flag: %TRUE overscan_appropriate_flag is present %FALSE otherwize
+ * @overscan_appropriate_flag: %TRUE indicates that the cropped decoded pictures
+ *  output are suitable for display using overscan. %FALSE the cropped decoded pictures
+ *  output contain visually important information
+ * @video_signal_type_present_flag: %TRUE specifies that video_format, video_full_range_flag and
+ *  colour_description_present_flag are present.
+ * @video_format: indicates the representation of the picture
+ * @video_full_range_flag: indicates the black level and range of the luma and chroma signals
+ * @colour_description_present_flag: %TRUE specifies that colour_primaries,
+ *  transfer_characteristics and matrix_coefficients are present
+ * @colour_primaries: indicates the chromaticity coordinates of the source primaries
+ * @transfer_characteristics: indicates the opto-electronic transfer characteristic
+ * @matrix_coefficients: describes the matrix coefficients used in deriving luma and chroma signals
+ * @chroma_loc_info_present_flag: %TRUE specifies that chroma_sample_loc_type_top_field and
+ *  chroma_sample_loc_type_bottom_field are present, %FALSE otherwize
+ * @chroma_sample_loc_type_top_field: specify the location of chroma for top field
+ * @chroma_sample_loc_type_bottom_field specify the location of chroma for bottom field
+ * @timing_info_present_flag: %TRUE specifies that num_units_in_tick,
+ *  time_scale and fixed_frame_rate_flag are present in the bitstream
+ * @num_units_in_tick: is the number of time units of a clock operating at the frequency time_scale Hz
+ * time_scale: is the number of time units that pass in one second
+ * @fixed_frame_rate_flag: %TRUE indicates that the temporal distance between the HRD output times
+ *  of any two consecutive pictures in output order is constrained as specified in the spec, %FALSE
+ *  otherwize.
+ * @nal_hrd_parameters_present_flag: %TRUE if nal hrd parameters present in the bitstream
+ * @vcl_hrd_parameters_present_flag: %TRUE if nal vlc hrd parameters present in the bitstream
+ * @low_delay_hrd_flag: specifies the HRD operational mode
+ * @pic_struct_present_flag: %TRUE specifies that picture timing SEI messages are present or not
+ * @bitstream_restriction_flag: %TRUE specifies that the following coded video sequence bitstream restriction
+ * parameters are present
+ * @motion_vectors_over_pic_boundaries_flag: %FALSE indicates that no sample outside the
+ *  picture boundaries and no sample at a fractional sample position, %TRUE indicates that one or more
+ *  samples outside picture boundaries may be used in inter prediction
+ * @max_bytes_per_pic_denom: indicates a number of bytes not exceeded by the sum of the sizes of
+ *  the VCL NAL units associated with any coded picture in the coded video sequence.
+ * @max_bits_per_mb_denom: indicates the maximum number of coded bits of macroblock_layer
+ * @log2_max_mv_length_horizontal: indicate the maximum absolute value of a decoded horizontal
+ * motion vector component
+ * @log2_max_mv_length_vertical: indicate the maximum absolute value of a decoded vertical
+ *  motion vector component
+ * @num_reorder_frames: indicates the maximum number of frames, complementary field pairs,
+ *  or non-paired fields that precede any frame,
+ * @max_dec_frame_buffering: specifies the required size of the HRD decoded picture buffer in
+ *  units of frame buffers.
+ *
+ * The structure representing the VUI parameters.
+ */
+struct _GstWFDH264VUIParams
+{
+  guint8 aspect_ratio_info_present_flag;
+  guint8 aspect_ratio_idc;
+  /* if aspect_ratio_idc == 255 */
+  guint16 sar_width;
+  guint16 sar_height;
+
+  guint8 overscan_info_present_flag;
+  /* if overscan_info_present_flag */
+  guint8 overscan_appropriate_flag;
+
+  guint8 video_signal_type_present_flag;
+  guint8 video_format;
+  guint8 video_full_range_flag;
+  guint8 colour_description_present_flag;
+  guint8 colour_primaries;
+  guint8 transfer_characteristics;
+  guint8 matrix_coefficients;
+
+  guint8 chroma_loc_info_present_flag;
+  guint8 chroma_sample_loc_type_top_field;
+  guint8 chroma_sample_loc_type_bottom_field;
+
+  guint8 timing_info_present_flag;
+  /* if timing_info_present_flag */
+  guint32 num_units_in_tick;
+  guint32 time_scale;
+  guint8 fixed_frame_rate_flag;
+
+  guint8 nal_hrd_parameters_present_flag;
+  /* if nal_hrd_parameters_present_flag */
+  GstWFDH264HRDParams nal_hrd_parameters;
+
+  guint8 vcl_hrd_parameters_present_flag;
+  /* if vcl_hrd_parameters_present_flag */
+  GstWFDH264HRDParams vcl_hrd_parameters;
+
+  guint8 low_delay_hrd_flag;
+  guint8 pic_struct_present_flag;
+
+  guint8 bitstream_restriction_flag;
+  /*  if bitstream_restriction_flag */
+  guint8 motion_vectors_over_pic_boundaries_flag;
+  guint32 max_bytes_per_pic_denom;
+  guint32 max_bits_per_mb_denom;
+  guint32 log2_max_mv_length_horizontal;
+  guint32 log2_max_mv_length_vertical;
+  guint32 num_reorder_frames;
+  guint32 max_dec_frame_buffering;
+
+  /* calculated values */
+  guint par_n;
+  guint par_d;
+};
+
+/**
+ * GstWFDH264SPS:
+ * @id: The ID of the sequence parameter set
+ * @profile_idc: indicate the profile to which the coded video sequence conforms
+ *
+ * H264 Sequence Parameter Set (SPS)
+ */
+struct _GstWFDH264SPS
+{
+  gint id;
+
+  guint8 profile_idc;
+  guint8 constraint_set0_flag;
+  guint8 constraint_set1_flag;
+  guint8 constraint_set2_flag;
+  guint8 constraint_set3_flag;
+  guint8 level_idc;
+
+  guint8 chroma_format_idc;
+  guint8 separate_colour_plane_flag;
+  guint8 bit_depth_luma_minus8;
+  guint8 bit_depth_chroma_minus8;
+  guint8 qpprime_y_zero_transform_bypass_flag;
+
+  guint8 scaling_matrix_present_flag;
+  guint8 scaling_lists_4x4[6][16];
+  guint8 scaling_lists_8x8[6][64];
+
+  guint8 log2_max_frame_num_minus4;
+  guint8 pic_order_cnt_type;
+
+  /* if pic_order_cnt_type == 0 */
+  guint8 log2_max_pic_order_cnt_lsb_minus4;
+
+  /* else if pic_order_cnt_type == 1 */
+  guint8 delta_pic_order_always_zero_flag;
+  gint32 offset_for_non_ref_pic;
+  gint32 offset_for_top_to_bottom_field;
+  guint8 num_ref_frames_in_pic_order_cnt_cycle;
+  gint32 offset_for_ref_frame[255];
+
+  guint32 num_ref_frames;
+  guint8 gaps_in_frame_num_value_allowed_flag;
+  guint32 pic_width_in_mbs_minus1;
+  guint32 pic_height_in_map_units_minus1;
+  guint8 frame_mbs_only_flag;
+
+  guint8 mb_adaptive_frame_field_flag;
+
+  guint8 direct_8x8_inference_flag;
+
+  guint8 frame_cropping_flag;
+
+  /* if frame_cropping_flag */
+  guint32 frame_crop_left_offset;
+  guint32 frame_crop_right_offset;
+  guint32 frame_crop_top_offset;
+  guint32 frame_crop_bottom_offset;
+
+  guint8 vui_parameters_present_flag;
+  /* if vui_parameters_present_flag */
+  GstWFDH264VUIParams vui_parameters;
+
+  /* calculated values */
+  guint8 chroma_array_type;
+  guint32 max_frame_num;
+  gint width, height;
+  gint crop_rect_width, crop_rect_height;
+  gint crop_rect_x, crop_rect_y;
+  gint fps_num, fps_den;
+  gboolean valid;
+};
+
+/**
+ * GstWFDH264PPS:
+ *
+ * H264 Picture Parameter Set
+ */
+struct _GstWFDH264PPS
+{
+  gint id;
+
+  GstWFDH264SPS *sequence;
+
+  guint8 entropy_coding_mode_flag;
+  guint8 pic_order_present_flag;
+
+  guint32 num_slice_groups_minus1;
+
+  /* if num_slice_groups_minus1 > 0 */
+  guint8 slice_group_map_type;
+  /* and if slice_group_map_type == 0 */
+  guint32 run_length_minus1[8];
+  /* or if slice_group_map_type == 2 */
+  guint32 top_left[8];
+  guint32 bottom_right[8];
+  /* or if slice_group_map_type == (3, 4, 5) */
+  guint8 slice_group_change_direction_flag;
+  guint32 slice_group_change_rate_minus1;
+  /* or if slice_group_map_type == 6 */
+  guint32 pic_size_in_map_units_minus1;
+  guint8 *slice_group_id;
+
+  guint8 num_ref_idx_l0_active_minus1;
+  guint8 num_ref_idx_l1_active_minus1;
+  guint8 weighted_pred_flag;
+  guint8 weighted_bipred_idc;
+  gint8 pic_init_qp_minus26;
+  gint8 pic_init_qs_minus26;
+  gint8 chroma_qp_index_offset;
+  guint8 deblocking_filter_control_present_flag;
+  guint8 constrained_intra_pred_flag;
+  guint8 redundant_pic_cnt_present_flag;
+
+  guint8 transform_8x8_mode_flag;
+
+  guint8 scaling_lists_4x4[6][16];
+  guint8 scaling_lists_8x8[6][64];
+
+  guint8 second_chroma_qp_index_offset;
+
+  gboolean valid;
+};
+
+struct _GstWFDH264RefPicListModification
+{
+  guint8 modification_of_pic_nums_idc;
+  union
+  {
+    /* if modification_of_pic_nums_idc == 0 || 1 */
+    guint32 abs_diff_pic_num_minus1;
+    /* if modification_of_pic_nums_idc == 2 */
+    guint32 long_term_pic_num;
+  } value;
+};
+
+struct _GstWFDH264PredWeightTable
+{
+  guint8 luma_log2_weight_denom;
+  guint8 chroma_log2_weight_denom;
+
+  gint16 luma_weight_l0[32];
+  gint8 luma_offset_l0[32];
+
+  /* if seq->ChromaArrayType != 0 */
+  gint16 chroma_weight_l0[32][2];
+  gint8 chroma_offset_l0[32][2];
+
+  /* if slice->slice_type % 5 == 1 */
+  gint16 luma_weight_l1[32];
+  gint8 luma_offset_l1[32];
+
+  /* and if seq->ChromaArrayType != 0 */
+  gint16 chroma_weight_l1[32][2];
+  gint8 chroma_offset_l1[32][2];
+};
+
+struct _GstWFDH264RefPicMarking
+{
+  guint8 memory_management_control_operation;
+
+  guint32 difference_of_pic_nums_minus1;
+  guint32 long_term_pic_num;
+  guint32 long_term_frame_idx;
+  guint32 max_long_term_frame_idx_plus1;
+};
+
+struct _GstWFDH264DecRefPicMarking
+{
+  /* if slice->nal_unit.IdrPicFlag */
+  guint8 no_output_of_prior_pics_flag;
+  guint8 long_term_reference_flag;
+
+  guint8 adaptive_ref_pic_marking_mode_flag;
+  GstWFDH264RefPicMarking ref_pic_marking[10];
+  guint8 n_ref_pic_marking;
+};
+
+
+struct _GstWFDH264SliceHdr
+{
+  guint32 first_mb_in_slice;
+  guint32 type;
+  GstWFDH264PPS *pps;
+
+  /* if seq->separate_colour_plane_flag */
+  guint8 colour_plane_id;
+
+  guint16 frame_num;
+
+  guint8 field_pic_flag;
+  guint8 bottom_field_flag;
+
+  /* if nal_unit.type == 5 */
+  guint16 idr_pic_id;
+
+  /* if seq->pic_order_cnt_type == 0 */
+  guint16 pic_order_cnt_lsb;
+  /* if seq->pic_order_present_flag && !field_pic_flag */
+  gint32 delta_pic_order_cnt_bottom;
+
+  gint32 delta_pic_order_cnt[2];
+  guint8 redundant_pic_cnt;
+
+  /* if slice_type == B_SLICE */
+  guint8 direct_spatial_mv_pred_flag;
+
+  guint8 num_ref_idx_l0_active_minus1;
+  guint8 num_ref_idx_l1_active_minus1;
+
+  guint8 ref_pic_list_modification_flag_l0;
+  guint8 n_ref_pic_list_modification_l0;
+  GstWFDH264RefPicListModification ref_pic_list_modification_l0[32];
+  guint8 ref_pic_list_modification_flag_l1;
+  guint8 n_ref_pic_list_modification_l1;
+  GstWFDH264RefPicListModification ref_pic_list_modification_l1[32];
+
+  GstWFDH264PredWeightTable pred_weight_table;
+  /* if nal_unit.ref_idc != 0 */
+  GstWFDH264DecRefPicMarking dec_ref_pic_marking;
+
+  guint8 cabac_init_idc;
+  gint8 slice_qp_delta;
+  gint8 slice_qs_delta;
+
+  guint8 disable_deblocking_filter_idc;
+  gint8 slice_alpha_c0_offset_div2;
+  gint8 slice_beta_offset_div2;
+
+  guint16 slice_group_change_cycle;
+
+  /* calculated values */
+  guint32 max_pic_num;
+  gboolean valid;
+
+  /* Size of the slice_header() in bits */
+  guint header_size;
+
+  /* Number of emulation prevention bytes (EPB) in this slice_header() */
+  guint n_emulation_prevention_bytes;
+};
+
+
+struct _GstWFDH264ClockTimestamp
+{
+  guint8 ct_type;
+  guint8 nuit_field_based_flag;
+  guint8 counting_type;
+  guint8 discontinuity_flag;
+  guint8 cnt_dropped_flag;
+  guint8 n_frames;
+
+  guint8 seconds_flag;
+  guint8 seconds_value;
+
+  guint8 minutes_flag;
+  guint8 minutes_value;
+
+  guint8 hours_flag;
+  guint8 hours_value;
+
+  guint32 time_offset;
+};
+
+struct _GstWFDH264PicTiming
+{
+  guint32 cpb_removal_delay;
+  guint32 dpb_output_delay;
+
+  guint8 pic_struct_present_flag;
+  /* if pic_struct_present_flag */
+  guint8 pic_struct;
+
+  guint8 clock_timestamp_flag[3];
+  GstWFDH264ClockTimestamp clock_timestamp[3];
+};
+
+struct _GstWFDH264BufferingPeriod
+{
+  GstWFDH264SPS *sps;
+
+  /* seq->vui_parameters->nal_hrd_parameters_present_flag */
+  guint8 nal_initial_cpb_removal_delay[32];
+  guint8 nal_initial_cpb_removal_delay_offset[32];
+
+  /* seq->vui_parameters->vcl_hrd_parameters_present_flag */
+  guint8 vcl_initial_cpb_removal_delay[32];
+  guint8 vcl_initial_cpb_removal_delay_offset[32];
+};
+
+struct _GstWFDH264RecoveryPoint
+{
+  guint32 recovery_frame_cnt;
+  guint8 exact_match_flag;
+  guint8 broken_link_flag;
+  guint8 changing_slice_group_idc;
+};
+
+struct _GstWFDH264SEIMessage
+{
+  GstWFDH264SEIPayloadType payloadType;
+
+  union {
+    GstWFDH264BufferingPeriod buffering_period;
+    GstWFDH264PicTiming pic_timing;
+    GstWFDH264RecoveryPoint recovery_point;
+    /* ... could implement more */
+  } payload;
+};
+
+/**
+ * GstWFDH264NalParser:
+ *
+ * H264 NAL Parser (opaque structure).
+ */
+struct _GstWFDH264NalParser
+{
+  /*< private >*/
+  GstWFDH264SPS sps[GST_H264_MAX_SPS_COUNT];
+  GstWFDH264PPS pps[GST_H264_MAX_PPS_COUNT];
+  GstWFDH264SPS *last_sps;
+  GstWFDH264PPS *last_pps;
+};
+
+GstWFDH264NalParser *gst_wfd_h264_nal_parser_new             (void);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_identify_nalu     (GstWFDH264NalParser *nalparser,
+                                                       const guint8 *data, guint offset,
+                                                       gsize size, GstWFDH264NalUnit *nalu);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_identify_nalu_unchecked (GstWFDH264NalParser *nalparser,
+                                                       const guint8 *data, guint offset,
+                                                       gsize size, GstWFDH264NalUnit *nalu);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_identify_nalu_avc (GstWFDH264NalParser *nalparser, const guint8 *data,
+                                                       guint offset, gsize size, guint8 nal_length_size,
+                                                       GstWFDH264NalUnit *nalu);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_parse_nal         (GstWFDH264NalParser *nalparser,
+                                                       GstWFDH264NalUnit *nalu);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_parse_slice_hdr   (GstWFDH264NalParser *nalparser, GstWFDH264NalUnit *nalu,
+                                                       GstWFDH264SliceHdr *slice, gboolean parse_pred_weight_table,
+                                                       gboolean parse_dec_ref_pic_marking);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_parse_sps         (GstWFDH264NalParser *nalparser, GstWFDH264NalUnit *nalu,
+                                                       GstWFDH264SPS *sps, gboolean parse_vui_params);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_parse_pps         (GstWFDH264NalParser *nalparser,
+                                                       GstWFDH264NalUnit *nalu, GstWFDH264PPS *pps);
+
+GstWFDH264ParserResult gst_wfd_h264_parser_parse_sei         (GstWFDH264NalParser *nalparser,
+                                                       GstWFDH264NalUnit *nalu, GArray ** messages);
+
+void gst_wfd_h264_nal_parser_free                         (GstWFDH264NalParser *nalparser);
+
+GstWFDH264ParserResult gst_wfd_h264_parse_sps                (GstWFDH264NalUnit *nalu,
+                                                       GstWFDH264SPS *sps, gboolean parse_vui_params);
+
+GstWFDH264ParserResult gst_wfd_h264_parse_pps                (GstWFDH264NalParser *nalparser,
+                                                       GstWFDH264NalUnit *nalu, GstWFDH264PPS *pps);
+
+void                gst_wfd_h264_pps_clear                (GstWFDH264PPS *pps);
+
+void    gst_wfd_h264_quant_matrix_8x8_get_zigzag_from_raster (guint8 out_quant[64],
+                                                          const guint8 quant[64]);
+
+void    gst_wfd_h264_quant_matrix_8x8_get_raster_from_zigzag (guint8 out_quant[64],
+                                                          const guint8 quant[64]);
+
+void    gst_wfd_h264_quant_matrix_4x4_get_zigzag_from_raster (guint8 out_quant[16],
+                                                          const guint8 quant[16]);
+
+void    gst_wfd_h264_quant_matrix_4x4_get_raster_from_zigzag (guint8 out_quant[16],
+                                                          const guint8 quant[16]);
+
+void gst_wfd_h264_video_calculate_framerate (const GstWFDH264SPS * sps, guint field_pic_flag,
+    guint pic_struct, gint * fps_num, gint * fps_den);
+
+G_END_DECLS
+
+#endif
diff --git a/wfdtsdemux/gstwfdts-private.h b/wfdtsdemux/gstwfdts-private.h
new file mode 100755 (executable)
index 0000000..047eb07
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+ * mpegts.h -
+ * Copyright (C) 2013 Edward Hervey
+ *
+ * Authors:
+ *   Edward Hervey <edward@collabora.com>
+ *
+ * This library is free softwagre; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef _GST_WFD_TS_PRIVATE_H_
+#define _GST_WFD_TS_PRIVATE_H_
+
+G_BEGIN_DECLS
+
+GST_DEBUG_CATEGORY_EXTERN (gst_wfd_ts_debug);
+#define GST_CAT_DEFAULT gst_wfd_ts_debug
+
+/*G_GNUC_INTERNAL*/ void __initialize_descriptors (void);
+/*G_GNUC_INTERNAL*/ guint32 _calc_crc32 (const guint8 *data, guint datalen);
+/*G_GNUC_INTERNAL*/ gchar *get_encoding_and_convert (const gchar *text, guint length);
+/*G_GNUC_INTERNAL*/ gchar *convert_lang_code (guint8 * data);
+/*G_GNUC_INTERNAL*/ guint8 *dvb_text_from_utf8 (const gchar * text, gsize *out_size);
+/*G_GNUC_INTERNAL*/ GstWFDTSDescriptor *_new_wfddescriptor (guint8 tag, guint8 length);
+/*G_GNUC_INTERNAL*/ GstWFDTSDescriptor *_new_wfddescriptor_with_extension (guint8 tag,
+    guint8 tag_extension, guint8 length);
+/*G_GNUC_INTERNAL*/ void _packetize_descriptor_array (GPtrArray * array,
+    guint8 ** out_data);
+/*G_GNUC_INTERNAL*/ GstWFDTSSection *_gst_wfd_ts_section_init (guint16 pid, guint8 table_id);
+/*G_GNUC_INTERNAL*/ void _packetize_common_section (GstWFDTSSection * section, gsize length);
+
+typedef gpointer (*GstWFDTSParseFunc) (GstWFDTSSection *section);
+/*G_GNUC_INTERNAL*/ gpointer __common_section_checks (GstWFDTSSection *section,
+                                                 guint minsize,
+                                                 GstWFDTSParseFunc parsefunc,
+                                                 GDestroyNotify destroynotify);
+
+#define __common_desc_check_base(desc, tagtype, retval)                        \
+  if (G_UNLIKELY ((desc)->data == NULL)) {                             \
+    GST_WARNING ("Descriptor is empty (data field == NULL)");          \
+    return retval;                                                     \
+  }                                                                    \
+  if (G_UNLIKELY ((desc)->tag != (tagtype))) {                         \
+    GST_WARNING ("Wrong descriptor type (Got 0x%02x, expected 0x%02x)",        \
+                (desc)->tag, tagtype);                                 \
+    return retval;                                                     \
+  }                                                                    \
+
+#define __common_desc_checks(desc, tagtype, minlen, retval)            \
+  __common_desc_check_base(desc, tagtype, retval);                     \
+  if (G_UNLIKELY ((desc)->length < (minlen))) {                                \
+    GST_WARNING ("Descriptor too small (Got %d, expected at least %d)",        \
+                (desc)->length, minlen);                               \
+    return retval;                                                     \
+  }
+#define __common_desc_checks_exact(desc, tagtype, len, retval)         \
+  __common_desc_check_base(desc, tagtype, retval);                     \
+  if (G_UNLIKELY ((desc)->length != (len))) {                          \
+    GST_WARNING ("Wrong descriptor size (Got %d, expected %d)",                \
+                (desc)->length, len);                                  \
+    return retval;                                                     \
+  }
+
+#define __common_desc_ext_check_base(desc, tagexttype, retval)          \
+  if (G_UNLIKELY ((desc)->data == NULL)) {                              \
+    GST_WARNING ("Descriptor is empty (data field == NULL)");           \
+    return retval;                                                      \
+  }                                                                     \
+  if (G_UNLIKELY ((desc)->tag != 0x7f) ||                               \
+    ((desc)->tag_extension != (tagexttype))) {                          \
+    GST_WARNING ("Wrong descriptor type (Got 0x%02x, expected 0x%02x)", \
+                 (desc)->tag_extension, tagexttype);                    \
+    return retval;                                                      \
+  }
+#define __common_desc_ext_checks(desc, tagexttype, minlen, retval)      \
+  __common_desc_ext_check_base(desc, tagexttype, retval);                    \
+  if (G_UNLIKELY ((desc)->length < (minlen))) {                         \
+    GST_WARNING ("Descriptor too small (Got %d, expected at least %d)", \
+                 (desc)->length, minlen);                               \
+    return retval;                                                      \
+  }
+#define __common_desc_ext_checks_exact(desc, tagexttype, len, retval)   \
+  __common_desc_ext_check_base(desc, tagexttype, retval);               \
+  if (G_UNLIKELY ((desc)->length != (len))) {                           \
+     GST_WARNING ("Wrong descriptor size (Got %d, expected %d)",        \
+                  (desc)->length, len);                                 \
+     return retval;                                                     \
+  }
+
+G_END_DECLS
+
+#endif /* _GST_WFD_TS_PRIVATE_H_ */
diff --git a/wfdtsdemux/gstwfdtsdefs.h b/wfdtsdemux/gstwfdtsdefs.h
new file mode 100755 (executable)
index 0000000..00c2258
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Fluendo MPEG Demuxer plugin.
+ *
+ * The Initial Developer of the Original Code is Fluendo, S.L.
+ * Portions created by Fluendo, S.L. are Copyright (C) 2005
+ * Fluendo, S.L. All Rights Reserved.
+ *
+ * Contributor(s): Wim Taymans <wim@fluendo.com>
+ */
+
+#ifndef __GST_WFD_DEFS_H__
+#define __GST_WFD_DEFS_H__
+#include <glib/gprintf.h>
+
+#define SAFE_FOURCC_FORMAT "02x%02x%02x%02x (%c%c%c%c)"
+#define SAFE_CHAR(a) (g_ascii_isalnum((gchar) (a)) ? ((gchar)(a)) : '.')
+#define SAFE_FOURCC_ARGS(a)                            \
+  ((guint8) ((a)>>24)),                                        \
+    ((guint8) ((a) >> 16 & 0xff)),                     \
+    ((guint8) a >> 8 & 0xff),                          \
+    ((guint8) a & 0xff),                               \
+    SAFE_CHAR((a)>>24),                                        \
+    SAFE_CHAR((a) >> 16 & 0xff),                       \
+    SAFE_CHAR((a) >> 8 & 0xff),                                \
+    SAFE_CHAR(a & 0xff)
+
+/* Stream type assignments */
+/* FIXME: Put these in mpegts lib separate stream type enums */
+/* Un-official Dirac extension */
+#define ST_VIDEO_DIRAC                  0xd1
+
+/* private stream types */
+#define ST_PS_VIDEO_MPEG2_DCII          0x80
+#define ST_PS_AUDIO_AC3                 0x81
+#define ST_PS_AUDIO_DTS                 0x8a
+#define ST_PS_AUDIO_LPCM                0x8b
+#define ST_PS_DVD_SUBPICTURE            0xff
+#ifdef WFD_SPEC
+#define ST_PS_WFD_AUDIO_LPCM            0x83
+#endif
+
+/* Blu-ray related (registration: 'HDMV'*/
+#define ST_BD_AUDIO_LPCM                0x80
+#define ST_BD_AUDIO_AC3                 0x81
+#define ST_BD_AUDIO_DTS                 0x82
+#define ST_BD_AUDIO_AC3_TRUE_HD         0x83
+#define ST_BD_AUDIO_AC3_PLUS            0x84
+#define ST_BD_AUDIO_DTS_HD              0x85
+#define ST_BD_AUDIO_DTS_HD_MASTER_AUDIO 0x86
+#define ST_BD_AUDIO_EAC3                0x87
+#define ST_BD_PGS_SUBPICTURE            0x90
+#define ST_BD_IGS                       0x91
+#define ST_BD_SUBTITLE                  0x92
+#define ST_BD_SECONDARY_AC3_PLUS        0xa1
+#define ST_BD_SECONDARY_DTS_HD          0xa2
+
+/* defined for VC1 extension in RP227 */
+#define ST_PRIVATE_EA                   0xea
+
+/* Following only apply for streams identified as HDV,
+ * According to specification 61834-11 the PMT will use
+ * a registration descriptor with values TSMV or TSHV */
+/* HDV AUX stream mapping
+ * 0xA0      ISO/IEC 61834-11
+ * 0xA1      ISO/IEC 61834-11
+ */
+#define ST_HDV_AUX_A                    0xa0
+#define ST_HDV_AUX_V                    0xa1
+
+#define CLOCK_BASE 9LL
+#define CLOCK_FREQ (CLOCK_BASE * 10000)
+
+/* Numerical values for second/millisecond in PCR units */
+#define PCR_SECOND 27000000
+#define PCR_MSECOND 27000
+
+/* PCR_TO_GST calculation requires at least 10 extra bits.
+ * Since maximum PCR value is coded with 42 bits, we are
+ * safe to use direct calculation (10+42 < 63)*/
+#define PCRTIME_TO_GSTTIME(t) (((t) * (guint64)1000) / 27)
+
+/* MPEG_TO_GST calculation requires at least 17 extra bits (100000)
+ * Since maximum PTS/DTS value is coded with 33bits, we are
+ * safe to use direct calculation (17+33 < 63) */
+#define MPEGTIME_TO_GSTTIME(t) ((t) * (guint64)100000 / 9)
+
+#define GSTTIME_TO_MPEGTIME(time) (gst_util_uint64_scale ((time), \
+            CLOCK_BASE, GST_MSECOND/10))
+#define GSTTIME_TO_PCRTIME(time) (gst_util_uint64_scale ((time), \
+            300 * CLOCK_BASE, GST_MSECOND/10))
+
+#define MPEG_MUX_RATE_MULT      50
+
+/* sync:4 == 00xx ! pts:3 ! 1 ! pts:15 ! 1 | pts:15 ! 1 */
+#define READ_TS(data, target, lost_sync_label)          \
+    if ((*data & 0x01) != 0x01) goto lost_sync_label;   \
+    target  = ((guint64) (*data++ & 0x0E)) << 29;       \
+    target |= ((guint64) (*data++       )) << 22;       \
+    if ((*data & 0x01) != 0x01) goto lost_sync_label;   \
+    target |= ((guint64) (*data++ & 0xFE)) << 14;       \
+    target |= ((guint64) (*data++       )) << 7;        \
+    if ((*data & 0x01) != 0x01) goto lost_sync_label;   \
+    target |= ((guint64) (*data++ & 0xFE)) >> 1;
+
+#endif /* __GST_WFD_DEFS_H__ */
diff --git a/wfdtsdemux/gstwfdtsdemux.c b/wfdtsdemux/gstwfdtsdemux.c
new file mode 100755 (executable)
index 0000000..5f8dd24
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "gstwfdtsdescriptor.h"
+#include "gstwfdtssection.h"
+#include "wfdtsbase.h"
+#include "wfdtspacketizer.h"
+#include "wfdtsparse.h"
+#include "wfdtsdemux.h"
+
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+  gst_wfd_ts_initialize ();
+  if (!gst_wfdtsbase_plugin_init (plugin))
+    return FALSE;
+  if (!gst_wfdtsparse_plugin_init (plugin))
+    return FALSE;
+  if (!gst_wfd_ts_demux_plugin_init (plugin))
+    return FALSE;
+  return TRUE;
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+    GST_VERSION_MINOR,
+    wfdtsdemux,
+    "Wi-Fi Display TS demuxer",
+    plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
diff --git a/wfdtsdemux/gstwfdtsdesc.h b/wfdtsdemux/gstwfdtsdesc.h
new file mode 100644 (file)
index 0000000..623f98a
--- /dev/null
@@ -0,0 +1,235 @@
+/*
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Fluendo MPEG Demuxer plugin.
+ *
+ * The Initial Developer of the Original Code is Fluendo, S.L.
+ * Portions created by Fluendo, S.L. are Copyright (C) 2005
+ * Fluendo, S.L. All Rights Reserved.
+ *
+ * Contributor(s): Wim Taymans <wim@fluendo.com>
+ *
+ */
+
+#ifndef __GST_WFD_TS_DESC_H__
+#define __GST_WFD_TS_DESC_H__
+
+#include <glib.h>
+
+
+/* Others */
+
+
+/* 0xFF is forbidden */
+
+/* common for all descriptors */
+#define DESC_TAG(desc)                 (desc[0])
+#define DESC_LENGTH(desc)      (desc[1])
+
+/* video_stream_descriptor */
+#define DESC_VIDEO_STREAM_multiple_framerate_flag(desc)        (((desc)[2] & 0x80) == 0x80)
+#define DESC_VIDEO_STREAM_frame_rate_code(desc)                (((desc)[2] & 0x38) >> 3)
+#define DESC_VIDEO_STREAM_MPEG_1_only_flag(desc)               (((desc)[2] & 0x04) == 0x04)
+#define DESC_VIDEO_STREAM_constrained_parameter_flag(desc)     (((desc)[2] & 0x02) == 0x02)
+#define DESC_VIDEO_STREAM_still_picture_flag(desc)             (((desc)[2] & 0x01) == 0x01)
+/* if (MPEG_1_only_flag == 1) */
+#define DESC_VIDEO_STREAM_profile_and_level_indication(desc)   ((desc)[3])
+#define DESC_VIDEO_STREAM_chroma_format(desc)                  (((desc)[4] & 0xc0) >> 6)
+#define DESC_VIDEO_STREAM_frame_rate_extension_flag(desc)      (((desc)[4] & 0x20) == 0x20)
+
+/* audio_stream_descriptor */
+#define DESC_AUDIO_STREAM_free_format_flag(desc)               (((desc)[2] & 0x80) == 0x80)
+#define DESC_AUDIO_STREAM_ID(desc)                             (((desc)[2] & 0x40) == 0x40)
+#define DESC_AUDIO_STREAM_layer(desc)                          (((desc)[2] & 0x30) >> 4)
+#define DESC_AUDIO_STREAM_variable_rate_audio_indicator(desc)  (((desc)[2] & 0x08) == 0x08)
+
+/* hierarchy_descriptor */
+#define DESC_HIERARCHY_hierarchy_type(desc)                    (((desc)[2] & 0x0f))
+#define DESC_HIERARCHY_hierarchy_layer_index(desc)             (((desc)[3] & 0x3f))
+#define DESC_HIERARCHY_hierarchy_embedded_layer_index(desc)    (((desc)[4] & 0x3f))
+#define DESC_HIERARCHY_hierarchy_channel(desc)                 (((desc)[5] & 0x3f))
+
+/* registration_descriptor */
+#define DESC_REGISTRATION_format_identifier(desc)              (GST_READ_UINT32_BE ((desc)+2))
+#define DESC_REGISTRATION_additional_ident_info_len(desc)      ((desc)[1] - 4)
+#define DESC_REGISTRATION_additional_ident_info(desc)          (&(desc)[6])
+
+/* data_stream_alignment_descriptor */
+#define DESC_DATA_STREAM_ALIGNMENT_alignment_type(desc)                ((desc)[2])
+
+/* target_background_grid_descriptor */
+#define DESC_TARGET_BACKGROUND_GRID_horizontal_size(desc)      (GST_READ_UINT16_BE ((desc)+2) >> 2)
+#define DESC_TARGET_BACKGROUND_GRID_vertical_size(desc)                ((GST_READ_UINT32_BE ((desc)+2) & 0x0003fff0) >> 4)
+#define DESC_TARGET_BACKGROUND_GRID_aspect_ratio_information(desc) ((desc)[5] & 0x0f)
+
+/* video_window_descriptor */
+#define DESC_VIDEO_WINDOW_horizontal_offset(desc)              (GST_READ_UINT16_BE ((desc)+2) >> 2)
+#define DESC_VIDEO_WINDOW_vertical_offset(desc)                        ((GST_READ_UINT32_BE ((desc)+2) & 0x0003fff0) >> 4)
+#define DESC_VIDEO_WINDOW_window_priority(desc)                        ((desc)[5] & 0x0f)
+
+/* CA_descriptor */
+#define DESC_CA_system_ID(desc)                                        (GST_READ_UINT16_BE ((desc)+2))
+#define DESC_CA_PID(desc)                                      (GST_READ_UINT16_BE ((desc)+2) & 0x1fff)
+
+/* ISO_639_language_descriptor */
+#define DESC_ISO_639_LANGUAGE_codes_n(desc)                    ((desc[1]) >> 2)
+#define DESC_ISO_639_LANGUAGE_language_code_nth(desc,i)                (&(desc[2 + (4*i)]))
+#define DESC_ISO_639_LANGUAGE_audio_type_nth(desc,i)           ((desc)[5 + (4*i)])
+
+/* system_clock_descriptor */
+#define DESC_SYSTEM_CLOCK_external_clock_reference_indicator(desc) (((desc)[2] & 0x80) == 0x80)
+#define DESC_SYSTEM_CLOCK_clock_accuracy_integer(desc)         ((desc)[2] & 0x3f)
+#define DESC_SYSTEM_CLOCK_clock_accuracy_exponent(desc)                (((desc)[3] & 0xe0) >> 5)
+
+/* multiplex_buffer_utilization_descriptor */
+#define DESC_MULTIPLEX_BUFFER_UTILISATION_bound_valid_flag(desc)       (((desc)[2] & 0x80) == 0x80)
+#define DESC_MULTIPLEX_BUFFER_UTILISATION_LTW_offset_lower_bound(desc) (GST_READ_UINT16_BE ((desc)+2) & 0x7fff)
+#define DESC_MULTIPLEX_BUFFER_UTILISATION_LTW_offset_upper_bound(desc) (GST_READ_UINT16_BE ((desc)+4) & 0x7fff)
+
+/* copyright_descriptor */
+#define DESC_COPYRIGHT_copyright_identifier(desc)              (GST_READ_UINT32_BE ((desc)+2))
+#define DESC_COPYRIGHT_additional_copyright_info_len(desc)     ((desc)[1] - 4)
+#define DESC_COPYRIGHT_additional_copyright_info(desc)         (&(desc)[6])
+
+/* maximum_bitrate_descriptor */
+#define DESC_MAXIMUM_BITRAT_maximum_bitrate(desc)              (((((guint32)desc[2]) & 0x3f) << 16) | \
+                                                                GST_READ_UINT16_BE ((desc)+3))
+
+/* private_data_indicator_descriptor */
+#define DESC_PRIVATE_DATA_INDICATOR_indicator(desc)            (GST_READ_UINT32_BE(&desc[2]))
+
+/* smoothing_buffer_descriptor */
+#define DESC_SMOOTHING_BUFFER_sb_leak_rate(desc)               (((((guint32)desc[2]) & 0x3f) << 16) | \
+                                                                 GST_READ_UINT16_BE ((desc)+3))
+#define DESC_SMOOTHING_BUFFER_sb_size(desc)                    (((((guint32)desc[5]) & 0x3f) << 16) | \
+                                                                 GST_READ_UINT16_BE ((desc)+6))
+/* STD_descriptor */
+#define DESC_STD_leak_valid_flag(desc)                         (((desc)[2] & 0x01) == 0x01)
+
+/* ibp_descriptor */
+#define DESC_IBP_closed_gop_flag(desc)                         (((desc)[2] & 0x80) == 0x80)
+#define DESC_IBP_identical_gop_flag(desc)                      (((desc)[2] & 0x40) == 0x40)
+#define DESC_IBP_max_gop_length(desc)                          (GST_READ_UINT16_BE ((desc)+6) & 0x3fff)
+
+/* time_code descriptor */
+#define DESC_TIMECODE_video_pid(desc)                           (GST_READ_UINT16_BE ((desc) + 2) & 0x1fff)
+
+/* Stream identifier descriptor */
+#define DESC_DVB_STREAM_IDENTIFIER_component_tag(desc)  (desc[2])
+
+/* DVB Network Name descriptor */
+#define DESC_DVB_NETWORK_NAME_length(desc)  (GST_READ_UINT8((desc)+1))
+#define DESC_DVB_NETWORK_NAME_text(desc)    (desc+2)
+
+/* DVB Service Descriptor */
+#define DESC_DVB_SERVICE_type(desc) (desc[2])
+#define DESC_DVB_SERVICE_provider_name_length(desc) (desc[3])
+#define DESC_DVB_SERVICE_provider_name_text(desc)   (desc+4)
+#define DESC_DVB_SERVICE_name_length(desc)  (desc[4 + DESC_DVB_SERVICE_provider_name_length(desc)])
+#define DESC_DVB_SERVICE_name_text(desc)    (desc + 5 + DESC_DVB_SERVICE_provider_name_length(desc))
+
+/* DVB Component Descriptor */
+#define DESC_DVB_COMPONENT_stream_content(desc) (desc[2] & 0x0F)
+#define DESC_DVB_COMPONENT_type(desc)   (desc[3])
+#define DESC_DVB_COMPONENT_tag(desc)    (desc[4])
+#define DESC_DVB_COMPONENT_language(desc)   (desc + 5)
+
+/* DVB Bouquet Name Descriptor */
+#define DESC_DVB_BOUQUET_NAME_text(desc)    (desc + 2)
+
+/* DVB Short Event Descriptor */
+#define DESC_DVB_SHORT_EVENT_name_text(desc)   (desc + 6)
+#define DESC_DVB_SHORT_EVENT_name_length(desc) (desc[5])
+#define DESC_DVB_SHORT_EVENT_description_text(desc) (desc + 6 + DESC_DVB_SHORT_EVENT_name_length(desc) + 1)
+#define DESC_DVB_SHORT_EVENT_description_length(desc)  (desc[6 + DESC_DVB_SHORT_EVENT_name_length(desc)])
+
+/* DVB Extended Event Descriptor */
+#define DESC_DVB_EXTENDED_EVENT_descriptor_number(desc) ((desc[2] & 0xF0) >> 4)
+#define DESC_DVB_EXTENDED_EVENT_last_descriptor_number(desc) (desc[2] & 0x0F)
+#define DESC_DVB_EXTENDED_EVENT_iso639_language_code(desc) (desc + 3)
+#define DESC_DVB_EXTENDED_EVENT_items_length(desc) (desc[6])
+#define DESC_DVB_EXTENDED_EVENT_items(desc) (desc + 7)
+#define DESC_DVB_EXTENDED_EVENT_text_length(desc) (desc[7 + DESC_DVB_EXTENDED_EVENT_items_length(desc)])
+#define DESC_DVB_EXTENDED_EVENT_text(desc) (desc + 7 + DESC_DVB_EXTENDED_EVENT_items_length(desc) + 1)
+
+/* DVB Satellite Delivery System Descriptor */
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_frequency(desc)     (desc + 2)
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_orbital_position(desc)      (desc + 6)
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_west_east_flag(desc)        ((desc[8] & 0x80) == 0x80)
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_polarization(desc)  ((desc[8] >> 5) & 0x3)
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_modulation(desc)    (desc[8] & 0x3)
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_symbol_rate(desc)   (desc + 9)
+#define DESC_DVB_SATELLITE_DELIVERY_SYSTEM_fec_inner(desc)     (desc[12] & 0x0F)
+
+/* DVB Terrestrial Delivery System Descriptor */
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_frequency(desc)   (GST_READ_UINT32_BE((desc) + 2))
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_bandwidth(desc)   ((desc[6] >> 5) & 0x7)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_constellation(desc)       ((desc[7] >> 6) & 0x3)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_hierarchy(desc)   ((desc[7] >> 3) & 0x7)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_code_rate_hp(desc)        (desc[7] & 0x7)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_code_rate_lp(desc)        ((desc[8] >> 5) & 0x7)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_guard_interval(desc)      ((desc[8] >> 3) & 0x3)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_transmission_mode(desc)   ((desc[8] >> 1) & 0x3)
+#define DESC_DVB_TERRESTRIAL_DELIVERY_SYSTEM_other_frequency(desc)     ((desc[8] & 0x01) == 0x01)
+
+/* DVB Cable Delivery System Descriptor */
+#define DESC_DVB_CABLE_DELIVERY_SYSTEM_frequency(desc)         (desc + 2)
+#define DESC_DVB_CABLE_DELIVERY_SYSTEM_fec_outer(desc)         (desc[7] & 0x0F)
+#define DESC_DVB_CABLE_DELIVERY_SYSTEM_modulation(desc)                (desc[8])
+#define DESC_DVB_CABLE_DELIVERY_SYSTEM_symbol_rate(desc)       (desc + 9)
+#define DESC_DVB_CABLE_DELIVERY_SYSTEM_fec_inner(desc)         (desc[12] & 0x0F)
+
+/* DVB Data Broadcast Descriptor */
+#define DESC_DVB_DATA_BROADCAST_data_broadcast_id(desc)                (GST_READ_UINT16_BE((desc) + 2))
+#define DESC_DVB_DATA_BROADCAST_component_tag(desc)            (desc[4])
+#define DESC_DVB_DATA_BROADCAST_selector_length(desc)          (desc[5])
+#define DESC_DVB_DATA_BROADCAST_selector(desc)                 (desc + 6)
+#define DESC_DVB_DATA_BROADCAST_iso639_language_code(desc)     (desc + 6 + DESC_DVB_DATA_BROADCAST_selector_length(desc))
+#define DESC_DVB_DATA_BROADCAST_text_length(desc)              (desc + 9 + DESC_DVB_DATA_BROADCAST_selector_length(desc))
+#define DESC_DVB_DATA_BROADCAST_text(desc)                     (desc + 10 + DESC_DVB_DATA_BROADCAST_selector_length(desc))
+
+/* DVB Data Broadcast Id Descriptor */
+#define DESC_DVB_DATA_BROADCAST_ID_data_broadcast_id(desc)     (GST_READ_UINT16_BE((desc) + 2))
+#define DESC_DVB_DATA_BROADCAST_ID_id_selector_byte(desc)      (desc + 4)
+
+/* DVB Carousel Identifier Descriptor */
+#define DESC_DVB_CAROUSEL_IDENTIFIER_carousel_id(desc)         (GST_READ_UINT32_BE((desc) + 2))
+
+/* AC3_audio_stream_descriptor */
+#define DESC_AC_AUDIO_STREAM_bsid(desc)             ((desc)[2] & 0x1f)
+
+/* FIXME : Move list of well know registration ids to an enum
+ * in the mpegts library.
+ *
+ * See http://www.smpte-ra.org/mpegreg/mpegreg.html for a full list
+ * */
+
+/* registration_descriptor format IDs */
+#define DRF_ID_HDMV       0x48444d56
+#define DRF_ID_VC1        0x56432D31   /* defined in RP227 */
+#define DRF_ID_DTS1       0x44545331
+#define DRF_ID_DTS2       0x44545332
+#define DRF_ID_DTS3       0x44545333
+#define DRF_ID_S302M      0x42535344
+#define DRF_ID_TSHV       0x54534856
+#define DRF_ID_AC3        0x41432d33
+#define DRF_ID_GA94       0x47413934
+#define DRF_ID_CUEI       0x43554549
+#define DRF_ID_ETV1       0x45545631
+#define DRF_ID_HEVC       0x48455643
+
+#endif /* __GST_WFD_TS_DESC_H__ */
diff --git a/wfdtsdemux/gstwfdtsdescriptor.c b/wfdtsdemux/gstwfdtsdescriptor.c
new file mode 100755 (executable)
index 0000000..dc62b25
--- /dev/null
@@ -0,0 +1,1113 @@
+/*
+ * gstwfdtsdescriptor.c -
+ * Copyright (C) 2013 Edward Hervey
+ *
+ * Authors:
+ *   Edward Hervey <edward@collabora.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#include <stdlib.h>
+#include <string.h>
+
+#include "gstwfdtsdescriptor.h"
+#include "gstwfdtssection.h"
+#include "gstwfdts-private.h"
+
+/**
+ * SECTION:gstwfdtsdescriptor
+ * @title: Base MPEG-TS descriptors
+ * @short_description: Descriptors for ITU H.222.0 | ISO/IEC 13818-1
+ * @include: gst/mpegts/mpegts.h
+ *
+ * These are the base descriptor types and methods.
+ *
+ * For more details, refer to the ITU H.222.0 or ISO/IEC 13818-1 specifications
+ * and other specifications mentionned in the documentation.
+ */
+
+/* FIXME : Move this to proper file once we have a C file for ATSC/ISDB descriptors */
+/**
+ * SECTION:gst-atsc-descriptor
+ * @title: ATSC variants of MPEG-TS descriptors
+ * @short_description: Descriptors for the various ATSC specifications
+ * @include: gst/mpegts/mpegts.h
+ *
+ */
+
+/**
+ * SECTION:gst-isdb-descriptor
+ * @title: ISDB variants of MPEG-TS descriptors
+ * @short_description: Descriptors for the various ISDB specifications
+ * @include: gst/mpegts/mpegts.h
+ *
+ */
+
+
+/*
+ * TODO
+ *
+ * * Add common validation code for data presence and minimum/maximum expected
+ *   size.
+ * * Add parsing methods for the following descriptors that were previously 
+ *   handled in mpegtsbase:
+ *   * GST_MTS_DESC_DVB_DATA_BROADCAST_ID
+ *   * GST_MTS_DESC_DVB_CAROUSEL_IDENTIFIER
+ *   * GST_MTS_DESC_DVB_FREQUENCY_LIST
+ */
+
+#define MAX_KNOWN_ICONV 25
+
+/* First column is the original encoding,
+ * second column is the target encoding */
+
+static GIConv __iconvs[MAX_KNOWN_ICONV][MAX_KNOWN_ICONV];
+
+/* All these conversions will be to UTF8 */
+typedef enum
+{
+  _ICONV_UNKNOWN = -1,
+  _ICONV_ISO8859_1,
+  _ICONV_ISO8859_2,
+  _ICONV_ISO8859_3,
+  _ICONV_ISO8859_4,
+  _ICONV_ISO8859_5,
+  _ICONV_ISO8859_6,
+  _ICONV_ISO8859_7,
+  _ICONV_ISO8859_8,
+  _ICONV_ISO8859_9,
+  _ICONV_ISO8859_10,
+  _ICONV_ISO8859_11,
+  _ICONV_ISO8859_12,
+  _ICONV_ISO8859_13,
+  _ICONV_ISO8859_14,
+  _ICONV_ISO8859_15,
+  _ICONV_UCS_2BE,
+  _ICONV_EUC_KR,
+  _ICONV_GB2312,
+  _ICONV_UTF_16BE,
+  _ICONV_ISO10646_UTF8,
+  _ICONV_ISO6937,
+  _ICONV_UTF8,
+  /* Insert more here if needed */
+  _ICONV_MAX
+} LocalIconvCode;
+
+static const gchar *iconvtablename[] = {
+  "iso-8859-1",
+  "iso-8859-2",
+  "iso-8859-3",
+  "iso-8859-4",
+  "iso-8859-5",
+  "iso-8859-6",
+  "iso-8859-7",
+  "iso-8859-8",
+  "iso-8859-9",
+  "iso-8859-10",
+  "iso-8859-11",
+  "iso-8859-12",
+  "iso-8859-13",
+  "iso-8859-14",
+  "iso-8859-15",
+  "UCS-2BE",
+  "EUC-KR",
+  "GB2312",
+  "UTF-16BE",
+  "ISO-10646/UTF8",
+  "iso6937",
+  "utf-8"
+      /* Insert more here if needed */
+};
+
+void
+__initialize_descriptors (void)
+{
+  guint i, j;
+
+  /* Initialize converters */
+  /* FIXME : How/when should we close them ??? */
+  for (i = 0; i < MAX_KNOWN_ICONV; i++) {
+    for (j = 0; j < MAX_KNOWN_ICONV; j++)
+      __iconvs[i][j] = ((GIConv) - 1);
+  }
+}
+
+/*
+ * @text: The text you want to get the encoding from
+ * @start_text: Location where the beginning of the actual text is stored
+ * @is_multibyte: Location where information whether it's a multibyte encoding
+ * or not is stored
+ * @returns: GIconv for conversion or NULL
+ */
+static LocalIconvCode
+get_encoding (const gchar * text, guint * start_text, gboolean * is_multibyte)
+{
+  LocalIconvCode encoding;
+  guint8 firstbyte;
+
+  *is_multibyte = FALSE;
+  *start_text = 0;
+
+  firstbyte = (guint8) text[0];
+
+  /* A wrong value */
+  g_return_val_if_fail (firstbyte != 0x00, _ICONV_UNKNOWN);
+
+  if (firstbyte <= 0x0B) {
+    /* 0x01 => iso 8859-5 */
+    encoding = firstbyte + _ICONV_ISO8859_4;
+    *start_text = 1;
+    goto beach;
+  }
+
+  /* ETSI EN 300 468, "Selection of character table" */
+  switch (firstbyte) {
+    case 0x0C:
+    case 0x0D:
+    case 0x0E:
+    case 0x0F:
+      /* RESERVED */
+      encoding = _ICONV_UNKNOWN;
+      break;
+    case 0x10:
+    {
+      guint16 table;
+
+      table = GST_READ_UINT16_BE (text + 1);
+
+      if (table < 17)
+        encoding = _ICONV_UNKNOWN + table;
+      else
+        encoding = _ICONV_UNKNOWN;;
+      *start_text = 3;
+      break;
+    }
+    case 0x11:
+      encoding = _ICONV_UCS_2BE;
+      *start_text = 1;
+      *is_multibyte = TRUE;
+      break;
+    case 0x12:
+      /*  EUC-KR implements KSX1001 */
+      encoding = _ICONV_EUC_KR;
+      *start_text = 1;
+      *is_multibyte = TRUE;
+      break;
+    case 0x13:
+      encoding = _ICONV_GB2312;
+      *start_text = 1;
+      break;
+    case 0x14:
+      encoding = _ICONV_UTF_16BE;
+      *start_text = 1;
+      *is_multibyte = TRUE;
+      break;
+    case 0x15:
+      /* TODO : Where does this come from ?? */
+      encoding = _ICONV_ISO10646_UTF8;
+      *start_text = 1;
+      break;
+    case 0x16:
+    case 0x17:
+    case 0x18:
+    case 0x19:
+    case 0x1A:
+    case 0x1B:
+    case 0x1C:
+    case 0x1D:
+    case 0x1E:
+    case 0x1F:
+      /* RESERVED */
+      encoding = _ICONV_UNKNOWN;
+      break;
+    default:
+      encoding = _ICONV_ISO6937;
+      break;
+  }
+
+beach:
+  GST_DEBUG
+      ("Found encoding %d, first byte is 0x%02x, start_text: %u, is_multibyte: %d",
+      encoding, firstbyte, *start_text, *is_multibyte);
+
+  return encoding;
+}
+
+static GIConv
+_get_iconv (LocalIconvCode from, LocalIconvCode to)
+{
+  if (__iconvs[from][to] == (GIConv) - 1)
+    __iconvs[from][to] = g_iconv_open (iconvtablename[to],
+        iconvtablename[from]);
+  return __iconvs[from][to];
+}
+
+static void
+_encode_control_codes (gchar * text, gsize length, gboolean is_multibyte)
+{
+  gsize pos = 0;
+
+  while (pos < length) {
+    if (is_multibyte) {
+      guint16 code = GST_READ_UINT16_BE (text + pos);
+      if (code == 0x000A) {
+        text[pos] = 0xE0;
+        text[pos + 1] = 0x8A;
+      }
+      pos += 2;
+    } else {
+      guint8 code = text[pos];
+      if (code == 0x0A)
+        text[pos] = 0x8A;
+      pos++;
+    }
+  }
+}
+
+/**
+ * dvb_text_from_utf8:
+ * @text: The text to convert. This should be in UTF-8 format
+ * @out_size: (out): the byte length of the new text
+ *
+ * Converts UTF-8 strings to text characters compliant with EN 300 468.
+ * The converted text can be used directly in DVB #GstWFDTSDescriptor
+ *
+ * The function will try different character maps until the string is
+ * completely converted.
+ *
+ * The function tries the default ISO 6937 character map first.
+ *
+ * If no character map that contains all characters could be found, the
+ * string is converted to ISO 6937 with unknown characters set to `?`.
+ *
+ * Returns: (transfer full): byte array of size @out_size
+ */
+guint8 *
+dvb_text_from_utf8 (const gchar * text, gsize * out_size)
+{
+  GError *error = NULL;
+  gchar *out_text;
+  guint8 *out_buffer;
+  guint encoding;
+  GIConv giconv = (GIConv) - 1;
+
+  /* We test character maps one-by-one. Start with the default */
+  encoding = _ICONV_ISO6937;
+  giconv = _get_iconv (_ICONV_UTF8, encoding);
+  out_text = g_convert_with_iconv (text, -1, giconv, NULL, out_size, &error);
+
+  if (out_text) {
+    GST_DEBUG ("Using default ISO6937 encoding");
+    goto out;
+  }
+
+  g_clear_error (&error);
+
+  for (encoding = _ICONV_ISO8859_1; encoding <= _ICONV_ISO10646_UTF8;
+      encoding++) {
+    giconv = _get_iconv (_ICONV_UTF8, encoding);
+    if (giconv == (GIConv) - 1)
+      continue;
+    out_text = g_convert_with_iconv (text, -1, giconv, NULL, out_size, &error);
+
+    if (out_text) {
+      GST_DEBUG ("Found suitable character map - %s", iconvtablename[encoding]);
+      goto out;
+    }
+
+    g_clear_error (&error);
+  }
+
+  out_text = g_convert_with_fallback (text, -1, iconvtablename[_ICONV_ISO6937],
+      iconvtablename[_ICONV_UTF8], "?", NULL, out_size, &error);
+
+out:
+
+  if (error) {
+    GST_WARNING ("Could not convert from utf-8: %s", error->message);
+    g_error_free (error);
+    g_free (out_text);
+    return NULL;
+  }
+
+  switch (encoding) {
+    case _ICONV_ISO6937:
+      /* Default encoding contains no selection bytes. */
+      _encode_control_codes (out_text, *out_size, FALSE);
+      return (guint8 *) out_text;
+    case _ICONV_ISO8859_1:
+    case _ICONV_ISO8859_2:
+    case _ICONV_ISO8859_3:
+    case _ICONV_ISO8859_4:
+      /* These character sets requires 3 selection bytes */
+      _encode_control_codes (out_text, *out_size, FALSE);
+      out_buffer = g_malloc (*out_size + 3);
+      out_buffer[0] = 0x10;
+      out_buffer[1] = 0x00;
+      out_buffer[2] = encoding - _ICONV_ISO8859_1 + 1;
+      memcpy (out_buffer + 3, out_text, *out_size);
+      *out_size += 3;
+      g_free (out_text);
+      return out_buffer;
+    case _ICONV_ISO8859_5:
+    case _ICONV_ISO8859_6:
+    case _ICONV_ISO8859_7:
+    case _ICONV_ISO8859_8:
+    case _ICONV_ISO8859_9:
+    case _ICONV_ISO8859_10:
+    case _ICONV_ISO8859_11:
+    case _ICONV_ISO8859_12:
+    case _ICONV_ISO8859_13:
+    case _ICONV_ISO8859_14:
+    case _ICONV_ISO8859_15:
+      /* These character sets requires 1 selection byte */
+      _encode_control_codes (out_text, *out_size, FALSE);
+      out_buffer = g_malloc (*out_size + 1);
+      out_buffer[0] = encoding - _ICONV_ISO8859_5 + 1;
+      memcpy (out_buffer + 1, out_text, *out_size);
+      *out_size += 1;
+      g_free (out_text);
+      return out_buffer;
+    case _ICONV_UCS_2BE:
+    case _ICONV_EUC_KR:
+    case _ICONV_UTF_16BE:
+      /* These character sets requires 1 selection byte */
+      _encode_control_codes (out_text, *out_size, TRUE);
+      out_buffer = g_malloc (*out_size + 1);
+      out_buffer[0] = encoding - _ICONV_UCS_2BE + 0x11;
+      memcpy (out_buffer + 1, out_text, *out_size);
+      *out_size += 1;
+      g_free (out_text);
+      return out_buffer;
+    case _ICONV_GB2312:
+    case _ICONV_ISO10646_UTF8:
+      /* These character sets requires 1 selection byte */
+      _encode_control_codes (out_text, *out_size, FALSE);
+      out_buffer = g_malloc (*out_size + 1);
+      out_buffer[0] = encoding - _ICONV_UCS_2BE + 0x11;
+      memcpy (out_buffer + 1, out_text, *out_size);
+      *out_size += 1;
+      g_free (out_text);
+      return out_buffer;
+    default:
+      g_free (out_text);
+      return NULL;
+  }
+}
+
+/*
+ * @text: The text to convert. It may include pango markup (<b> and </b>)
+ * @length: The length of the string -1 if it's nul-terminated
+ * @start: Where to start converting in the text
+ * @encoding: The encoding of text
+ * @is_multibyte: Whether the encoding is a multibyte encoding
+ * @error: The location to store the error, or NULL to ignore errors
+ * @returns: UTF-8 encoded string
+ *
+ * Convert text to UTF-8.
+ */
+static gchar *
+convert_to_utf8 (const gchar * text, gint length, guint start,
+    GIConv giconv, gboolean is_multibyte, GError ** error)
+{
+  gchar *new_text;
+  gchar *tmp, *pos;
+  gint i;
+
+  text += start;
+
+  pos = tmp = g_malloc (length * 2);
+  if(!pos)
+    return NULL;
+
+  if (is_multibyte) {
+    if (length == -1) {
+      while (*text != '\0') {
+        guint16 code = GST_READ_UINT16_BE (text);
+
+        switch (code) {
+          case 0xE086:         /* emphasis on */
+          case 0xE087:         /* emphasis off */
+            /* skip it */
+            break;
+          case 0xE08A:{
+            pos[0] = 0x00;      /* 0x00 0x0A is a new line */
+            pos[1] = 0x0A;
+            pos += 2;
+            break;
+          }
+          default:
+            pos[0] = text[0];
+            pos[1] = text[1];
+            pos += 2;
+            break;
+        }
+
+        text += 2;
+      }
+    } else {
+      for (i = 0; i < length; i += 2) {
+        guint16 code = GST_READ_UINT16_BE (text);
+
+        switch (code) {
+          case 0xE086:         /* emphasis on */
+          case 0xE087:         /* emphasis off */
+            /* skip it */
+            break;
+          case 0xE08A:{
+            pos[0] = 0x00;      /* 0x00 0x0A is a new line */
+            pos[1] = 0x0A;
+            pos += 2;
+            break;
+          }
+          default:
+            pos[0] = text[0];
+            pos[1] = text[1];
+            pos += 2;
+            break;
+        }
+
+        text += 2;
+      }
+    }
+  } else {
+    if (length == -1) {
+      while (*text != '\0') {
+        guint8 code = (guint8) (*text);
+
+        switch (code) {
+          case 0x86:           /* emphasis on */
+          case 0x87:           /* emphasis off */
+            /* skip it */
+            break;
+          case 0x8A:
+            *pos = '\n';
+            pos += 1;
+            break;
+          default:
+            *pos = *text;
+            pos += 1;
+            break;
+        }
+
+        text++;
+      }
+    } else {
+      for (i = 0; i < length; i++) {
+        guint8 code = (guint8) (*text);
+
+        switch (code) {
+          case 0x86:           /* emphasis on */
+          case 0x87:           /* emphasis off */
+            /* skip it */
+            break;
+          case 0x8A:
+            *pos = '\n';
+            pos += 1;
+            break;
+          default:
+            *pos = *text;
+            pos += 1;
+            break;
+        }
+
+        text++;
+      }
+    }
+  }
+
+  if (pos > tmp) {
+    gsize bread = 0;
+    new_text =
+        g_convert_with_iconv (tmp, pos - tmp, giconv, &bread, NULL, error);
+    GST_DEBUG ("Converted to : %s", new_text);
+  } else {
+    new_text = g_strdup ("");
+  }
+
+  g_free (tmp);
+
+  return new_text;
+}
+
+gchar *
+get_encoding_and_convert (const gchar * text, guint length)
+{
+  GError *error = NULL;
+  gchar *converted_str;
+  guint start_text = 0;
+  gboolean is_multibyte;
+  LocalIconvCode encoding;
+  GIConv giconv = (GIConv) - 1;
+
+  g_return_val_if_fail (text != NULL, NULL);
+
+  if (text == NULL || length == 0)
+    return g_strdup ("");
+
+  encoding = get_encoding (text, &start_text, &is_multibyte);
+
+  if (encoding > _ICONV_UNKNOWN && encoding < _ICONV_MAX) {
+    GST_DEBUG ("Encoding %s", iconvtablename[encoding]);
+    giconv = _get_iconv (encoding, _ICONV_UTF8);
+  } else {
+    GST_FIXME ("Could not detect encoding. Returning NULL string");
+    converted_str = NULL;
+    goto beach;
+  }
+
+  converted_str = convert_to_utf8 (text, length - start_text, start_text,
+      giconv, is_multibyte, &error);
+  if (error != NULL) {
+    GST_WARNING ("Could not convert string: %s", error->message);
+    g_free (converted_str);
+    g_error_free (error);
+    error = NULL;
+
+    if (encoding >= _ICONV_ISO8859_2 && encoding <= _ICONV_ISO8859_15) {
+      /* Sometimes using the standard 8859-1 set fixes issues */
+      GST_DEBUG ("Encoding %s", iconvtablename[_ICONV_ISO8859_1]);
+      giconv = _get_iconv (_ICONV_ISO8859_1, _ICONV_UTF8);
+
+      GST_INFO ("Trying encoding ISO 8859-1");
+      converted_str = convert_to_utf8 (text, length, 1, giconv, FALSE, &error);
+      if (error != NULL) {
+        GST_WARNING
+            ("Could not convert string while assuming encoding ISO 8859-1: %s",
+            error->message);
+        g_error_free (error);
+        goto failed;
+      }
+    } else if (encoding == _ICONV_ISO6937) {
+
+      /* The first part of ISO 6937 is identical to ISO 8859-9, but
+       * they differ in the second part. Some channels don't
+       * provide the first byte that indicates ISO 8859-9 encoding.
+       * If decoding from ISO 6937 failed, we try ISO 8859-9 here.
+       */
+      giconv = _get_iconv (_ICONV_ISO8859_9, _ICONV_UTF8);
+
+      GST_INFO ("Trying encoding ISO 8859-9");
+      converted_str = convert_to_utf8 (text, length, 0, giconv, FALSE, &error);
+      if (error != NULL) {
+        GST_WARNING
+            ("Could not convert string while assuming encoding ISO 8859-9: %s",
+            error->message);
+        g_error_free (error);
+        goto failed;
+      }
+    } else
+      goto failed;
+  }
+
+beach:
+  return converted_str;
+
+failed:
+  {
+    text += start_text;
+    return g_strndup (text, length - start_text);
+  }
+}
+
+gchar *
+convert_lang_code (guint8 * data)
+{
+  gchar *code;
+  /* the iso language code and country code is always 3 byte long */
+  code = g_malloc0 (4);
+  memcpy (code, data, 3);
+
+  return code;
+}
+
+void
+_packetize_descriptor_array (GPtrArray * array, guint8 ** out_data)
+{
+  guint i;
+  guint8 header_size;
+  GstWFDTSDescriptor *descriptor;
+
+  g_return_if_fail (out_data != NULL);
+  g_return_if_fail (*out_data != NULL);
+
+  if (array == NULL)
+    return;
+
+  for (i = 0; i < array->len; i++) {
+    descriptor = g_ptr_array_index (array, i);
+
+#ifdef ENABLE_ALL
+    if (descriptor->tag == GST_MTS_DESC_DVB_EXTENSION)
+      header_size = 3;
+    else
+      header_size = 2;
+#else
+    header_size = 2;
+#endif
+
+    memcpy (*out_data, descriptor->data, descriptor->length + header_size);
+    *out_data += descriptor->length + header_size;
+  }
+}
+
+GstWFDTSDescriptor *
+_new_wfddescriptor (guint8 tag, guint8 length)
+{
+  GstWFDTSDescriptor *descriptor;
+  guint8 *data;
+
+  descriptor = g_slice_new (GstWFDTSDescriptor);
+
+  descriptor->tag = tag;
+  descriptor->tag_extension = 0;
+  descriptor->length = length;
+
+  descriptor->data = g_malloc (length + 2);
+
+  data = descriptor->data;
+
+  *data++ = descriptor->tag;
+  *data = descriptor->length;
+
+  return descriptor;
+}
+
+GstWFDTSDescriptor *
+_new_wfddescriptor_with_extension (guint8 tag, guint8 tag_extension, guint8 length)
+{
+  GstWFDTSDescriptor *descriptor;
+  guint8 *data;
+
+  descriptor = g_slice_new (GstWFDTSDescriptor);
+
+  descriptor->tag = tag;
+  descriptor->tag_extension = tag_extension;
+  descriptor->length = length;
+
+  descriptor->data = g_malloc (length + 3);
+
+  data = descriptor->data;
+
+  *data++ = descriptor->tag;
+  *data++ = descriptor->tag_extension;
+  *data = descriptor->length;
+
+  return descriptor;
+}
+
+static GstWFDTSDescriptor *
+_copy_descriptor (GstWFDTSDescriptor * desc)
+{
+  GstWFDTSDescriptor *copy;
+
+  copy = g_slice_dup (GstWFDTSDescriptor, desc);
+  copy->data = g_memdup (desc->data, desc->length + 2);
+
+  return copy;
+}
+
+/**
+ * gst_wfd_ts_descriptor_free:
+ * @desc: The descriptor to free
+ *
+ * Frees @desc
+ */
+void
+gst_wfd_ts_descriptor_free (GstWFDTSDescriptor * desc)
+{
+  g_free ((gpointer) desc->data);
+  g_slice_free (GstWFDTSDescriptor, desc);
+}
+
+G_DEFINE_BOXED_TYPE (GstWFDTSDescriptor, gst_wfd_ts_descriptor,
+    (GBoxedCopyFunc) _copy_descriptor,
+    (GBoxedFreeFunc) gst_wfd_ts_descriptor_free);
+
+/**
+ * gst_wfd_ts_parse_descriptors:
+ * @buffer: (transfer none): descriptors to parse
+ * @buf_len: Size of @buffer
+ *
+ * Parses the descriptors present in @buffer and returns them as an
+ * array.
+ *
+ * Note: The data provided in @buffer will not be copied.
+ *
+ * Returns: (transfer full) (element-type GstWFDTSDescriptor): an
+ * array of the parsed descriptors or %NULL if there was an error.
+ * Release with #g_array_unref when done with it.
+ */
+GPtrArray *
+gst_wfd_ts_parse_descriptors (guint8 * buffer, gsize buf_len)
+{
+  GPtrArray *res;
+  guint8 length;
+  guint8 *data;
+  guint i, nb_desc = 0;
+
+  /* fast-path */
+  if (buf_len == 0)
+    return g_ptr_array_new ();
+
+  data = buffer;
+
+  GST_MEMDUMP ("Full descriptor array", buffer, buf_len);
+
+  while (data - buffer < buf_len) {
+    data++;                     /* skip tag */
+    length = *data++;
+
+    if (data - buffer > buf_len) {
+      GST_WARNING ("invalid descriptor length %d now at %d max %"
+          G_GSIZE_FORMAT, length, (gint) (data - buffer), buf_len);
+      return NULL;
+    }
+
+    data += length;
+    nb_desc++;
+  }
+
+  GST_DEBUG ("Saw %d descriptors, read %" G_GSIZE_FORMAT " bytes",
+      nb_desc, data - buffer);
+
+  if (data - buffer != buf_len) {
+    GST_WARNING ("descriptors size %d expected %" G_GSIZE_FORMAT,
+        (gint) (data - buffer), buf_len);
+    return NULL;
+  }
+
+  res =
+      g_ptr_array_new_full (nb_desc + 1,
+      (GDestroyNotify) gst_wfd_ts_descriptor_free);
+
+  data = buffer;
+
+  for (i = 0; i < nb_desc; i++) {
+    GstWFDTSDescriptor *desc = g_slice_new0 (GstWFDTSDescriptor);
+
+    desc->data = data;
+    desc->tag = *data++;
+    desc->length = *data++;
+    /* Copy the data now that we known the size */
+    desc->data = g_memdup (desc->data, desc->length + 2);
+    GST_LOG ("descriptor 0x%02x length:%d", desc->tag, desc->length);
+    GST_MEMDUMP ("descriptor", desc->data + 2, desc->length);
+    /* extended descriptors */
+    if (G_UNLIKELY (desc->tag == 0x7f))
+      desc->tag_extension = *data;
+
+    data += desc->length;
+
+    /* Set the descriptor in the array */
+    g_ptr_array_index (res, i) = desc;
+  }
+
+  res->len = nb_desc;
+
+  return res;
+}
+
+/**
+ * gst_wfd_ts_find_descriptor:
+ * @descriptors: (element-type GstWFDTSDescriptor) (transfer none): an array
+ * of #GstWFDTSDescriptor
+ * @tag: the tag to look for
+ *
+ * Finds the first descriptor of type @tag in the array.
+ *
+ * Note: To look for descriptors that can be present more than once in an
+ * array of descriptors, iterate the #GArray manually.
+ *
+ * Returns: (transfer none): the first descriptor matchin @tag, else %NULL.
+ */
+const GstWFDTSDescriptor *
+gst_wfd_ts_find_descriptor (GPtrArray * descriptors, guint8 tag)
+{
+  guint i, nb_desc;
+
+  g_return_val_if_fail (descriptors != NULL, NULL);
+
+  nb_desc = descriptors->len;
+  for (i = 0; i < nb_desc; i++) {
+    GstWFDTSDescriptor *desc = g_ptr_array_index (descriptors, i);
+    if (desc->tag == tag)
+      return (const GstWFDTSDescriptor *) desc;
+  }
+  return NULL;
+}
+
+/* GST_MTS_DESC_REGISTRATION (0x05) */
+/**
+ * gst_wfd_ts_descriptor_from_registration:
+ * @format_identifier: (transfer none): a 4 character format identifier string
+ * @additional_info: (transfer none) (allow-none): pointer to optional additional info
+ * @additional_info_length: length of the optional @additional_info
+ *
+ * Creates a %GST_MTS_DESC_REGISTRATION #GstWFDTSDescriptor
+ *
+ * Return: #GstWFDTSDescriptor, %NULL on failure
+ */
+GstWFDTSDescriptor *
+gst_wfd_ts_descriptor_from_registration (const gchar * format_identifier,
+    guint8 * additional_info, gsize additional_info_length)
+{
+  GstWFDTSDescriptor *descriptor;
+
+  g_return_val_if_fail (format_identifier != NULL, NULL);
+
+  descriptor = _new_wfddescriptor (GST_MTS_DESC_REGISTRATION,
+      4 + additional_info_length);
+
+  memcpy (descriptor->data + 2, format_identifier, 4);
+  if (additional_info && (additional_info_length > 0))
+    memcpy (descriptor->data + 6, additional_info, additional_info_length);
+
+  return descriptor;
+}
+
+/* GST_MTS_DESC_CA (0x09) */
+
+/**
+ * gst_wfd_ts_descriptor_parse_ca:
+ * @descriptor: a %GST_MTS_DESC_CA #GstWFDTSDescriptor
+ * @ca_system_id: (out): the type of CA system used
+ * @ca_pid: (out): The PID containing ECM or EMM data
+ * @private_data: (out) (allow-none): The private data
+ * @private_data_size: (out) (allow-none): The size of @private_data in bytes
+ *
+ * Extracts the Conditional Access information from @descriptor.
+ *
+ * Returns: %TRUE if parsing succeeded, else %FALSE.
+ */
+
+gboolean
+gst_wfd_ts_descriptor_parse_ca (GstWFDTSDescriptor * descriptor,
+    guint16 * ca_system_id, guint16 * ca_pid,
+    const guint8 ** private_data, gsize * private_data_size)
+{
+  guint8 *data;
+
+  g_return_val_if_fail (descriptor != NULL && ca_system_id != NULL
+      && ca_pid != NULL, FALSE);
+  /* The smallest CA is 4 bytes (though not having any private data
+   * sounds a bit ... weird) */
+  __common_desc_checks (descriptor, GST_MTS_DESC_CA, 4, FALSE);
+
+  data = (guint8 *) descriptor->data + 2;
+  *ca_system_id = GST_READ_UINT16_BE (data);
+  data += 2;
+  *ca_pid = GST_READ_UINT16_BE (data) & 0x1fff;
+  data += 2;
+  if (private_data && private_data_size) {
+    *private_data = data;
+    *private_data_size = descriptor->length - 4;
+  }
+
+  return TRUE;
+}
+
+/* GST_MTS_DESC_ISO_639_LANGUAGE (0x0A) */
+static GstWFDTSISO639LanguageDescriptor *
+_gst_wfd_ts_iso_639_language_descriptor_copy (GstWFDTSISO639LanguageDescriptor
+    * source)
+{
+  GstWFDTSISO639LanguageDescriptor *copy;
+  guint i;
+
+  copy = g_slice_dup (GstWFDTSISO639LanguageDescriptor, source);
+
+  for (i = 0; i < source->nb_language; i++) {
+    copy->language[i] = g_strdup (source->language[i]);
+  }
+
+  return copy;
+}
+
+void
+gst_wfd_ts_iso_639_language_descriptor_free (GstWFDTSISO639LanguageDescriptor
+    * desc)
+{
+  guint i;
+
+  for (i = 0; i < desc->nb_language; i++) {
+    g_free (desc->language[i]);
+  }
+  g_slice_free (GstWFDTSISO639LanguageDescriptor, desc);
+}
+
+G_DEFINE_BOXED_TYPE (GstWFDTSISO639LanguageDescriptor,
+    gst_wfd_ts_iso_639_language,
+    (GBoxedCopyFunc) _gst_wfd_ts_iso_639_language_descriptor_copy,
+    (GFreeFunc) gst_wfd_ts_iso_639_language_descriptor_free);
+
+/**
+ * gst_wfd_ts_descriptor_parse_iso_639_language:
+ * @descriptor: a %GST_MTS_DESC_ISO_639_LANGUAGE #GstWFDTSDescriptor
+ * @res: (out) (transfer full): the #GstWFDTSISO639LanguageDescriptor to fill
+ *
+ * Extracts the iso 639-2 language information from @descriptor.
+ *
+ * Note: Use #gst_tag_get_language_code if you want to get the the
+ * ISO 639-1 language code from the returned ISO 639-2 one.
+ *
+ * Returns: %TRUE if parsing succeeded, else %FALSE.
+ */
+gboolean
+gst_wfd_ts_descriptor_parse_iso_639_language (const GstWFDTSDescriptor *
+    descriptor, GstWFDTSISO639LanguageDescriptor ** desc)
+{
+  guint i;
+  guint8 *data;
+  GstWFDTSISO639LanguageDescriptor *res;
+
+  g_return_val_if_fail (descriptor != NULL && desc != NULL, FALSE);
+  /* This descriptor can be empty, no size check needed */
+  __common_desc_checks (descriptor, GST_MTS_DESC_ISO_639_LANGUAGE, 0, FALSE);
+
+  data = (guint8 *) descriptor->data + 2;
+
+  res = g_slice_new0 (GstWFDTSISO639LanguageDescriptor);
+
+  /* Each language is 3 + 1 bytes */
+  res->nb_language = descriptor->length / 4;
+  for (i = 0; i < res->nb_language; i++) {
+    res->language[i] = convert_lang_code (data);
+    res->audio_type[i] = data[3];
+    data += 4;
+  }
+
+  *desc = res;
+
+  return TRUE;
+
+}
+
+/**
+ * gst_wfd_ts_descriptor_parse_iso_639_language_idx:
+ * @descriptor: a %GST_MTS_DESC_ISO_639_LANGUAGE #GstWFDTSDescriptor
+ * @idx: Table id of the language to parse
+ * @lang: (out) (transfer full): 4-byte gchar array to hold the language code
+ * @audio_type: (out) (transfer none) (allow-none): the #GstWFDTSIso639AudioType to set
+ *
+ * Extracts the iso 639-2 language information from specific table id in @descriptor.
+ *
+ * Note: Use #gst_tag_get_language_code if you want to get the the
+ * ISO 639-1 language code from the returned ISO 639-2 one.
+ *
+ * Returns: %TRUE if parsing succeeded, else %FALSE.
+ */
+gboolean
+gst_wfd_ts_descriptor_parse_iso_639_language_idx (const GstWFDTSDescriptor *
+    descriptor, guint idx, gchar ** lang, GstWFDTSIso639AudioType * audio_type)
+{
+  guint8 *data;
+
+  g_return_val_if_fail (descriptor != NULL && lang != NULL, FALSE);
+  /* This descriptor can be empty, no size check needed */
+  __common_desc_checks (descriptor, GST_MTS_DESC_ISO_639_LANGUAGE, 0, FALSE);
+
+  if (descriptor->length / 4 <= idx)
+    return FALSE;
+
+  data = (guint8 *) descriptor->data + 2 + idx * 4;
+
+  *lang = convert_lang_code (data);
+
+  data += 3;
+
+  if (audio_type)
+    *audio_type = *data;
+
+  return TRUE;
+}
+
+/**
+ * gst_wfd_ts_descriptor_parse_iso_639_language_nb:
+ * @descriptor: a %GST_MTS_DESC_ISO_639_LANGUAGE #GstWFDTSDescriptor
+ *
+ * Returns: The number of languages in @descriptor
+ */
+guint
+gst_wfd_ts_descriptor_parse_iso_639_language_nb (const GstWFDTSDescriptor *
+    descriptor)
+{
+  g_return_val_if_fail (descriptor != NULL, 0);
+  /* This descriptor can be empty, no size check needed */
+  __common_desc_checks (descriptor, GST_MTS_DESC_ISO_639_LANGUAGE, 0, FALSE);
+
+  return descriptor->length / 4;
+}
+
+/**
+ * gst_wfd_ts_descriptor_parse_logical_channel:
+ * @descriptor: a %GST_MTS_DESC_DTG_LOGICAL_CHANNEL #GstWFDTSDescriptor
+ * @res: (out) (transfer none): the #GstWFDTSLogicalChannelDescriptor to fill
+ *
+ * Extracts the logical channels from @descriptor.
+ *
+ * Returns: %TRUE if parsing succeeded, else %FALSE.
+ */
+gboolean
+gst_wfd_ts_descriptor_parse_logical_channel (const GstWFDTSDescriptor *
+    descriptor, GstWFDTSLogicalChannelDescriptor * res)
+{
+  guint i;
+  guint8 *data;
+
+  g_return_val_if_fail (descriptor != NULL && res != NULL, FALSE);
+  /* This descriptor loop can be empty, no size check required */
+  __common_desc_checks (descriptor, GST_MTS_DESC_DTG_LOGICAL_CHANNEL, 0, FALSE);
+
+  data = (guint8 *) descriptor->data + 2;
+
+  res->nb_channels = descriptor->length / 4;
+
+  for (i = 0; i < res->nb_channels; i++) {
+    res->channels[i].service_id = GST_READ_UINT16_BE (data);
+    data += 2;
+    res->channels[i].visible_service = *data >> 7;
+    res->channels[i].logical_channel_number =
+        GST_READ_UINT16_BE (data) & 0x03ff;
+    data += 2;
+  }
+
+  return TRUE;
+}
+
+/**
+ * gst_wfd_ts_descriptor_from_custom:
+ * @tag: descriptor tag
+ * @data: (transfer none): descriptor data (after tag and length field)
+ * @length: length of @data
+ *
+ * Creates a #GstWFDTSDescriptor with custom @tag and @data
+ *
+ * Returns: #GstWFDTSDescriptor
+ */
+GstWFDTSDescriptor *
+gst_wfd_ts_descriptor_from_custom (guint8 tag, const guint8 * data,
+    gsize length)
+{
+  GstWFDTSDescriptor *descriptor;
+
+  descriptor = _new_wfddescriptor (tag, length);
+
+  if (data && (length > 0))
+    memcpy (descriptor->data + 2, data, length);
+
+  return descriptor;
+}
diff --git a/wfdtsdemux/gstwfdtsdescriptor.h b/wfdtsdemux/gstwfdtsdescriptor.h
new file mode 100755 (executable)
index 0000000..a7ad0fb
--- /dev/null
@@ -0,0 +1,347 @@
+/*
+ * gstwfdtsdescriptor.h -
+ * Copyright (C) 2013 Edward Hervey
+ *
+ * Authors:
+ *   Edward Hervey <edward@collabora.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * Some parts of this code come from the Fluendo MPEG Demuxer plugin.
+ *
+ * The Initial Developer of the Original Code is Fluendo, S.L.
+ * Portions created by Fluendo, S.L. are Copyright (C) 2005
+ * Fluendo, S.L. All Rights Reserved.
+ *
+ * Contributor(s): Wim Taymans <wim@fluendo.com>
+ */
+
+#ifndef GST_WFD_TS_DESCRIPTOR_H
+#define GST_WFD_TS_DESCRIPTOR_H
+
+#include <gst/gst.h>
+
+G_BEGIN_DECLS
+
+/*
+ * descriptor_tag TS  PS                      Identification
+ *        0       n/a n/a Reserved
+ *        1       n/a n/a Reserved
+ *        2        X   X  video_stream_descriptor
+ *        3        X   X  audio_stream_descriptor
+ *        4        X   X  hierarchy_descriptor
+ *        5        X   X  registration_descriptor
+ *        6        X   X  data_stream_alignment_descriptor
+ *        7        X   X  target_background_grid_descriptor
+ *        8        X   X  video_window_descriptor
+ *        9        X   X  CA_descriptor
+ *       10        X   X  ISO_639_language_descriptor
+ *       11        X   X  system_clock_descriptor
+ *       12        X   X  multiplex_buffer_utilization_descriptor
+ *       13        X   X  copyright_descriptor
+ *       14        X      maximum bitrate descriptor
+ *       15        X   X  private data indicator descriptor
+ *       16        X   X  smoothing buffer descriptor
+ *       17        X      STD_descriptor
+ *       18        X   X  IBP descriptor
+ *      19-63     n/a n/a ITU-T Rec. H.222.0 | ISO/IEC 13818-1 Reserved
+ *     64-255     n/a n/a User Private
+ */
+
+/**
+ * GstWFDTSDescriptorType:
+ *
+ * The type of #GstWFDTSDescriptor
+ *
+ * These values correspond to the registered descriptor type from
+ * the base MPEG-TS specifications (ITU H.222.0 | ISO/IEC 13818-1).
+ *
+ * Consult the relevant specifications for more details.
+ */
+typedef enum {
+  /* 0-18 ISO/IEC 13818-1 (H222.0 06/2012) */
+  GST_MTS_DESC_RESERVED_00                      = 0x00,
+  GST_MTS_DESC_RESERVED_01                      = 0x01,
+  GST_MTS_DESC_VIDEO_STREAM                     = 0x02,
+  GST_MTS_DESC_AUDIO_STREAM                     = 0x03,
+  GST_MTS_DESC_HIERARCHY                        = 0x04,
+  GST_MTS_DESC_REGISTRATION                     = 0x05,
+  GST_MTS_DESC_DATA_STREAM_ALIGNMENT            = 0x06,
+  GST_MTS_DESC_TARGET_BACKGROUND_GRID           = 0x07,
+  GST_MTS_DESC_VIDEO_WINDOW                     = 0x08,
+  GST_MTS_DESC_CA                               = 0x09,
+  GST_MTS_DESC_ISO_639_LANGUAGE                 = 0x0A,
+  GST_MTS_DESC_SYSTEM_CLOCK                     = 0x0B,
+  GST_MTS_DESC_MULTIPLEX_BUFFER_UTILISATION     = 0x0C,
+  GST_MTS_DESC_COPYRIGHT                        = 0x0D,
+  GST_MTS_DESC_MAXIMUM_BITRATE                  = 0x0E,
+  GST_MTS_DESC_PRIVATE_DATA_INDICATOR           = 0x0F,
+  GST_MTS_DESC_SMOOTHING_BUFFER                 = 0x10,
+  GST_MTS_DESC_STD                              = 0x11,
+  GST_MTS_DESC_IBP                              = 0x12,
+
+  /* 19-26 Defined in ISO/IEC 13818-6 (Extensions for DSM-CC) */
+  GST_MTS_DESC_DSMCC_CAROUSEL_IDENTIFIER        = 0x13,
+  GST_MTS_DESC_DSMCC_ASSOCIATION_TAG            = 0x14,
+  GST_MTS_DESC_DSMCC_DEFERRED_ASSOCIATION_TAG   = 0x15,
+  /* 0x16 is reserved (so far) */
+  GST_MTS_DESC_DSMCC_NPT_REFERENCE              = 0x17,
+  GST_MTS_DESC_DSMCC_NPT_ENDPOINT               = 0x18,
+  GST_MTS_DESC_DSMCC_STREAM_MODE                = 0x19,
+  GST_MTS_DESC_DSMCC_STREAM_EVENT               = 0x1A,
+
+  /* 27-54 Later additions to ISO/IEC 13818-1 (H222.0 06/2012) */
+  GST_MTS_DESC_MPEG4_VIDEO                      = 0x1B,
+  GST_MTS_DESC_MPEG4_AUDIO                      = 0x1C,
+  GST_MTS_DESC_IOD                              = 0x1D,
+  GST_MTS_DESC_SL                               = 0x1E,
+  GST_MTS_DESC_FMC                              = 0x1F,
+  GST_MTS_DESC_EXTERNAL_ES_ID                   = 0x20,
+  GST_MTS_DESC_MUX_CODE                         = 0x21,
+  GST_MTS_DESC_FMX_BUFFER_SIZE                  = 0x22,
+  GST_MTS_DESC_MULTIPLEX_BUFFER                 = 0x23,
+  GST_MTS_DESC_CONTENT_LABELING                 = 0x24,
+  GST_MTS_DESC_METADATA_POINTER                 = 0x25,
+  GST_MTS_DESC_METADATA                         = 0x26,
+  GST_MTS_DESC_METADATA_STD                     = 0x27,
+  GST_MTS_DESC_AVC_VIDEO                        = 0x28,
+  /* defined in ISO/IEC 13818-11, MPEG-2 IPMP */
+  GST_MTS_DESC_IPMP                             = 0x29,
+  GST_MTS_DESC_AVC_TIMING_AND_HRD               = 0x2A,
+  GST_MTS_DESC_MPEG2_AAC_AUDIO                  = 0x2B,
+  GST_MTS_DESC_FLEX_MUX_TIMING                  = 0x2C,
+  GST_MTS_DESC_MPEG4_TEXT                       = 0x2D,
+  GST_MTS_DESC_MPEG4_AUDIO_EXTENSION            = 0x2E,
+  GST_MTS_DESC_AUXILIARY_VIDEO_STREAM           = 0x2F,
+  GST_MTS_DESC_SVC_EXTENSION                    = 0x30,
+  GST_MTS_DESC_MVC_EXTENSION                    = 0x31,
+  GST_MTS_DESC_J2K_VIDEO                        = 0x32,
+  GST_MTS_DESC_MVC_OPERATION_POINT              = 0x33,
+  GST_MTS_DESC_MPEG2_STEREOSCOPIC_VIDEO_FORMAT  = 0x34,
+  GST_MTS_DESC_STEREOSCOPIC_PROGRAM_INFO        = 0x35,
+  GST_MTS_DESC_STEREOSCOPIC_VIDEO_INFO          = 0x36,
+
+  /* 55-63 ITU-T Rec. H.222.0 | ISO/IEC 13818-1 Reserved */
+} GstWFDTSDescriptorType;
+
+/**
+ * GstWFDTSMiscDescriptorType:
+ *
+ * The type of #GstWFDTSDescriptor
+ *
+ * These values correspond to miscellaneous descriptor types that are
+ * not yet identified from known specifications.
+ */
+typedef enum {
+  /* 0x80 - 0xFE are user defined */
+  GST_MTS_DESC_AC3_AUDIO_STREAM                 = 0x81,
+  GST_MTS_DESC_DTG_LOGICAL_CHANNEL              = 0x83,    /* from DTG D-Book */
+} GstWFDTSMiscDescriptorType;
+
+/**
+ * GstWFDTSATSCDescriptorType:
+ *
+ * These values correspond to the registered descriptor type from
+ * the various ATSC specifications.
+ *
+ * Consult the relevant specifications for more details.
+ */
+typedef enum {
+  /* ATSC A/65 2009 */
+  GST_MTS_DESC_ATSC_STUFFING                    = 0x80,
+  GST_MTS_DESC_ATSC_AC3                         = 0x83,
+  GST_MTS_DESC_ATSC_CAPTION_SERVICE             = 0x86,
+  GST_MTS_DESC_ATSC_CONTENT_ADVISORY            = 0x87,
+  GST_MTS_DESC_ATSC_EXTENDED_CHANNEL_NAME       = 0xA0,
+  GST_MTS_DESC_ATSC_SERVICE_LOCATION            = 0xA1,
+  GST_MTS_DESC_ATSC_TIME_SHIFTED_SERVICE        = 0xA2,
+  GST_MTS_DESC_ATSC_COMPONENT_NAME              = 0xA3,
+  GST_MTS_DESC_ATSC_DCC_DEPARTING_REQUEST       = 0xA8,
+  GST_MTS_DESC_ATSC_DCC_ARRIVING_REQUEST        = 0xA9,
+  GST_MTS_DESC_ATSC_REDISTRIBUTION_CONTROL      = 0xAA,
+  GST_MTS_DESC_ATSC_GENRE                       = 0xAB,
+  GST_MTS_DESC_ATSC_PRIVATE_INFORMATION         = 0xAD,
+
+  /* ATSC A/53:3 2009 */
+  GST_MTS_DESC_ATSC_ENHANCED_SIGNALING          = 0xB2,
+
+  /* ATSC A/90 */
+  GST_MTS_DESC_ATSC_DATA_SERVICE                = 0xA4,
+  GST_MTS_DESC_ATSC_PID_COUNT                   = 0xA5,
+  GST_MTS_DESC_ATSC_DOWNLOAD_DESCRIPTOR         = 0xA6,
+  GST_MTS_DESC_ATSC_MULTIPROTOCOL_ENCAPSULATION = 0xA7,
+  GST_MTS_DESC_ATSC_MODULE_LINK                 = 0xB4,
+  GST_MTS_DESC_ATSC_CRC32                       = 0xB5,
+  GST_MTS_DESC_ATSC_GROUP_LINK                  = 0xB8,
+} GstWFDTSATSCDescriptorType;
+
+/**
+ * GstWFDTSISDBDescriptorType:
+ *
+ * These values correspond to the registered descriptor type from
+ * the various ISDB specifications.
+ *
+ * Consult the relevant specifications for more details.
+ */
+typedef enum {
+  /* ISDB ARIB B10 v4.6 */
+  GST_MTS_DESC_ISDB_HIERARCHICAL_TRANSMISSION   = 0xC0,
+  GST_MTS_DESC_ISDB_DIGITAL_COPY_CONTROL        = 0xC1,
+  GST_MTS_DESC_ISDB_NETWORK_IDENTIFICATION      = 0xC2,
+  GST_MTS_DESC_ISDB_PARTIAL_TS_TIME             = 0xc3,
+  GST_MTS_DESC_ISDB_AUDIO_COMPONENT             = 0xc4,
+  GST_MTS_DESC_ISDB_HYPERLINK                   = 0xc5,
+  GST_MTS_DESC_ISDB_TARGET_REGION               = 0xc6,
+  GST_MTS_DESC_ISDB_DATA_CONTENT                = 0xc7,
+  GST_MTS_DESC_ISDB_VIDEO_DECODE_CONTROL        = 0xc8,
+  GST_MTS_DESC_ISDB_DOWNLOAD_CONTENT            = 0xc9,
+  GST_MTS_DESC_ISDB_CA_EMM_TS                   = 0xca,
+  GST_MTS_DESC_ISDB_CA_CONTRACT_INFORMATION     = 0xcb,
+  GST_MTS_DESC_ISDB_CA_SERVICE                  = 0xcc,
+  GST_MTS_DESC_ISDB_TS_INFORMATION              = 0xcd,
+  GST_MTS_DESC_ISDB_EXTENDED_BROADCASTER        = 0xce,
+  GST_MTS_DESC_ISDB_LOGO_TRANSMISSION           = 0xcf,
+  GST_MTS_DESC_ISDB_BASIC_LOCAL_EVENT           = 0xd0,
+  GST_MTS_DESC_ISDB_REFERENCE                   = 0xd1,
+  GST_MTS_DESC_ISDB_NODE_RELATION               = 0xd2,
+  GST_MTS_DESC_ISDB_SHORT_NODE_INFORMATION      = 0xd3,
+  GST_MTS_DESC_ISDB_STC_REFERENCE               = 0xd4,
+  GST_MTS_DESC_ISDB_SERIES                      = 0xd5,
+  GST_MTS_DESC_ISDB_EVENT_GROUP                 = 0xd6,
+  GST_MTS_DESC_ISDB_SI_PARAMETER                = 0xd7,
+  GST_MTS_DESC_ISDB_BROADCASTER_NAME            = 0xd8,
+  GST_MTS_DESC_ISDB_COMPONENT_GROUP             = 0xd9,
+  GST_MTS_DESC_ISDB_SI_PRIME_TS                 = 0xda,
+  GST_MTS_DESC_ISDB_BOARD_INFORMATION           = 0xdb,
+  GST_MTS_DESC_ISDB_LDT_LINKAGE                 = 0xdc,
+  GST_MTS_DESC_ISDB_CONNECTED_TRANSMISSION      = 0xdd,
+  GST_MTS_DESC_ISDB_CONTENT_AVAILABILITY        = 0xde,
+  /* ... */
+  GST_MTS_DESC_ISDB_SERVICE_GROUP               = 0xe0
+
+} GstWFDTSISDBDescriptorType;
+
+typedef struct _GstWFDTSDescriptor GstWFDTSDescriptor;
+
+#define GST_TYPE_WFD_TS_DESCRIPTOR (gst_wfd_ts_descriptor_get_type())
+GType gst_wfd_ts_descriptor_get_type (void);
+
+/**
+ * GstWFDTSDescriptor:
+ * @tag: the type of descriptor
+ * @tag_extension: the extended type (if @descriptor_tag is 0x7f)
+ * @length: the length of the descriptor content (excluding tag/length field)
+ * @data: the full descriptor data (including tag, extension, length). The first
+ * two bytes are the @tag and @tag_extension.
+ *
+ * Mpeg-TS descriptor (ISO/IEC 13818-1).
+ */
+struct _GstWFDTSDescriptor
+{
+  guint8 tag;
+  guint8 tag_extension;
+  guint8 length;
+  guint8 *data;
+
+  /*< private >*/
+  /* Padding for future extension */
+  gpointer _gst_reserved[GST_PADDING];
+};
+
+void       gst_wfd_ts_descriptor_free (GstWFDTSDescriptor *desc);
+
+GPtrArray *gst_wfd_ts_parse_descriptors (guint8 * buffer, gsize buf_len);
+
+const GstWFDTSDescriptor * gst_wfd_ts_find_descriptor (GPtrArray *descriptors,
+                                                       guint8 tag);
+
+/* GST_MTS_DESC_REGISTRATION (0x05) */
+
+GstWFDTSDescriptor *gst_wfd_ts_descriptor_from_registration (
+    const gchar *format_identifier,
+    guint8 *additional_info, gsize additional_info_length);
+
+/* GST_MTS_DESC_CA (0x09) */
+gboolean  gst_wfd_ts_descriptor_parse_ca (GstWFDTSDescriptor *descriptor,
+                                         guint16 *ca_system_id,
+                                         guint16 *ca_pid,
+                                         const guint8 **private_data,
+                                         gsize *private_data_size);
+
+/* GST_MTS_DESC_ISO_639_LANGUAGE (0x0A) */
+/**
+ * GstWFDTSISO639AudioType:
+ *
+ * Type of audio streams
+ *
+ * Defined in ITU H.222.0 Table 2-60
+ */
+typedef enum {
+  GST_MPEGTS_AUDIO_TYPE_UNDEFINED = 0,
+  GST_MPEGTS_AUDIO_TYPE_CLEAN_EFFECTS,
+  GST_MPEGTS_AUDIO_TYPE_HEARING_IMPAIRED,
+  GST_MPEGTS_AUDIO_TYPE_VISUAL_IMPAIRED_COMMENTARY
+} GstWFDTSIso639AudioType;
+
+typedef struct _GstWFDTSISO639LanguageDescriptor GstWFDTSISO639LanguageDescriptor;
+struct _GstWFDTSISO639LanguageDescriptor
+{
+  guint                    nb_language;
+  gchar                    *language[64];
+  GstWFDTSIso639AudioType audio_type[64];
+};
+
+#define GST_TYPE_MPEGTS_ISO_639_LANGUAGE (gst_wfd_ts_iso_639_language_get_type ())
+GType gst_wfd_ts_iso_639_language_get_type (void);
+void gst_wfd_ts_iso_639_language_descriptor_free (GstWFDTSISO639LanguageDescriptor * desc);
+gboolean gst_wfd_ts_descriptor_parse_iso_639_language (const GstWFDTSDescriptor *descriptor,
+                                                      GstWFDTSISO639LanguageDescriptor **res);
+gboolean gst_wfd_ts_descriptor_parse_iso_639_language_idx (const GstWFDTSDescriptor *descriptor,
+                                                           guint idx, gchar **lang,
+                                                           GstWFDTSIso639AudioType *audio_type);
+guint gst_wfd_ts_descriptor_parse_iso_639_language_nb (const GstWFDTSDescriptor *descriptor);
+
+
+
+/* GST_MTS_DESC_DTG_LOGICAL_CHANNEL (0x83) */
+typedef struct _GstWFDTSLogicalChannelDescriptor GstWFDTSLogicalChannelDescriptor;
+typedef struct _GstWFDTSLogicalChannel GstWFDTSLogicalChannel;
+
+struct _GstWFDTSLogicalChannel
+{
+  guint16   service_id;
+  gboolean  visible_service;
+  guint16   logical_channel_number;
+};
+
+struct _GstWFDTSLogicalChannelDescriptor
+{
+  guint                   nb_channels;
+  GstWFDTSLogicalChannel channels[64];
+};
+
+/* FIXME : Maybe make two methods. One for getting the number of channels,
+ * and the other for getting the content for one channel ? */
+gboolean
+gst_wfd_ts_descriptor_parse_logical_channel (const GstWFDTSDescriptor *descriptor,
+                                            GstWFDTSLogicalChannelDescriptor *res);
+
+GstWFDTSDescriptor *
+gst_wfd_ts_descriptor_from_custom (guint8 tag, const guint8 *data, gsize length);
+
+G_END_DECLS
+
+#endif                         /* GST_WFD_TS_DESCRIPTOR_H */
diff --git a/wfdtsdemux/gstwfdtssection.c b/wfdtsdemux/gstwfdtssection.c
new file mode 100755 (executable)
index 0000000..ddd15bf
--- /dev/null
@@ -0,0 +1,1286 @@
+/*
+ * gstwfdtssection.c -
+ * Copyright (C) 2013 Edward Hervey
+ * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
+ * Copyright (C) 2007 Alessandro Decina
+ *               2010 Edward Hervey
+ *  Author: Youness Alaoui <youness.alaoui@collabora.co.uk>, Collabora Ltd.
+ *  Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
+ *  Author: Edward Hervey <bilboed@bilboed.com>, Collabora Ltd.
+ *
+ * Authors:
+ *   Alessandro Decina <alessandro@nnva.org>
+ *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
+ *   Edward Hervey <edward@collabora.com>
+ *
+ * This library is free softwagre; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+
+#include "gstwfdtssection.h"
+#include "gstwfdtsdescriptor.h"
+#include "gstwfdts-private.h"
+
+/**
+ * SECTION:gstwfdts
+ * @title: Mpeg-ts helper library
+ * @short_description: Mpeg-ts helper library for plugins and applications
+ * @include: gst/mpegts/mpegts.h
+ */
+
+/**
+ * SECTION:gstwfdtssection
+ * @title: Base MPEG-TS sections
+ * @short_description: Sections for ITU H.222.0 | ISO/IEC 13818-1
+ * @include: gst/mpegts/mpegts.h
+ *
+ * For more details, refer to the ITU H.222.0 or ISO/IEC 13818-1 specifications
+ * and other specifications mentionned in the documentation.
+ */
+
+/*
+ * TODO
+ *
+ * * Check minimum size for section parsing in the various
+ *   gst_wfd_ts_section_get_<tabld>() methods
+ *
+ * * Implement parsing code for
+ *   * BAT
+ *   * CAT
+ *   * TSDT
+ */
+
+GST_DEBUG_CATEGORY (gst_wfd_ts_debug);
+
+static GQuark QUARK_PAT;
+static GQuark QUARK_CAT;
+static GQuark QUARK_BAT;
+static GQuark QUARK_PMT;
+static GQuark QUARK_NIT;
+static GQuark QUARK_SDT;
+static GQuark QUARK_EIT;
+static GQuark QUARK_TDT;
+static GQuark QUARK_TOT;
+static GQuark QUARK_SECTION;
+
+static GType _gst_wfd_ts_section_type = 0;
+#define MPEG_TYPE_WFD_TS_SECTION (_gst_wfd_ts_section_type)
+GST_DEFINE_MINI_OBJECT_TYPE (GstWFDTSSection, gst_wfd_ts_section);
+
+static const guint32 crc_tab[256] = {
+  0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
+  0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
+  0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7,
+  0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
+  0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3,
+  0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
+  0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef,
+  0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
+  0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb,
+  0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
+  0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
+  0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
+  0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4,
+  0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
+  0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08,
+  0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
+  0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc,
+  0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
+  0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050,
+  0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
+  0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
+  0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
+  0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1,
+  0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
+  0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5,
+  0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
+  0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9,
+  0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
+  0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd,
+  0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
+  0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
+  0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
+  0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2,
+  0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
+  0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e,
+  0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
+  0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a,
+  0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
+  0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676,
+  0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
+  0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
+  0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
+  0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
+};
+
+/* _calc_crc32 relicenced to LGPL from fluendo ts demuxer */
+guint32
+_calc_crc32 (const guint8 * data, guint datalen)
+{
+  gint i;
+  guint32 crc = 0xffffffff;
+
+  for (i = 0; i < datalen; i++) {
+    crc = (crc << 8) ^ crc_tab[((crc >> 24) ^ *data++) & 0xff];
+  }
+  return crc;
+}
+
+gpointer
+__common_section_checks (GstWFDTSSection * section, guint min_size,
+    GstWFDTSParseFunc parsefunc, GDestroyNotify destroynotify)
+{
+  gpointer res;
+
+  /* Check section is big enough */
+  if (section->section_length < min_size) {
+    GST_WARNING
+        ("PID:0x%04x table_id:0x%02x, section too small (Got %d, need at least %d)",
+        section->pid, section->table_id, section->section_length, min_size);
+    return NULL;
+  }
+
+  /* If section has a CRC, check it */
+  if (!section->short_section
+      && (_calc_crc32 (section->data, section->section_length) != 0)) {
+    GST_WARNING ("PID:0x%04x table_id:0x%02x, Bad CRC on section", section->pid,
+        section->table_id);
+    return NULL;
+  }
+
+  /* Finally parse and set the destroy notify */
+  res = parsefunc (section);
+  if (res == NULL)
+    GST_WARNING ("PID:0x%04x table_id:0x%02x, Failed to parse section",
+        section->pid, section->table_id);
+  else
+    section->destroy_parsed = destroynotify;
+  return res;
+}
+
+
+/*
+ * GENERIC MPEG-TS SECTION
+ */
+static void
+_gst_wfd_ts_section_free (GstWFDTSSection * section)
+{
+  GST_DEBUG ("Freeing section type %d", section->section_type);
+
+  if (section->cached_parsed && section->destroy_parsed)
+    section->destroy_parsed (section->cached_parsed);
+
+  g_free (section->data);
+
+  g_slice_free (GstWFDTSSection, section);
+}
+
+static GstWFDTSSection *
+_gst_wfd_ts_section_copy (GstWFDTSSection * section)
+{
+  GstWFDTSSection *copy;
+
+  copy = g_slice_new0 (GstWFDTSSection);
+  gst_mini_object_init (GST_MINI_OBJECT_CAST (copy), 0, MPEG_TYPE_WFD_TS_SECTION,
+      (GstMiniObjectCopyFunction) _gst_wfd_ts_section_copy, NULL,
+      (GstMiniObjectFreeFunction) _gst_wfd_ts_section_free);
+
+  copy->section_type = section->section_type;
+  copy->pid = section->pid;
+  copy->table_id = section->table_id;
+  copy->subtable_extension = section->subtable_extension;
+  copy->version_number = section->version_number;
+  copy->current_next_indicator = section->current_next_indicator;
+  copy->section_number = section->section_number;
+  copy->last_section_number = section->last_section_number;
+  copy->crc = section->crc;
+
+  copy->data = g_memdup (section->data, section->section_length);
+  copy->section_length = section->section_length;
+  /* Note: We do not copy the cached parsed item, it will be
+   * reconstructed on that copy */
+  copy->cached_parsed = NULL;
+  copy->offset = section->offset;
+  copy->short_section = section->short_section;
+
+  return copy;
+}
+
+/**
+ * gst_wfd_ts_section_get_data:
+ * @section: a #GstWFDTSSection
+ *
+ * Gets the original unparsed section data.
+ *
+ * Returns: (transfer full): The original unparsed section data.
+ */
+GBytes *
+gst_wfd_ts_section_get_data (GstWFDTSSection * section)
+{
+  return g_bytes_new (section->data, section->section_length);
+}
+
+/**
+ * gst_message_parse_wfd_ts_section:
+ * @message: a #GstMessage
+ *
+ * Returns the #GstWFDTSSection contained in a message.
+ *
+ * Returns: (transfer full): the contained #GstWFDTSSection, or %NULL.
+ */
+GstWFDTSSection *
+gst_message_parse_wfd_ts_section (GstMessage * message)
+{
+  const GstStructure *st;
+  GstWFDTSSection *section;
+
+  if (message->type != GST_MESSAGE_ELEMENT)
+    return NULL;
+
+  st = gst_message_get_structure (message);
+  /* FIXME : Add checks against know section names */
+  if (!gst_structure_id_get (st, QUARK_SECTION, GST_TYPE_WFD_TS_SECTION,
+          &section, NULL))
+    return NULL;
+
+  return section;
+}
+
+static GstStructure *
+_wfd_ts_section_get_structure (GstWFDTSSection * section)
+{
+  GstStructure *st;
+  GQuark quark;
+
+  switch (section->section_type) {
+    case GST_WFD_TS_SECTION_PAT:
+      quark = QUARK_PAT;
+      break;
+    case GST_WFD_TS_SECTION_PMT:
+      quark = QUARK_PMT;
+      break;
+    case GST_WFD_TS_SECTION_CAT:
+      quark = QUARK_CAT;
+      break;
+    case GST_WFD_TS_SECTION_EIT:
+      quark = QUARK_EIT;
+      break;
+    case GST_WFD_TS_SECTION_BAT:
+      quark = QUARK_BAT;
+      break;
+    case GST_WFD_TS_SECTION_NIT:
+      quark = QUARK_NIT;
+      break;
+    case GST_WFD_TS_SECTION_SDT:
+      quark = QUARK_SDT;
+      break;
+    case GST_WFD_TS_SECTION_TDT:
+      quark = QUARK_TDT;
+      break;
+    case GST_WFD_TS_SECTION_TOT:
+      quark = QUARK_TOT;
+      break;
+    default:
+      GST_DEBUG ("Creating structure for unknown GstWFDTSSection");
+      quark = QUARK_SECTION;
+      break;
+  }
+
+  st = gst_structure_new_id (quark, QUARK_SECTION, MPEG_TYPE_WFD_TS_SECTION,
+      section, NULL);
+
+  return st;
+}
+
+/**
+ * gst_message_new_wfd_ts_section:
+ * @parent: (transfer none): The creator of the message
+ * @section: (transfer none): The #GstWFDTSSection to put in a message
+ *
+ * Creates a new #GstMessage for a @GstWFDTSSection.
+ *
+ * Returns: (transfer full): The new #GstMessage to be posted, or %NULL if the
+ * section is not valid.
+ */
+GstMessage *
+gst_message_new_wfd_ts_section (GstObject * parent, GstWFDTSSection * section)
+{
+  GstMessage *msg;
+  GstStructure *st;
+
+  st = _wfd_ts_section_get_structure (section);
+
+  msg = gst_message_new_element (parent, st);
+
+  return msg;
+}
+
+static GstEvent *
+_wfd_ts_section_get_event (GstWFDTSSection * section)
+{
+  GstStructure *structure;
+  GstEvent *event;
+
+  structure = _wfd_ts_section_get_structure (section);
+
+  event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, structure);
+
+  return event;
+}
+
+/**
+ * gst_event_parse_wfd_ts_section:
+ * @event: (transfer none): #GstEvent containing a #GstWFDTSSection
+ *
+ * Extracts the #GstWFDTSSection contained in the @event #GstEvent
+ *
+ * Returns: (transfer full): The extracted #GstWFDTSSection
+ */
+GstWFDTSSection *
+gst_event_parse_wfd_ts_section (GstEvent * event)
+{
+  const GstStructure *structure;
+  GstWFDTSSection *section;
+
+  structure = gst_event_get_structure (event);
+
+  if (!gst_structure_id_get (structure, QUARK_SECTION, MPEG_TYPE_WFD_TS_SECTION,
+          &section, NULL))
+    return NULL;
+
+  return section;
+}
+
+/**
+ * gst_wfd_ts_section_send_event:
+ * @element: (transfer none): The #GstElement to send to section event to
+ * @section: (transfer none): The #GstWFDTSSection to put in the event
+ *
+ * Creates a custom #GstEvent with a @GstWFDTSSection.
+ * The #GstEvent is sent to the @element #GstElement.
+ *
+ * Returns: %TRUE if the event is sent
+ */
+gboolean
+gst_wfd_ts_section_send_event (GstWFDTSSection * section, GstElement * element)
+{
+  GstEvent *event;
+
+  g_return_val_if_fail (section != NULL, FALSE);
+  g_return_val_if_fail (element != NULL, FALSE);
+
+  event = _wfd_ts_section_get_event (section);
+
+  if (!gst_element_send_event (element, event)) {
+    gst_event_unref (event);
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+static GstMpegtsPatProgram *
+_mpegts_pat_program_copy (GstMpegtsPatProgram * orig)
+{
+  return g_slice_dup (GstMpegtsPatProgram, orig);
+}
+
+static void
+_mpegts_pat_program_free (GstMpegtsPatProgram * orig)
+{
+  g_slice_free (GstMpegtsPatProgram, orig);
+}
+
+G_DEFINE_BOXED_TYPE (GstMpegtsPatProgram, gst_wfd_ts_pat_program,
+    (GBoxedCopyFunc) _mpegts_pat_program_copy,
+    (GFreeFunc) _mpegts_pat_program_free);
+
+/* Program Association Table */
+static gpointer
+_parse_pat (GstWFDTSSection * section)
+{
+  GPtrArray *pat;
+  guint16 i = 0, nb_programs;
+  GstMpegtsPatProgram *program;
+  guint8 *data, *end;
+
+  /* Skip already parsed data */
+  data = section->data + 8;
+
+  /* stop at the CRC */
+  end = section->data + section->section_length;
+
+  /* Initialize program list */
+  nb_programs = (end - 4 - data) / 4;
+  pat =
+      g_ptr_array_new_full (nb_programs,
+      (GDestroyNotify) _mpegts_pat_program_free);
+
+  while (data < end - 4) {
+    program = g_slice_new0 (GstMpegtsPatProgram);
+    program->program_number = GST_READ_UINT16_BE (data);
+    data += 2;
+
+    program->network_or_program_map_PID = GST_READ_UINT16_BE (data) & 0x1FFF;
+    data += 2;
+
+    g_ptr_array_index (pat, i) = program;
+
+    i++;
+  }
+  pat->len = nb_programs;
+
+  if (data != end - 4) {
+    GST_ERROR ("at the end of PAT data != end - 4");
+    g_ptr_array_unref (pat);
+
+    return NULL;
+  }
+
+  return (gpointer) pat;
+}
+
+/**
+ * gst_wfd_ts_section_get_pat:
+ * @section: a #GstWFDTSSection of type %GST_WFD_TS_SECTION_PAT
+ *
+ * Parses a Program Association Table (ITU H.222.0, ISO/IEC 13818-1).
+ *
+ * Returns the array of #GstMpegtsPatProgram contained in the section.
+ *
+ * Note: The PAT "transport_id" field corresponds to the "subtable_extension"
+ * field of the provided @section.
+ *
+ * Returns: (transfer container) (element-type GstMpegtsPatProgram): The
+ * #GstMpegtsPatProgram contained in the section, or %NULL if an error
+ * happened. Release with #g_ptr_array_unref when done.
+ */
+GPtrArray *
+gst_wfd_ts_section_get_pat (GstWFDTSSection * section)
+{
+  g_return_val_if_fail (section->section_type == GST_WFD_TS_SECTION_PAT, NULL);
+  g_return_val_if_fail (section->cached_parsed || section->data, NULL);
+
+  if (!section->cached_parsed)
+    section->cached_parsed =
+        __common_section_checks (section, 12, _parse_pat,
+        (GDestroyNotify) g_ptr_array_unref);
+
+  if (section->cached_parsed)
+    return g_ptr_array_ref ((GPtrArray *) section->cached_parsed);
+  return NULL;
+}
+
+/**
+ * gst_wfd_ts_pat_new:
+ *
+ * Allocates a new #GPtrArray for #GstMpegtsPatProgram
+ *
+ * Returns: (transfer full) (element-type GstMpegtsPatProgram): A newly allocated #GPtrArray
+ */
+GPtrArray *
+gst_wfd_ts_pat_new (void)
+{
+  GPtrArray *pat;
+
+  pat = g_ptr_array_new_with_free_func (
+      (GDestroyNotify) _mpegts_pat_program_free);
+
+  return pat;
+}
+
+/**
+ * gst_wfd_ts_pat_program_new:
+ *
+ * Allocates a new #GstMpegtsPatProgram.
+ *
+ * Returns: (transfer full): A newly allocated #GstMpegtsPatProgram
+ */
+GstMpegtsPatProgram *
+gst_wfd_ts_pat_program_new (void)
+{
+  GstMpegtsPatProgram *program;
+
+  program = g_slice_new0 (GstMpegtsPatProgram);
+
+  return program;
+}
+
+static gboolean
+_packetize_pat (GstWFDTSSection * section)
+{
+  GPtrArray *programs;
+  guint8 *data;
+  gsize length;
+  guint i;
+
+  programs = gst_wfd_ts_section_get_pat (section);
+
+  if (programs == NULL)
+    return FALSE;
+
+  /* 8 byte common section fields
+     4 byte CRC */
+  length = 12;
+
+  /* 2 byte program number
+     2 byte program/network PID */
+  length += programs->len * 4;
+
+  _packetize_common_section (section, length);
+  data = section->data + 8;
+
+  for (i = 0; i < programs->len; i++) {
+    GstMpegtsPatProgram *program;
+
+    program = g_ptr_array_index (programs, i);
+
+    /* program_number       - 16 bit uimsbf */
+    GST_WRITE_UINT16_BE (data, program->program_number);
+    data += 2;
+
+    /* reserved             - 3  bit
+       program/network_PID  - 13 uimsbf */
+    GST_WRITE_UINT16_BE (data, program->network_or_program_map_PID | 0xE000);
+    data += 2;
+  }
+
+  g_ptr_array_unref (programs);
+
+  return TRUE;
+}
+
+/**
+ * gst_wfd_ts_section_from_pat:
+ * @programs: (transfer full) (element-type GstMpegtsPatProgram): an array of #GstMpegtsPatProgram
+ * @ts_id: Transport stream ID of the PAT
+ *
+ * Creates a PAT #GstWFDTSSection from the @programs array of #GstMpegtsPatPrograms
+ *
+ * Returns: (transfer full): a #GstWFDTSSection
+ */
+GstWFDTSSection *
+gst_wfd_ts_section_from_pat (GPtrArray * programs, guint16 ts_id)
+{
+  GstWFDTSSection *section;
+
+  section = _gst_wfd_ts_section_init (0x00,
+      GST_MTS_TABLE_ID_PROGRAM_ASSOCIATION);
+
+  section->subtable_extension = ts_id;
+  section->cached_parsed = (gpointer) programs;
+  section->packetizer = _packetize_pat;
+  section->destroy_parsed = (GDestroyNotify) g_ptr_array_unref;
+
+  return section;
+}
+
+/* Program Map Table */
+
+static GstWFDTSPMTStream *
+_gst_wfd_ts_pmt_stream_copy (GstWFDTSPMTStream * pmt)
+{
+  GstWFDTSPMTStream *copy;
+
+  g_return_val_if_fail (pmt, NULL);
+
+  copy = g_slice_dup (GstWFDTSPMTStream, pmt);
+  copy->descriptors = g_ptr_array_ref (pmt->descriptors);
+
+  return copy;
+}
+
+static void
+_gst_wfd_ts_pmt_stream_free (GstWFDTSPMTStream * pmt)
+{
+  g_return_if_fail (pmt);
+
+  if (pmt->descriptors)
+    g_ptr_array_unref (pmt->descriptors);
+  g_slice_free (GstWFDTSPMTStream, pmt);
+}
+
+G_DEFINE_BOXED_TYPE (GstWFDTSPMTStream, gst_wfd_ts_pmt_stream,
+    (GBoxedCopyFunc) _gst_wfd_ts_pmt_stream_copy,
+    (GFreeFunc) _gst_wfd_ts_pmt_stream_free);
+
+static GstWFDTSPMT *
+_gst_wfd_ts_pmt_copy (GstWFDTSPMT * pmt)
+{
+  GstWFDTSPMT *copy;
+
+  g_return_val_if_fail (pmt, NULL);
+
+  copy = g_slice_dup (GstWFDTSPMT, pmt);
+  if (pmt->descriptors)
+    copy->descriptors = g_ptr_array_ref (pmt->descriptors);
+  copy->streams = g_ptr_array_ref (pmt->streams);
+
+  return copy;
+}
+
+static void
+_gst_wfd_ts_pmt_free (GstWFDTSPMT * pmt)
+{
+  g_return_if_fail (pmt);
+
+  if (pmt->descriptors)
+    g_ptr_array_unref (pmt->descriptors);
+  g_ptr_array_unref (pmt->streams);
+  g_slice_free (GstWFDTSPMT, pmt);
+}
+
+G_DEFINE_BOXED_TYPE (GstWFDTSPMT, gst_mpegts_pmt,
+    (GBoxedCopyFunc) _gst_wfd_ts_pmt_copy, (GFreeFunc) _gst_wfd_ts_pmt_free);
+
+
+static gpointer
+_parse_pmt (GstWFDTSSection * section)
+{
+  GstWFDTSPMT *pmt = NULL;
+  guint i = 0, allocated_streams = 8;
+  guint8 *data, *end;
+  guint program_info_length;
+  guint stream_info_length;
+
+  pmt = g_slice_new0 (GstWFDTSPMT);
+  if(pmt == NULL) {
+    GST_ERROR("Failed to allocate memory for pmt");
+    return NULL;
+  }
+
+  data = section->data;
+  end = data + section->section_length;
+
+  GST_DEBUG ("Parsing %d Program Map Table", section->subtable_extension);
+
+  /* Assign program number from subtable extenstion,
+     and skip already parsed data */
+  pmt->program_number = section->subtable_extension;
+  data += 8;
+
+  pmt->pcr_pid = GST_READ_UINT16_BE (data) & 0x1FFF;
+  data += 2;
+
+  program_info_length = GST_READ_UINT16_BE (data) & 0x0FFF;
+  data += 2;
+
+  /* check that the buffer is large enough to contain at least
+   * program_info_length bytes + CRC */
+  if (program_info_length && (data + program_info_length + 4 > end)) {
+    GST_WARNING ("PID %d invalid program info length %d left %d",
+        section->pid, program_info_length, (gint) (end - data));
+    goto error;
+  }
+  pmt->descriptors = gst_wfd_ts_parse_descriptors (data, program_info_length);
+  if (pmt->descriptors == NULL)
+    goto error;
+  data += program_info_length;
+
+  pmt->streams =
+      g_ptr_array_new_full (allocated_streams,
+      (GDestroyNotify) _gst_wfd_ts_pmt_stream_free);
+
+  /* parse entries, cycle until there's space for another entry (at least 5
+   * bytes) plus the CRC */
+  while (data <= end - 4 - 5) {
+    GstWFDTSPMTStream *stream = g_slice_new0 (GstWFDTSPMTStream);
+
+    g_ptr_array_add (pmt->streams, stream);
+
+    stream->stream_type = *data++;
+    GST_DEBUG ("[%d] Stream type 0x%02x found", i, stream->stream_type);
+
+    stream->pid = GST_READ_UINT16_BE (data) & 0x1FFF;
+    data += 2;
+
+    stream_info_length = GST_READ_UINT16_BE (data) & 0x0FFF;
+    data += 2;
+
+    if (data + stream_info_length + 4 > end) {
+      GST_WARNING ("PID %d invalid stream info length %d left %d", section->pid,
+          stream_info_length, (gint) (end - data));
+      goto error;
+    }
+
+    stream->descriptors =
+        gst_wfd_ts_parse_descriptors (data, stream_info_length);
+    if (stream->descriptors == NULL)
+      goto error;
+    data += stream_info_length;
+
+    i += 1;
+  }
+
+  g_assert (data == end - 4);
+
+  return (gpointer) pmt;
+
+error:
+  if (pmt)
+    _gst_wfd_ts_pmt_free (pmt);
+
+  return NULL;
+}
+
+/**
+ * gst_wfd_ts_section_get_pmt:
+ * @section: a #GstWFDTSSection of type %GST_WFD_TS_SECTION_PMT
+ *
+ * Returns the #GstWFDTSPMT contained in the @section.
+ *
+ * Returns: The #GstWFDTSPMT contained in the section, or %NULL if an error
+ * happened.
+ */
+const GstWFDTSPMT *
+gst_wfd_ts_section_get_pmt (GstWFDTSSection * section)
+{
+  g_return_val_if_fail (section->section_type == GST_WFD_TS_SECTION_PMT, NULL);
+  g_return_val_if_fail (section->cached_parsed || section->data, NULL);
+
+  if (!section->cached_parsed)
+    section->cached_parsed =
+        __common_section_checks (section, 16, _parse_pmt,
+        (GDestroyNotify) _gst_wfd_ts_pmt_free);
+
+  return (const GstWFDTSPMT *) section->cached_parsed;
+}
+
+/**
+ * gst_wfd_ts_pmt_new:
+ *
+ * Allocates and initializes a new #GstWFDTSPMT.
+ *
+ * Returns: (transfer full): #GstWFDTSPMT
+ */
+GstWFDTSPMT *
+gst_wfd_ts_pmt_new (void)
+{
+  GstWFDTSPMT *pmt;
+
+  pmt = g_slice_new0 (GstWFDTSPMT);
+
+  pmt->descriptors = g_ptr_array_new_with_free_func ((GDestroyNotify)
+      gst_wfd_ts_descriptor_free);
+  pmt->streams = g_ptr_array_new_with_free_func ((GDestroyNotify)
+      _gst_wfd_ts_pmt_stream_free);
+
+  return pmt;
+}
+
+/**
+ * gst_wfd_ts_pmt_stream_new:
+ *
+ * Allocates and initializes a new #GstWFDTSPMTStream.
+ *
+ * Returns: (transfer full): #GstWFDTSPMTStream
+ */
+GstWFDTSPMTStream *
+gst_wfd_ts_pmt_stream_new (void)
+{
+  GstWFDTSPMTStream *stream;
+
+  stream = g_slice_new0 (GstWFDTSPMTStream);
+
+  stream->descriptors = g_ptr_array_new_with_free_func ((GDestroyNotify)
+      gst_wfd_ts_descriptor_free);
+
+  return stream;
+}
+
+static gboolean
+_packetize_pmt (GstWFDTSSection * section)
+{
+  const GstWFDTSPMT *pmt;
+  GstWFDTSPMTStream *stream;
+  GstWFDTSDescriptor *descriptor;
+  gsize length, pgm_info_length, stream_length;
+  guint8 *data;
+  guint i, j;
+
+  pmt = gst_wfd_ts_section_get_pmt (section);
+
+  if (pmt == NULL)
+    return FALSE;
+
+  /* 8 byte common section fields
+     2 byte PCR pid
+     2 byte program info length
+     4 byte CRC */
+  length = 16;
+
+  /* Find length of program info */
+  pgm_info_length = 0;
+  if (pmt->descriptors) {
+    for (i = 0; i < pmt->descriptors->len; i++) {
+      descriptor = g_ptr_array_index (pmt->descriptors, i);
+      pgm_info_length += descriptor->length + 2;
+    }
+  }
+
+  /* Find length of PMT streams */
+  stream_length = 0;
+  if (pmt->streams) {
+    for (i = 0; i < pmt->streams->len; i++) {
+      stream = g_ptr_array_index (pmt->streams, i);
+
+      /* 1 byte stream type
+         2 byte PID
+         2 byte ES info length */
+      stream_length += 5;
+
+      if (stream->descriptors) {
+        for (j = 0; j < stream->descriptors->len; j++) {
+          descriptor = g_ptr_array_index (stream->descriptors, j);
+          stream_length += descriptor->length + 2;
+        }
+      }
+    }
+  }
+
+  length += pgm_info_length + stream_length;
+
+  _packetize_common_section (section, length);
+  data = section->data + 8;
+
+  /* reserved                         - 3  bit
+     PCR_PID                          - 13 uimsbf */
+  GST_WRITE_UINT16_BE (data, pmt->pcr_pid | 0xE000);
+  data += 2;
+
+  /* reserved                         - 4  bit
+     program_info_length              - 12 uimsbf */
+  GST_WRITE_UINT16_BE (data, pgm_info_length | 0xF000);
+  data += 2;
+
+  _packetize_descriptor_array (pmt->descriptors, &data);
+
+  if (pmt->streams) {
+    guint8 *pos;
+
+    for (i = 0; i < pmt->streams->len; i++) {
+      stream = g_ptr_array_index (pmt->streams, i);
+      /* stream_type                  - 8  bit uimsbf */
+      *data++ = stream->stream_type;
+
+      /* reserved                     - 3  bit
+         elementary_PID               - 13 bit uimsbf */
+      GST_WRITE_UINT16_BE (data, stream->pid | 0xE000);
+      data += 2;
+
+      /* reserved                     - 4  bit
+         ES_info_length               - 12 bit uimsbf */
+      pos = data;
+      data += 2;
+      _packetize_descriptor_array (stream->descriptors, &data);
+
+      /* Go back and update descriptor length */
+      GST_WRITE_UINT16_BE (pos, (data - pos - 2) | 0xF000);
+    }
+  }
+
+  return TRUE;
+}
+
+/**
+ * gst_wfd_ts_section_from_pmt:
+ * @pmt: (transfer full): a #GstWFDTSPMT to create a #GstWFDTSSection from
+ * @pid: The PID that the #GstWFDTSPMT belongs to
+ *
+ * Creates a #GstWFDTSSection from @pmt that is bound to @pid
+ *
+ * Returns: (transfer full): #GstWFDTSSection
+ */
+GstWFDTSSection *
+gst_wfd_ts_section_from_pmt (GstWFDTSPMT * pmt, guint16 pid)
+{
+  GstWFDTSSection *section;
+
+  g_return_val_if_fail (pmt != NULL, NULL);
+
+  section = _gst_wfd_ts_section_init (pid, GST_MTS_TABLE_ID_TS_PROGRAM_MAP);
+
+  section->subtable_extension = pmt->program_number;
+  section->cached_parsed = (gpointer) pmt;
+  section->packetizer = _packetize_pmt;
+  section->destroy_parsed = (GDestroyNotify) _gst_wfd_ts_pmt_free;
+
+  return section;
+}
+
+/* Conditional Access Table */
+static gpointer
+_parse_cat (GstWFDTSSection * section)
+{
+  guint8 *data;
+  guint desc_len;
+
+  /* Skip parts already parsed */
+  data = section->data + 8;
+
+  /* descriptors */
+  desc_len = section->section_length - 4 - 8;
+  return (gpointer) gst_wfd_ts_parse_descriptors (data, desc_len);
+}
+
+/**
+ * gst_wfd_ts_section_get_cat:
+ * @section: a #GstWFDTSSection of type %GST_WFD_TS_SECTION_CAT
+ *
+ * Returns the array of #GstWFDTSDescriptor contained in the Condtional
+ * Access Table.:0
+
+ *
+ * Returns: (transfer container) (element-type GstWFDTSDescriptor): The
+ * #GstWFDTSDescriptor contained in the section, or %NULL if an error
+ * happened. Release with #g_array_unref when done.
+ */
+GPtrArray *
+gst_wfd_ts_section_get_cat (GstWFDTSSection * section)
+{
+  g_return_val_if_fail (section->section_type == GST_WFD_TS_SECTION_CAT, NULL);
+  g_return_val_if_fail (section->cached_parsed || section->data, NULL);
+
+  if (!section->cached_parsed)
+    section->cached_parsed =
+        __common_section_checks (section, 12, _parse_cat,
+        (GDestroyNotify) g_ptr_array_unref);
+
+  if (section->cached_parsed)
+    return g_ptr_array_ref ((GPtrArray *) section->cached_parsed);
+  return NULL;
+}
+
+/* Transport Stream Description Table (TSDT) */
+/**
+ * gst_wfd_ts_section_get_tsdt:
+ * @section: a #GstWFDTSSection of type %GST_WFD_TS_SECTION_TSDT
+ *
+ * Returns the array of #GstWFDTSDescriptor contained in the section
+ *
+ * Returns: (transfer container) (element-type GstWFDTSDescriptor): The
+ * #GstWFDTSDescriptor contained in the section, or %NULL if an error
+ * happened. Release with #g_array_unref when done.
+ */
+GPtrArray *
+gst_wfd_ts_section_get_tsdt (GstWFDTSSection * section)
+{
+  g_return_val_if_fail (section->section_type == GST_WFD_TS_SECTION_TSDT, NULL);
+  g_return_val_if_fail (section->cached_parsed || section->data, NULL);
+
+  if (section->cached_parsed)
+    return g_ptr_array_ref ((GPtrArray *) section->cached_parsed);
+
+  /* FIXME : parse TSDT */
+  return NULL;
+}
+
+
+/**
+ * gst_wfd_ts_initialize:
+ *
+ * Initializes the MPEG-TS helper library. Must be called before any
+ * usage.
+ */
+void
+gst_wfd_ts_initialize (void)
+{
+  if (_gst_wfd_ts_section_type)
+    return;
+
+  GST_DEBUG_CATEGORY_INIT (gst_wfd_ts_debug, "wfdts", 0,
+      "WiFi Display TS helper library");
+
+  /* FIXME : Temporary hack to initialize section gtype */
+  _gst_wfd_ts_section_type = gst_wfd_ts_section_get_type ();
+
+  QUARK_PAT = g_quark_from_string ("pat");
+  QUARK_CAT = g_quark_from_string ("cat");
+  QUARK_PMT = g_quark_from_string ("pmt");
+  QUARK_NIT = g_quark_from_string ("nit");
+  QUARK_BAT = g_quark_from_string ("bat");
+  QUARK_SDT = g_quark_from_string ("sdt");
+  QUARK_EIT = g_quark_from_string ("eit");
+  QUARK_TDT = g_quark_from_string ("tdt");
+  QUARK_TOT = g_quark_from_string ("tot");
+  QUARK_SECTION = g_quark_from_string ("section");
+
+  __initialize_descriptors ();
+}
+
+/* FIXME : Later on we might need to use more than just the table_id
+ * to figure out which type of section this is. */
+static GstWFDTSSectionType
+_identify_section (guint16 pid, guint8 table_id)
+{
+  switch (table_id) {
+    case GST_MTS_TABLE_ID_PROGRAM_ASSOCIATION:
+      if (pid == 0x00)
+        return GST_WFD_TS_SECTION_PAT;
+      break;
+    case GST_MTS_TABLE_ID_CONDITIONAL_ACCESS:
+      if (pid == 0x01)
+        return GST_WFD_TS_SECTION_CAT;
+      break;
+    case GST_MTS_TABLE_ID_TS_PROGRAM_MAP:
+      return GST_WFD_TS_SECTION_PMT;
+#ifdef ENABLE_ALL
+    case GST_MTS_TABLE_ID_BOUQUET_ASSOCIATION:
+      if (pid == 0x0011)
+        return GST_WFD_TS_SECTION_BAT;
+      break;
+    case GST_MTS_TABLE_ID_NETWORK_INFORMATION_ACTUAL_NETWORK:
+    case GST_MTS_TABLE_ID_NETWORK_INFORMATION_OTHER_NETWORK:
+      if (pid == 0x0010)
+        return GST_WFD_TS_SECTION_NIT;
+      break;
+    case GST_MTS_TABLE_ID_SERVICE_DESCRIPTION_ACTUAL_TS:
+    case GST_MTS_TABLE_ID_SERVICE_DESCRIPTION_OTHER_TS:
+      if (pid == 0x0011)
+        return GST_WFD_TS_SECTION_SDT;
+      break;
+    case GST_MTS_TABLE_ID_TIME_DATE:
+      if (pid == 0x0014)
+        return GST_WFD_TS_SECTION_TDT;
+      break;
+    case GST_MTS_TABLE_ID_TIME_OFFSET:
+      if (pid == 0x0014)
+        return GST_WFD_TS_SECTION_TOT;
+      break;
+    case GST_MTS_TABLE_ID_ATSC_TERRESTRIAL_VIRTUAL_CHANNEL:
+      if (pid == 0x1ffb)
+        return GST_WFD_TS_SECTION_ATSC_TVCT;
+      break;
+    case GST_MTS_TABLE_ID_ATSC_CABLE_VIRTUAL_CHANNEL:
+      if (pid == 0x1ffb)
+        return GST_WFD_TS_SECTION_ATSC_CVCT;
+      break;
+    case GST_MTS_TABLE_ID_ATSC_MASTER_GUIDE:
+      if (pid == 0x1ffb)
+        return GST_WFD_TS_SECTION_ATSC_MGT;
+      break;
+    case GST_MTS_TABLE_ID_ATSC_EVENT_INFORMATION:
+      /* FIXME check pids reported on the MGT to confirm expectations */
+      return GST_WFD_TS_SECTION_ATSC_EIT;
+    case GST_MTS_TABLE_ID_ATSC_CHANNEL_OR_EVENT_EXTENDED_TEXT:
+      /* FIXME check pids reported on the MGT to confirm expectations */
+      return GST_WFD_TS_SECTION_ATSC_ETT;
+      /* FIXME : FILL */
+    case GST_MTS_TABLE_ID_ATSC_SYSTEM_TIME:
+      if (pid == 0x1ffb)
+        return GST_WFD_TS_SECTION_ATSC_STT;
+      break;
+#endif
+    default:
+#ifdef ENABLE_ALL
+      /* Handle ranges */
+      if (table_id >= GST_MTS_TABLE_ID_EVENT_INFORMATION_ACTUAL_TS_PRESENT &&
+          table_id <= GST_MTS_TABLE_ID_EVENT_INFORMATION_OTHER_TS_SCHEDULE_N) {
+        if (pid == 0x0012)
+          return GST_WFD_TS_SECTION_EIT;
+      }
+#endif
+      return GST_WFD_TS_SECTION_UNKNOWN;
+  }
+  return GST_WFD_TS_SECTION_UNKNOWN;
+
+}
+
+GstWFDTSSection *
+_gst_wfd_ts_section_init (guint16 pid, guint8 table_id)
+{
+  GstWFDTSSection *section;
+
+  section = g_slice_new0 (GstWFDTSSection);
+  gst_mini_object_init (GST_MINI_OBJECT_CAST (section), 0, MPEG_TYPE_WFD_TS_SECTION,
+      (GstMiniObjectCopyFunction) _gst_wfd_ts_section_copy, NULL,
+      (GstMiniObjectFreeFunction) _gst_wfd_ts_section_free);
+
+  section->pid = pid;
+  section->table_id = table_id;
+  section->current_next_indicator = TRUE;
+  section->section_type = _identify_section (pid, table_id);
+
+  return section;
+}
+
+void
+_packetize_common_section (GstWFDTSSection * section, gsize length)
+{
+  guint8 *data;
+
+  section->section_length = length;
+  data = section->data = g_malloc (length);
+
+  /* table_id                         - 8 bit uimsbf */
+  *data++ = section->table_id;
+
+  /* section_syntax_indicator         - 1  bit
+     reserved                         - 3  bit
+     section_length                   - 12 bit uimsbf */
+  switch (section->section_type) {
+    case GST_WFD_TS_SECTION_PAT:
+    case GST_WFD_TS_SECTION_PMT:
+    case GST_WFD_TS_SECTION_CAT:
+    case GST_WFD_TS_SECTION_TSDT:
+      /* Tables from ISO/IEC 13818-1 has a '0' bit
+       * after the section_syntax_indicator */
+      GST_WRITE_UINT16_BE (data, (section->section_length - 3) | 0x3000);
+      break;
+    default:
+      GST_WRITE_UINT16_BE (data, (section->section_length - 3) | 0x7000);
+  }
+
+  if (!section->short_section)
+    *data |= 0x80;
+
+  data += 2;
+
+  /* subtable_extension               - 16 bit uimsbf */
+  GST_WRITE_UINT16_BE (data, section->subtable_extension);
+  data += 2;
+
+  /* reserved                         - 2  bit
+     version_number                   - 5  bit uimsbf
+     current_next_indicator           - 1  bit */
+  *data++ = 0xC0 |
+      ((section->version_number & 0x1F) << 1) |
+      (section->current_next_indicator & 0x01);
+
+  /* section_number                   - 8  bit uimsbf */
+  *data++ = section->section_number;
+  /* last_section_number              - 8  bit uimsbf */
+  *data++ = section->last_section_number;
+}
+
+/**
+ * gst_wfd_ts_section_new:
+ * @pid: the PID to which this section belongs
+ * @data: (transfer full): a pointer to the beginning of the section (i.e. the first byte
+ * should contain the table_id field).
+ * @data_size: size of the @data argument.
+ *
+ * Creates a new #GstWFDTSSection from the provided @data.
+ *
+ * Note: Ensuring @data is big enough to contain the full section is the
+ * responsibility of the caller. If it is not big enough, %NULL will be
+ * returned.
+ *
+ * Note: it is the responsibility of the caller to ensure @data does point
+ * to the beginning of the section.
+ *
+ * Returns: (transfer full): A new #GstWFDTSSection if the data was valid,
+ * else %NULL
+ */
+GstWFDTSSection *
+gst_wfd_ts_section_new (guint16 pid, guint8 * data, gsize data_size)
+{
+  GstWFDTSSection *res = NULL;
+  guint8 tmp;
+  guint8 table_id;
+  guint16 section_length;
+
+  g_return_val_if_fail (data, NULL);
+
+  /* Check for length */
+  section_length = GST_READ_UINT16_BE (data + 1) & 0x0FFF;
+  if (G_UNLIKELY (data_size < section_length + 3))
+    goto short_packet;
+
+  /* Table id is in first byte */
+  table_id = *data;
+
+  res = _gst_wfd_ts_section_init (pid, table_id);
+
+  res->data = data;
+  /* table_id (already parsed)       : 8  bit */
+  data++;
+  /* section_syntax_indicator        : 1  bit
+   * other_fields (reserved)         : 3  bit*/
+  res->short_section = (*data & 0x80) == 0x00;
+  /* section_length (already parsed) : 12 bit */
+  res->section_length = section_length + 3;
+  if (!res->short_section) {
+    /* CRC is after section_length (-4 for the size of the CRC) */
+    res->crc = GST_READ_UINT32_BE (res->data + res->section_length - 4);
+    /* Skip to after section_length */
+    data += 2;
+    /* subtable extension            : 16 bit */
+    res->subtable_extension = GST_READ_UINT16_BE (data);
+    data += 2;
+    /* reserved                      : 2  bit
+     * version_number                : 5  bit
+     * current_next_indicator        : 1  bit */
+    tmp = *data++;
+    res->version_number = tmp >> 1 & 0x1f;
+    res->current_next_indicator = tmp & 0x01;
+    /* section_number                : 8  bit */
+    res->section_number = *data++;
+    /* last_section_number                : 8  bit */
+    res->last_section_number = *data;
+  }
+
+  return res;
+
+short_packet:
+  {
+    GST_WARNING
+        ("PID 0x%04x section extends past provided data (got:%" G_GSIZE_FORMAT
+        ", need:%d)", pid, data_size, section_length + 3);
+    g_free (data);
+    return NULL;
+  }
+}
+
+/**
+ * gst_wfd_ts_section_packetize:
+ * @section: (transfer none): the #GstWFDTSSection that holds the data
+ * @output_size: (out): #gsize to hold the size of the data
+ *
+ * If the data in @section has aldready been packetized, the data pointer is returned
+ * immediately. Otherwise, the data field is allocated and populated.
+ *
+ * Returns: (transfer none): pointer to section data, or %NULL on fail
+ */
+guint8 *
+gst_wfd_ts_section_packetize (GstWFDTSSection * section, gsize * output_size)
+{
+  guint8 *crc;
+  g_return_val_if_fail (section != NULL, NULL);
+  g_return_val_if_fail (output_size != NULL, NULL);
+  g_return_val_if_fail (section->packetizer != NULL, NULL);
+
+  /* Section data has already been packetized */
+  if (section->data) {
+    *output_size = section->section_length;
+    return section->data;
+  }
+
+  if (!section->packetizer (section))
+    return NULL;
+
+  if (!section->short_section) {
+    /* Update the CRC in the last 4 bytes of the section */
+    crc = section->data + section->section_length - 4;
+    GST_WRITE_UINT32_BE (crc, _calc_crc32 (section->data, crc - section->data));
+  }
+
+  *output_size = section->section_length;
+
+  return section->data;
+}
diff --git a/wfdtsdemux/gstwfdtssection.h b/wfdtsdemux/gstwfdtssection.h
new file mode 100755 (executable)
index 0000000..ad904f0
--- /dev/null
@@ -0,0 +1,405 @@
+/*
+ * wfdtspacketizer.h -
+ * Copyright (C) 2013 Edward Hervey
+ *
+ * Authors:
+ *   Edward Hervey <edward@collabora.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef GST_WFD_TS_SECTION_H
+#define GST_WFD_TS_SECTION_H
+
+#include <gst/gst.h>
+//#include "gstwfdtsdescriptor.h"
+
+G_BEGIN_DECLS
+
+typedef struct _GstWFDTSSection GstWFDTSSection;
+
+#define GST_TYPE_WFD_TS_SECTION (gst_wfd_ts_section_get_type())
+#define GST_WFD_TS_SECTION(section) ((GstWFDTSSection*) section)
+
+#define GST_WFD_TS_SECTION_TYPE(section) (GST_WFD_TS_SECTION (section)->section_type)
+
+GType gst_wfd_ts_section_get_type (void);
+
+/**
+ * GstWFDTSSectionType:
+ * @GST_WFD_TS_SECTION_UNKNOWN: Unknown section type
+ * @GST_WFD_TS_SECTION_PAT: Program Association Table (ISO/IEC 13818-1)
+ * @GST_WFD_TS_SECTION_PMT: Program Map Table (ISO/IEC 13818-1)
+ * @GST_WFD_TS_SECTION_CAT: Conditional Access Table (ISO/IEC 13818-1)
+ * @GST_WFD_TS_SECTION_TSDT: Transport Stream Description Table (ISO/IEC 13818-1)
+ * @GST_WFD_TS_SECTION_EIT: Event Information Table (EN 300 468)
+ * @GST_WFD_TS_SECTION_NIT: Network Information Table (ISO/IEC 13818-1 / EN 300 468)
+ * @GST_WFD_TS_SECTION_BAT: Bouquet Association Table ((EN 300 468)
+ * @GST_WFD_TS_SECTION_SDT: Service Description Table (EN 300 468)
+ * @GST_WFD_TS_SECTION_TDT: Time and Date Table (EN 300 468)
+ * @GST_WFD_TS_SECTION_TOT: Time Offset Table (EN 300 468)
+ * @GST_WFD_TS_SECTION_ATSC_TVCT: ATSC Terrestrial Virtual Channel Table (A65)
+ * @GST_WFD_TS_SECTION_ATSC_CVCT: ATSC Cable Virtual Channel Table (A65)
+ * @GST_WFD_TS_SECTION_ATSC_MGT: ATSC Master Guide Table (A65)
+ * @GST_WFD_TS_SECTION_ATSC_ETT: ATSC Extended Text Table (A65)
+ * @GST_WFD_TS_SECTION_ATSC_EIT: ATSC Event Information Table (A65)
+ * @GST_WFD_TS_SECTION_ATSC_STT: ATSC System Time Table (A65)
+ *
+ * Types of #GstWFDTSSection that the library handles.
+ */
+typedef enum {
+  GST_WFD_TS_SECTION_UNKNOWN           = 0,
+  GST_WFD_TS_SECTION_PAT,
+  GST_WFD_TS_SECTION_PMT,
+  GST_WFD_TS_SECTION_CAT,
+  GST_WFD_TS_SECTION_TSDT,
+  GST_WFD_TS_SECTION_EIT,
+  GST_WFD_TS_SECTION_NIT,
+  GST_WFD_TS_SECTION_BAT,
+  GST_WFD_TS_SECTION_SDT,
+  GST_WFD_TS_SECTION_TDT,
+  GST_WFD_TS_SECTION_TOT,
+  GST_WFD_TS_SECTION_ATSC_TVCT,
+  GST_WFD_TS_SECTION_ATSC_CVCT,
+  GST_WFD_TS_SECTION_ATSC_MGT,
+  GST_WFD_TS_SECTION_ATSC_ETT,
+  GST_WFD_TS_SECTION_ATSC_EIT,
+  GST_WFD_TS_SECTION_ATSC_STT
+} GstWFDTSSectionType;
+
+/**
+ * GstWFDTSSectionTableID:
+ *
+ * Values for a #GstWFDTSSection table_id
+ *
+ * These are the registered ITU H.222.0 | ISO/IEC 13818-1 table_id variants.
+ *
+ * see also #GstWFDTSSectionATSCTableID, #GstWFDTSSectionDVBTableID, and
+ * #GstWFDTSSectionSCTETableID
+ */
+typedef enum {
+  /* ITU H.222.0 / IEC 13818-1 */
+  GST_MTS_TABLE_ID_PROGRAM_ASSOCIATION         = 0x00,
+  GST_MTS_TABLE_ID_CONDITIONAL_ACCESS          = 0x01,
+  GST_MTS_TABLE_ID_TS_PROGRAM_MAP              = 0x02,
+  GST_MTS_TABLE_ID_TS_DESCRIPTION              = 0x03,
+  GST_MTS_TABLE_ID_14496_SCENE_DESCRIPTION     = 0x04,
+  GST_MTS_TABLE_ID_14496_OBJET_DESCRIPTOR      = 0x05,
+  GST_MTS_TABLE_ID_METADATA                    = 0x06,
+  GST_MTS_TABLE_ID_IPMP_CONTROL_INFORMATION    = 0x07,
+
+  /* 0x08 - 0x39 : ITU H.222.0 | ISO/IEC 13818-1 reserved */
+
+  /* IEC 13818-6 (DSM-CC) */
+  GST_MTS_TABLE_ID_DSM_CC_MULTIPROTO_ENCAPSULATED_DATA = 0x3A,
+  GST_MTS_TABLE_ID_DSM_CC_U_N_MESSAGES                 = 0x3B,
+  GST_MTS_TABLE_ID_DSM_CC_DOWNLOAD_DATA_MESSAGES       = 0x3C,
+  GST_MTS_TABLE_ID_DSM_CC_STREAM_DESCRIPTORS           = 0x3D,
+  GST_MTS_TABLE_ID_DSM_CC_PRIVATE_DATA                 = 0x3E,
+  GST_MTS_TABLE_ID_DSM_CC_ADDRESSABLE_SECTIONS         = 0x3F,
+
+  /* Unset */
+  GST_MTS_TABLE_ID_UNSET = 0xFF
+
+} GstWFDTSSectionTableID;
+
+typedef gboolean (*GstWFDTSPacketizeFunc) (GstWFDTSSection *section);
+
+/**
+ * GstWFDTSSection:
+ * @section_type: The type of section
+ * @pid: The pid on which this section was found
+ * @table_id: The table id of this section
+ * @subtable_extension: This meaning differs per section. See the documentation
+ * of the parsed section type for the meaning of this field
+ * @version_number: Version of the section.
+ * @current_next_indicator: Applies to current/next stream or not
+ * @section_number: Number of the section (if multiple)
+ * @last_section_number: Number of the last expected section (if multiple)
+ * @crc: CRC
+ *
+ * Mpeg-TS Section Information (SI) (ISO/IEC 13818-1)
+ */
+struct _GstWFDTSSection
+{
+  /*< private >*/
+  GstMiniObject parent;
+
+  /*< public >*/
+  GstWFDTSSectionType   section_type;
+
+  guint16       pid;
+  guint8        table_id;
+
+  guint16       subtable_extension;
+  guint8        version_number;
+
+  gboolean      current_next_indicator;
+
+  guint8        section_number;
+  guint8        last_section_number;
+
+  guint32       crc;
+
+  /*< private >*/
+  /* data: Points to beginning of section data
+   * i.e. the first byte is the table_id field */
+  guint8       *data;
+  /* section_length: length of data (including final CRC if present) */
+  guint                section_length;
+  /* cached_parsed: cached copy of parsed section */
+  gpointer     *cached_parsed;
+  /* destroy_parsed: function to clear cached_parsed */
+  GDestroyNotify destroy_parsed;
+  /* offset: offset of the section within the container stream */
+  guint64       offset;
+  /* short_section: TRUE if section_syntax_indicator == 0
+   * FIXME : Maybe make public later on when allowing creation of
+   * sections to that people can create private short sections ? */
+  gboolean      short_section;
+  GstWFDTSPacketizeFunc packetizer;
+
+  /* Padding for future extension */
+  gpointer _gst_reserved[GST_PADDING];
+};
+
+GBytes *gst_wfd_ts_section_get_data (GstWFDTSSection *section);
+
+/* PAT */
+#define GST_TYPE_MPEGTS_PAT_PROGRAM (gst_wfd_ts_pat_program_get_type())
+
+typedef struct _GstMpegtsPatProgram GstMpegtsPatProgram;
+/**
+ * GstMpegtsPatProgram:
+ * @program_number: the program number
+ * @network_or_program_map_PID: the network of program map PID
+ *
+ * A program entry from a Program Association Table (ITU H.222.0, ISO/IEC 13818-1).
+ */
+struct _GstMpegtsPatProgram
+{
+  guint16 program_number;
+  guint16 network_or_program_map_PID;
+};
+
+GPtrArray *gst_wfd_ts_section_get_pat (GstWFDTSSection *section);
+GType gst_wfd_ts_pat_program_get_type (void);
+
+GPtrArray *gst_wfd_ts_pat_new (void);
+GstMpegtsPatProgram *gst_wfd_ts_pat_program_new (void);
+GstWFDTSSection *gst_wfd_ts_section_from_pat (GPtrArray * programs,
+    guint16 ts_id);
+
+/* CAT */
+
+GPtrArray *gst_wfd_ts_section_get_cat (GstWFDTSSection *section);
+
+/* PMT */
+typedef struct _GstWFDTSPMTStream GstWFDTSPMTStream;
+typedef struct _GstWFDTSPMT GstWFDTSPMT;
+#define GST_TYPE_WFD_TS_PMT (gst_wfd_ts_pmt_get_type())
+#define GST_TYPE_WFD_TS_PMT_STREAM (gst_wfd_ts_pmt_stream_get_type())
+
+/**
+ * GstMpegtsStreamType:
+ * @GST_WFD_TS_STREAM_TYPE_RESERVED_00: ITU-T | ISO/IEC Reserved
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG1: ISO/IEC 11172-2 Video
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG2: Rec. ITU-T H.262 | ISO/IEC 13818-2
+ * Video or ISO/IEC 11172-2 constrained parameter video stream
+ * @GST_WFD_TS_STREAM_TYPE_AUDIO_MPEG1: ISO/IEC 11172-3 Audio
+ * @GST_WFD_TS_STREAM_TYPE_AUDIO_MPEG2: ISO/IEC 13818-3 Audio
+ * @GST_WFD_TS_STREAM_TYPE_PRIVATE_SECTIONS: private sections
+ * @GST_WFD_TS_STREAM_TYPE_PRIVATE_PES_PACKETS: PES packets containing private data
+ * @GST_WFD_TS_STREAM_TYPE_MHEG: ISO/IEC 13522 MHEG
+ * @GST_WFD_TS_STREAM_TYPE_DSM_CC: Annex A DSM-CC
+ * @GST_WFD_TS_STREAM_TYPE_H_222_1: Rec. ITU-T H.222.1
+ * @GST_WFD_TS_STREAM_TYPE_DSMCC_A: ISO/IEC 13818-6 type A
+ * @GST_WFD_TS_STREAM_TYPE_DSMCC_B: ISO/IEC 13818-6 type B
+ * @GST_WFD_TS_STREAM_TYPE_DSMCC_C: ISO/IEC 13818-6 type C
+ * @GST_WFD_TS_STREAM_TYPE_DSMCC_D: ISO/IEC 13818-6 type D
+ * @GST_WFD_TS_STREAM_TYPE_AUXILIARY: auxiliary streams
+ * @GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_ADTS: ISO/IEC 13818-7 Audio with ADTS
+ * transport syntax
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG4: ISO/IEC 14496-2 Visual
+ * @GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_LATM: ISO/IEC 14496-3 Audio with the LATM
+ * transport syntax as defined in ISO/IEC 14496-3
+ * @GST_WFD_TS_STREAM_TYPE_SL_FLEXMUX_PES_PACKETS: ISO/IEC 14496-1
+ * SL-packetized stream or FlexMux stream carried in PES packets
+ * @GST_WFD_TS_STREAM_TYPE_SL_FLEXMUX_SECTIONS: ISO/IEC 14496-1 SL-packetized
+ * stream or FlexMux stream carried in ISO/IEC 14496_sections
+ * @GST_WFD_TS_STREAM_TYPE_SYNCHRONIZED_DOWNLOAD: ISO/IEC 13818-6 Synchronized
+ * Download Protocol
+ * @GST_WFD_TS_STREAM_TYPE_METADATA_PES_PACKETS: Metadata carried in PES packets
+ * @GST_WFD_TS_STREAM_TYPE_METADATA_SECTIONS: Metadata carried in metadata_sections
+ * @GST_WFD_TS_STREAM_TYPE_METADATA_DATA_CAROUSEL: Metadata carried in ISO/IEC
+ * 13818-6 Data Carousel
+ * @GST_WFD_TS_STREAM_TYPE_METADATA_OBJECT_CAROUSEL: Metadata carried in
+ * ISO/IEC 13818-6 Object Carousel
+ * @GST_WFD_TS_STREAM_TYPE_METADATA_SYNCHRONIZED_DOWNLOAD: Metadata carried in
+ * ISO/IEC 13818-6 Synchronized Download Protocol
+ * @GST_WFD_TS_STREAM_TYPE_MPEG2_IPMP: IPMP stream (defined in ISO/IEC 13818-11,
+ * MPEG-2 IPMP)
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_H264: AVC video stream conforming to one or
+ * more profiles defined in Annex A of Rec. ITU-T H.264 | ISO/IEC 14496-10 or
+ * AVC video sub-bitstream of SVC as defined in 2.1.78 or MVC base view
+ * sub-bitstream, as defined in 2.1.85, or AVC video sub-bitstream of MVC, as
+ * defined in 2.1.88
+ * @GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_CLEAN: ISO/IEC 14496-3 Audio, without
+ * using any additional transport syntax, such as DST, ALS and SLS
+ * @GST_WFD_TS_STREAM_TYPE_MPEG4_TIMED_TEXT: ISO/IEC 14496-17 Text
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_RVC: Auxiliary video stream as defined in
+ * ISO/IEC 23002-3
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_H264_SVC_SUB_BITSTREAM: SVC video sub-bitstream
+ * of an AVC video stream conforming to one or more profiles defined in Annex G
+ * of Rec. ITU-T H.264 | ISO/IEC 14496-10
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_H264_MVC_SUB_BITSTREAM: MVC video sub-bitstream
+ * of an AVC video stream conforming to one or more profiles defined in Annex H
+ * of Rec. ITU-T H.264 | ISO/IEC 14496-10
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_JP2K: Video stream conforming to one or more
+ * profiles as defined in Rec. ITU-T T.800 | ISO/IEC 15444-1
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG2_STEREO_ADDITIONAL_VIEW: Additional view
+ * Rec. ITU-T H.262 | ISO/IEC 13818-2 video stream for service-compatible
+ * stereoscopic 3D services
+ * @GST_WFD_TS_STREAM_TYPE_VIDEO_H264_STEREO_ADDITIONAL_VIEW: Additional view
+ * Rec. ITU-T H.264 | ISO/IEC 14496-10 video stream conforming to one or more
+ * profiles defined in Annex A for service-compatible stereoscopic 3D services
+ * @GST_WFD_TS_STREAM_TYPE_IPMP_STREAM: IPMP stream
+ *
+ * Type of mpeg-ts stream type.
+ *
+ * These values correspond to the base standard registered types. Depending
+ * on the variant of mpeg-ts being used (Bluray, ATSC, DVB, ...), other
+ * types might also be used, but will not conflict with these.
+ *
+ * Corresponds to table 2-34 of ITU H.222.0 | ISO/IEC 13818-1
+ */
+typedef enum {
+  GST_WFD_TS_STREAM_TYPE_RESERVED_00                  = 0x00,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG1                  = 0x01,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG2                  = 0x02,
+  GST_WFD_TS_STREAM_TYPE_AUDIO_MPEG1                  = 0x03,
+  GST_WFD_TS_STREAM_TYPE_AUDIO_MPEG2                  = 0x04,
+  GST_WFD_TS_STREAM_TYPE_PRIVATE_SECTIONS             = 0x05,
+  GST_WFD_TS_STREAM_TYPE_PRIVATE_PES_PACKETS          = 0x06,
+  GST_WFD_TS_STREAM_TYPE_MHEG                         = 0x07,
+  GST_WFD_TS_STREAM_TYPE_DSM_CC                       = 0x08,
+  GST_WFD_TS_STREAM_TYPE_H_222_1                      = 0x09,
+  GST_WFD_TS_STREAM_TYPE_DSMCC_A                      = 0x0a,
+  GST_WFD_TS_STREAM_TYPE_DSMCC_B                      = 0x0b,
+  GST_WFD_TS_STREAM_TYPE_DSMCC_C                      = 0x0c,
+  GST_WFD_TS_STREAM_TYPE_DSMCC_D                      = 0x0d,
+  GST_WFD_TS_STREAM_TYPE_AUXILIARY                    = 0x0e,
+  GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_ADTS               = 0x0f,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG4                  = 0x10,
+  GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_LATM               = 0x11,
+  GST_WFD_TS_STREAM_TYPE_SL_FLEXMUX_PES_PACKETS       = 0x12,
+  GST_WFD_TS_STREAM_TYPE_SL_FLEXMUX_SECTIONS          = 0x13,
+  GST_WFD_TS_STREAM_TYPE_SYNCHRONIZED_DOWNLOAD        = 0x14,
+  GST_WFD_TS_STREAM_TYPE_METADATA_PES_PACKETS         = 0x15,
+  GST_WFD_TS_STREAM_TYPE_METADATA_SECTIONS            = 0x16,
+  GST_WFD_TS_STREAM_TYPE_METADATA_DATA_CAROUSEL       = 0x17,
+  GST_WFD_TS_STREAM_TYPE_METADATA_OBJECT_CAROUSEL     = 0x18,
+  GST_WFD_TS_STREAM_TYPE_METADATA_SYNCHRONIZED_DOWNLOAD  = 0x19,
+  GST_WFD_TS_STREAM_TYPE_MPEG2_IPMP                   = 0x1a,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_H264                   = 0x1b,
+  GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_CLEAN              = 0x1c,
+  GST_WFD_TS_STREAM_TYPE_MPEG4_TIMED_TEXT             = 0x1d,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_RVC                    = 0x1e,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_H264_SVC_SUB_BITSTREAM = 0x1f,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_H264_MVC_SUB_BITSTREAM = 0x20,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_JP2K                   = 0x21,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_MPEG2_STEREO_ADDITIONAL_VIEW = 0x22,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_H264_STEREO_ADDITIONAL_VIEW  = 0x23,
+  GST_WFD_TS_STREAM_TYPE_VIDEO_HEVC                   = 0x24,
+  /* 0x24 - 0x7e : Rec. ITU-T H.222.0 | ISO/IEC 13818-1 Reserved */
+  GST_WFD_TS_STREAM_TYPE_IPMP_STREAM                  = 0x7f
+  /* 0x80 - 0xff : User Private (or defined in other specs) */
+} GstMpegtsStreamType;
+
+/**
+ * GstWFDTSPMTStream:
+ * @stream_type: the type of stream. See #GstMpegtsStreamType
+ * @pid: the PID of the stream
+ * @descriptors: (element-type GstMpegtsDescriptor): the descriptors of the
+ * stream
+ *
+ * An individual stream definition.
+ */
+struct _GstWFDTSPMTStream
+{
+  guint8      stream_type;
+  guint16     pid;
+
+  GPtrArray  *descriptors;
+};
+
+/**
+ * GstWFDTSPMT:
+ * @pcr_pid: PID of the stream containing PCR
+ * @descriptors: (element-type GstMpegtsDescriptor): array of #GstMpegtsDescriptor
+ * @streams: (element-type GstWFDTSPMTStream): Array of #GstWFDTSPMTStream
+ *
+ * Program Map Table (ISO/IEC 13818-1).
+ *
+ * The program_number is contained in the subtable_extension field of the
+ * container #GstWFDTSSection.
+ */
+struct _GstWFDTSPMT
+{
+  guint16    pcr_pid;
+  guint16    program_number;
+
+  GPtrArray *descriptors;
+  GPtrArray *streams;
+};
+
+GType gst_wfd_ts_pmt_get_type (void);
+GType gst_wfd_ts_pmt_stream_get_type (void);
+
+GstWFDTSPMT *gst_wfd_ts_pmt_new (void);
+GstWFDTSPMTStream *gst_wfd_ts_pmt_stream_new (void);
+const GstWFDTSPMT *gst_wfd_ts_section_get_pmt (GstWFDTSSection *section);
+GstWFDTSSection *gst_wfd_ts_section_from_pmt (GstWFDTSPMT *pmt, guint16 pid);
+
+/* TSDT */
+
+GPtrArray *gst_wfd_ts_section_get_tsdt (GstWFDTSSection *section);
+
+
+/* generic */
+
+#define gst_wfd_ts_section_ref(section)   ((GstWFDTSSection*) gst_mini_object_ref (GST_MINI_OBJECT_CAST (section)))
+#define gst_wfd_ts_section_unref(section) (gst_mini_object_unref (GST_MINI_OBJECT_CAST (section)))
+
+GstMessage *gst_message_new_wfd_ts_section (GstObject *parent, GstWFDTSSection *section);
+gboolean gst_wfd_ts_section_send_event (GstWFDTSSection * section, GstElement * element);
+GstWFDTSSection *gst_event_parse_wfd_ts_section (GstEvent * event);
+
+GstWFDTSSection *gst_message_parse_wfd_ts_section (GstMessage *message);
+
+GstWFDTSSection *gst_wfd_ts_section_new (guint16 pid,
+                                          guint8 * data,
+                                          gsize data_size);
+
+guint8 *gst_wfd_ts_section_packetize (GstWFDTSSection * section, gsize * output_size);
+
+
+void gst_wfd_ts_initialize (void);
+
+
+G_END_DECLS
+
+#endif                         /* GST_WFD_TS_SECTION_H */
diff --git a/wfdtsdemux/wfdnalutils.c b/wfdtsdemux/wfdnalutils.c
new file mode 100755 (executable)
index 0000000..9bac543
--- /dev/null
@@ -0,0 +1,312 @@
+/* Gstreamer
+ * Copyright (C) <2011> Intel Corporation
+ * Copyright (C) <2011> Collabora Ltd.
+ * Copyright (C) <2011> Thibault Saunier <thibault.saunier@collabora.com>
+ *
+ * Some bits C-c,C-v'ed and s/4/3 from h264parse and videoparsers/h264parse.c:
+ *    Copyright (C) <2010> Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>
+ *    Copyright (C) <2010> Collabora Multimedia
+ *    Copyright (C) <2010> Nokia Corporation
+ *
+ *    (C) 2005 Michal Benes <michal.benes@itonis.tv>
+ *    (C) 2008 Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+/**
+ * Common code for NAL parsing from h264 and h265 parsers.
+ */
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#include "wfdnalutils.h"
+
+/* Compute Ceil(Log2(v)) */
+/* Derived from branchless code for integer log2(v) from:
+   <http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog> */
+guint
+ceil_log2 (guint32 v)
+{
+  guint r, shift;
+
+  v--;
+  r = (v > 0xFFFF) << 4;
+  v >>= r;
+  shift = (v > 0xFF) << 3;
+  v >>= shift;
+  r |= shift;
+  shift = (v > 0xF) << 2;
+  v >>= shift;
+  r |= shift;
+  shift = (v > 0x3) << 1;
+  v >>= shift;
+  r |= shift;
+  r |= (v >> 1);
+  return r + 1;
+}
+
+/****** Nal parser ******/
+
+void
+wfd_nal_reader_init (WFDNalReader * nr, const guint8 * data, guint size)
+{
+  nr->data = data;
+  nr->size = size;
+  nr->n_epb = 0;
+
+  nr->byte = 0;
+  nr->bits_in_cache = 0;
+  /* fill with something other than 0 to detect emulation prevention bytes */
+  nr->first_byte = 0xff;
+  nr->cache = 0xff;
+}
+
+inline gboolean
+wfd_nal_reader_read (WFDNalReader * nr, guint nbits)
+{
+  if (G_UNLIKELY (nr->byte * 8 + (nbits - nr->bits_in_cache) > nr->size * 8)) {
+    GST_DEBUG ("Can not read %u bits, bits in cache %u, Byte * 8 %u, size in "
+        "bits %u", nbits, nr->bits_in_cache, nr->byte * 8, nr->size * 8);
+    return FALSE;
+  }
+
+  while (nr->bits_in_cache < nbits) {
+    guint8 byte;
+    gboolean check_three_byte;
+
+    check_three_byte = TRUE;
+  next_byte:
+    if (G_UNLIKELY (nr->byte >= nr->size))
+      return FALSE;
+
+    byte = nr->data[nr->byte++];
+
+    /* check if the byte is a emulation_prevention_three_byte */
+    if (check_three_byte && byte == 0x03 && nr->first_byte == 0x00 &&
+        ((nr->cache & 0xff) == 0)) {
+      /* next byte goes unconditionally to the cache, even if it's 0x03 */
+      check_three_byte = FALSE;
+      nr->n_epb++;
+      goto next_byte;
+    }
+    nr->cache = (nr->cache << 8) | nr->first_byte;
+    nr->first_byte = byte;
+    nr->bits_in_cache += 8;
+  }
+
+  return TRUE;
+}
+
+/* Skips the specified amount of bits. This is only suitable to a
+   cacheable number of bits */
+inline gboolean
+wfd_nal_reader_skip (WFDNalReader * nr, guint nbits)
+{
+  g_assert (nbits <= 8 * sizeof (nr->cache));
+
+  if (G_UNLIKELY (!wfd_nal_reader_read (nr, nbits)))
+    return FALSE;
+
+  nr->bits_in_cache -= nbits;
+
+  return TRUE;
+}
+
+/* Generic version to skip any number of bits */
+gboolean
+wfd_nal_reader_skip_long (WFDNalReader * nr, guint nbits)
+{
+  /* Leave out enough bits in the cache once we are finished */
+  const guint skip_size = 4 * sizeof (nr->cache);
+  guint remaining = nbits;
+
+  nbits %= skip_size;
+  while (remaining > 0) {
+    if (!wfd_nal_reader_skip (nr, nbits))
+      return FALSE;
+    remaining -= nbits;
+    nbits = skip_size;
+  }
+  return TRUE;
+}
+
+inline guint
+wfd_nal_reader_get_pos (const WFDNalReader * nr)
+{
+  return nr->byte * 8 - nr->bits_in_cache;
+}
+
+inline guint
+wfd_nal_reader_get_remaining (const WFDNalReader * nr)
+{
+  return (nr->size - nr->byte) * 8 + nr->bits_in_cache;
+}
+
+inline guint
+wfd_nal_reader_get_epb_count (const WFDNalReader * nr)
+{
+  return nr->n_epb;
+}
+
+#define WFD_NAL_READER_READ_BITS(bits) \
+gboolean \
+wfd_nal_reader_get_bits_uint##bits (WFDNalReader *nr, guint##bits *val, guint nbits) \
+{ \
+  guint shift; \
+  \
+  if (!wfd_nal_reader_read (nr, nbits)) \
+    return FALSE; \
+  \
+  /* bring the required bits down and truncate */ \
+  shift = nr->bits_in_cache - nbits; \
+  *val = nr->first_byte >> shift; \
+  \
+  *val |= nr->cache << (8 - shift); \
+  /* mask out required bits */ \
+  if (nbits < bits) \
+    *val &= ((guint##bits)1 << nbits) - 1; \
+  \
+  nr->bits_in_cache = shift; \
+  \
+  return TRUE; \
+} \
+
+WFD_NAL_READER_READ_BITS (8);
+WFD_NAL_READER_READ_BITS (16);
+WFD_NAL_READER_READ_BITS (32);
+
+#define WFD_NAL_READER_PEEK_BITS(bits) \
+gboolean \
+wfd_nal_reader_peek_bits_uint##bits (const WFDNalReader *nr, guint##bits *val, guint nbits) \
+{ \
+  WFDNalReader tmp; \
+  \
+  tmp = *nr; \
+  return wfd_nal_reader_get_bits_uint##bits (&tmp, val, nbits); \
+}
+
+WFD_NAL_READER_PEEK_BITS (8);
+
+gboolean
+wfd_nal_reader_get_ue (WFDNalReader * nr, guint32 * val)
+{
+  guint i = 0;
+  guint8 bit;
+  guint32 value;
+
+  if (G_UNLIKELY (!wfd_nal_reader_get_bits_uint8 (nr, &bit, 1))) {
+
+    return FALSE;
+  }
+
+  while (bit == 0) {
+    i++;
+    if G_UNLIKELY
+      ((!wfd_nal_reader_get_bits_uint8 (nr, &bit, 1)))
+          return FALSE;
+  }
+
+  if (G_UNLIKELY (i > 32))
+    return FALSE;
+
+  if (G_UNLIKELY (!wfd_nal_reader_get_bits_uint32 (nr, &value, i)))
+    return FALSE;
+
+  *val = (1 << i) - 1 + value;
+
+  return TRUE;
+}
+
+inline gboolean
+wfd_nal_reader_get_se (WFDNalReader * nr, gint32 * val)
+{
+  guint32 value;
+
+  if (G_UNLIKELY (!wfd_nal_reader_get_ue (nr, &value)))
+    return FALSE;
+
+  if (value % 2)
+    *val = (value / 2) + 1;
+  else
+    *val = -(value / 2);
+
+  return TRUE;
+}
+
+gboolean
+wfd_nal_reader_is_byte_aligned (WFDNalReader * nr)
+{
+  if (nr->bits_in_cache != 0)
+    return FALSE;
+  return TRUE;
+}
+
+gboolean
+wfd_nal_reader_has_more_data (WFDNalReader * nr)
+{
+  WFDNalReader nr_tmp;
+  guint remaining, nbits;
+  guint8 rbsp_stop_one_bit, zero_bits;
+
+  remaining = wfd_nal_reader_get_remaining (nr);
+  if (remaining == 0)
+    return FALSE;
+
+  nr_tmp = *nr;
+  nr = &nr_tmp;
+
+  /* The spec defines that more_rbsp_data() searches for the last bit
+     equal to 1, and that it is the rbsp_stop_one_bit. Subsequent bits
+     until byte boundary is reached shall be zero.
+
+     This means that more_rbsp_data() is FALSE if the next bit is 1
+     and the remaining bits until byte boundary are zero. One way to
+     be sure that this bit was the very last one, is that every other
+     bit after we reached byte boundary are also set to zero.
+     Otherwise, if the next bit is 0 or if there are non-zero bits
+     afterwards, then then we have more_rbsp_data() */
+  if (!wfd_nal_reader_get_bits_uint8 (nr, &rbsp_stop_one_bit, 1))
+    return FALSE;
+  if (!rbsp_stop_one_bit)
+    return TRUE;
+
+  nbits = --remaining % 8;
+  while (remaining > 0) {
+    if (!wfd_nal_reader_get_bits_uint8 (nr, &zero_bits, nbits))
+      return FALSE;
+    if (zero_bits != 0)
+      return TRUE;
+    remaining -= nbits;
+    nbits = 8;
+  }
+  return FALSE;
+}
+
+/***********  end of nal parser ***************/
+
+inline gint
+scan_for_start_codes (const guint8 * data, guint size)
+{
+  GstByteReader br;
+  gst_byte_reader_init (&br, data, size);
+
+  /* NALU not empty, so we can at least expect 1 (even 2) bytes following sc */
+  return gst_byte_reader_masked_scan_uint32 (&br, 0xffffff00, 0x00000100,
+      0, size);
+}
diff --git a/wfdtsdemux/wfdnalutils.h b/wfdtsdemux/wfdnalutils.h
new file mode 100755 (executable)
index 0000000..f63a8ec
--- /dev/null
@@ -0,0 +1,147 @@
+/* Gstreamer
+ * Copyright (C) <2011> Intel Corporation
+ * Copyright (C) <2011> Collabora Ltd.
+ * Copyright (C) <2011> Thibault Saunier <thibault.saunier@collabora.com>
+ *
+ * Some bits C-c,C-v'ed and s/4/3 from h264parse and videoparsers/h264parse.c:
+ *    Copyright (C) <2010> Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>
+ *    Copyright (C) <2010> Collabora Multimedia
+ *    Copyright (C) <2010> Nokia Corporation
+ *
+ *    (C) 2005 Michal Benes <michal.benes@itonis.tv>
+ *    (C) 2008 Wim Taymans <wim.taymans@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+/**
+ * Common code for NAL parsing from h264 and h265 parsers.
+ */
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#include <gst/base/gstbytereader.h>
+#include <gst/base/gstbitreader.h>
+#include <string.h>
+
+guint ceil_log2 (guint32 v);
+
+typedef struct
+{
+  const guint8 *data;
+  guint size;
+
+  guint n_epb;                  /* Number of emulation prevention bytes */
+  guint byte;                   /* Byte position */
+  guint bits_in_cache;          /* bitpos in the cache of next bit */
+  guint8 first_byte;
+  guint64 cache;                /* cached bytes */
+} WFDNalReader;
+
+void wfd_nal_reader_init (WFDNalReader * nr, const guint8 * data, guint size);
+
+gboolean wfd_nal_reader_read (WFDNalReader * nr, guint nbits);
+gboolean wfd_nal_reader_skip (WFDNalReader * nr, guint nbits);
+gboolean wfd_nal_reader_skip_long (WFDNalReader * nr, guint nbits);
+guint wfd_nal_reader_get_pos (const WFDNalReader * nr);
+guint wfd_nal_reader_get_remaining (const WFDNalReader * nr);
+guint wfd_nal_reader_get_epb_count (const WFDNalReader * nr);
+
+gboolean wfd_nal_reader_is_byte_aligned (WFDNalReader * nr);
+gboolean wfd_nal_reader_has_more_data (WFDNalReader * nr);
+
+#define WFD_NAL_READER_READ_BITS_H(bits) \
+gboolean wfd_nal_reader_get_bits_uint##bits (WFDNalReader *nr, guint##bits *val, guint nbits)
+
+WFD_NAL_READER_READ_BITS_H (8);
+WFD_NAL_READER_READ_BITS_H (16);
+WFD_NAL_READER_READ_BITS_H (32);
+
+#define WFD_NAL_READER_PEEK_BITS_H(bits) \
+gboolean wfd_nal_reader_peek_bits_uint##bits (const WFDNalReader *nr, guint##bits *val, guint nbits)
+
+WFD_NAL_READER_PEEK_BITS_H (8);
+
+gboolean wfd_nal_reader_get_ue (WFDNalReader * nr, guint32 * val);
+gboolean wfd_nal_reader_get_se (WFDNalReader * nr, gint32 * val);
+
+#define CHECK_ALLOWED(val, min, max) { \
+  if (val < min || val > max) { \
+    GST_WARNING ("value not in allowed range. value: %d, range %d-%d", \
+                     val, min, max); \
+    goto error; \
+  } \
+}
+
+#define READ_UINT8(nr, val, nbits) { \
+  if (!wfd_nal_reader_get_bits_uint8 (nr, &val, nbits)) { \
+    GST_WARNING ("failed to read uint8, nbits: %d", nbits); \
+    goto error; \
+  } \
+}
+
+#define READ_UINT16(nr, val, nbits) { \
+  if (!wfd_nal_reader_get_bits_uint16 (nr, &val, nbits)) { \
+  GST_WARNING ("failed to read uint16, nbits: %d", nbits); \
+    goto error; \
+  } \
+}
+
+#define READ_UINT32(nr, val, nbits) { \
+  if (!wfd_nal_reader_get_bits_uint32 (nr, &val, nbits)) { \
+  GST_WARNING ("failed to read uint32, nbits: %d", nbits); \
+    goto error; \
+  } \
+}
+
+#define READ_UINT64(nr, val, nbits) { \
+  if (!wfd_nal_reader_get_bits_uint64 (nr, &val, nbits)) { \
+    GST_WARNING ("failed to read uint32, nbits: %d", nbits); \
+    goto error; \
+  } \
+}
+
+#define READ_UE(nr, val) { \
+  if (!wfd_nal_reader_get_ue (nr, &val)) { \
+    GST_WARNING ("failed to read UE"); \
+    goto error; \
+  } \
+}
+
+#define READ_UE_ALLOWED(nr, val, min, max) { \
+  guint32 tmp; \
+  READ_UE (nr, tmp); \
+  CHECK_ALLOWED (tmp, min, max); \
+  val = tmp; \
+}
+
+#define READ_SE(nr, val) { \
+  if (!wfd_nal_reader_get_se (nr, &val)) { \
+    GST_WARNING ("failed to read SE"); \
+    goto error; \
+  } \
+}
+
+#define READ_SE_ALLOWED(nr, val, min, max) { \
+  gint32 tmp; \
+  READ_SE (nr, tmp); \
+  CHECK_ALLOWED (tmp, min, max); \
+  val = tmp; \
+}
+
+gint scan_for_start_codes (const guint8 * data, guint size);
diff --git a/wfdtsdemux/wfdpesparse.c b/wfdtsdemux/wfdpesparse.c
new file mode 100755 (executable)
index 0000000..493674e
--- /dev/null
@@ -0,0 +1,474 @@
+/*
+ * pesparse.c : MPEG PES parsing utility
+ * Copyright (C) 2011 Edward Hervey <bilboed@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <glib.h>
+
+#include "wfdpesparse.h"
+
+GST_DEBUG_CATEGORY_STATIC (wfd_pes_parser_debug);
+#define GST_CAT_DEFAULT wfd_pes_parser_debug
+
+/**
+ * wfd_ts_parse_pes_header:
+ * @data: data to parse (starting from, and including, the sync code)
+ * @length: size of @data in bytes
+ * @res: WFDPESHeader to fill (only valid with #PES_PARSING_OK.
+ *
+ * Parses the mpeg-ts PES header located in @data into the @res.
+ *
+ * Returns: #PES_PARSING_OK if the header was fully parsed and valid,
+ * #PES_PARSING_BAD if the header is invalid, or #PES_PARSING_NEED_MORE if more data
+ * is needed to properly parse the header.
+ */
+WFDPESParsingResult
+wfd_ts_parse_pes_header (const guint8 * data, gsize length, WFDPESHeader * res)
+{
+  WFDPESParsingResult ret = PES_PARSING_NEED_MORE;
+  gsize origlength = length;
+  const guint8 *origdata = data;
+  guint32 val32;
+  guint8 val8, flags;
+
+  g_return_val_if_fail (res != NULL, PES_PARSING_BAD);
+
+  /* The smallest valid PES header is 6 bytes (prefix + stream_id + length) */
+  if (G_UNLIKELY (length < 6))
+    goto need_more_data;
+
+  val32 = GST_READ_UINT32_BE (data);
+  data += 4;
+  length -= 4;
+  if (G_UNLIKELY ((val32 & 0xffffff00) != 0x00000100))
+    goto bad_start_code;
+
+  /* Clear the header */
+  memset (res, 0, sizeof (WFDPESHeader));
+  res->PTS = -1;
+  res->DTS = -1;
+  res->ESCR = -1;
+#ifdef WFD_SPEC
+  res->is_lpcm = FALSE;
+#endif
+
+  res->stream_id = val32 & 0x000000ff;
+
+  res->packet_length = GST_READ_UINT16_BE (data);
+  if (res->packet_length)
+    res->packet_length += 6;
+  data += 2;
+  length -= 2;
+
+  GST_LOG ("stream_id : 0x%08x , packet_length : %d", res->stream_id,
+      res->packet_length);
+
+  /* Jump if we don't need to parse anything more */
+  if (G_UNLIKELY (res->stream_id == 0xbc || res->stream_id == 0xbe
+          || res->stream_id == 0xbf || (res->stream_id >= 0xf0
+              && res->stream_id <= 0xf2) || res->stream_id == 0xff
+          || res->stream_id == 0xf8))
+    goto done_parsing;
+
+  if (G_UNLIKELY (length < 3))
+    goto need_more_data;
+
+  /* '10'                             2
+   * PES_scrambling_control           2
+   * PES_priority                     1
+   * data_alignment_indicator         1
+   * copyright                        1
+   * original_or_copy                 1 */
+  val8 = *data++;
+  if (G_UNLIKELY ((val8 & 0xc0) != 0x80))
+    goto bad_marker_1;
+  res->scrambling_control = (val8 >> 4) & 0x3;
+  res->flags = val8 & 0xf;
+
+  GST_LOG ("scrambling_control 0x%0x", res->scrambling_control);
+  GST_LOG ("flags_1: %s%s%s%s%s",
+      val8 & 0x08 ? "priority " : "",
+      val8 & 0x04 ? "data_alignment " : "",
+      val8 & 0x02 ? "copyright " : "",
+      val8 & 0x01 ? "original_or_copy " : "", val8 & 0x0f ? "" : "<none>");
+
+  /* PTS_DTS_flags                    2
+   * ESCR_flag                        1
+   * ES_rate_flag                     1
+   * DSM_trick_mode_flag              1
+   * additional_copy_info_flag        1
+   * PES_CRC_flag                     1
+   * PES_extension_flag               1*/
+  flags = *data++;
+  GST_LOG ("flags_2: %s%s%s%s%s%s%s%s%s",
+      flags & 0x80 ? "PTS " : "",
+      flags & 0x40 ? "DTS " : "",
+      flags & 0x20 ? "ESCR" : "",
+      flags & 0x10 ? "ES_rate " : "",
+      flags & 0x08 ? "DSM_trick_mode " : "",
+      flags & 0x04 ? "additional_copy_info " : "",
+      flags & 0x02 ? "CRC " : "",
+      flags & 0x01 ? "extension " : "", flags ? "" : "<none>");
+
+  /* PES_header_data_length           8 */
+  res->header_size = *data++;
+  length -= 3;
+  if (G_UNLIKELY (length < res->header_size))
+    goto need_more_data;
+
+  res->header_size += 9;        /* We add 9 since that's the offset
+                                 * of the field in the header*/
+
+  /* PTS/DTS */
+  /* PTS_DTS_flags == 0x01 is invalid */
+  if (G_UNLIKELY ((flags >> 6) == 0x01)) {
+    GST_WARNING ("Invalid PTS_DTS_flag (0x01 is forbidden)");
+  }
+
+  if ((flags & 0x80) == 0x80) {
+    /* PTS */
+    if (G_UNLIKELY (length < 5))
+      goto need_more_data;
+
+    READ_TS (data, res->PTS, bad_PTS_value);
+    length -= 5;
+    GST_LOG ("PTS %" G_GUINT64_FORMAT " %" GST_TIME_FORMAT,
+        res->PTS, GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (res->PTS)));
+
+  }
+
+  if ((flags & 0x40) == 0x40) {
+    /* DTS */
+    if (G_UNLIKELY (length < 5))
+      goto need_more_data;
+
+    READ_TS (data, res->DTS, bad_DTS_value);
+    length -= 5;
+
+    GST_LOG ("DTS %" G_GUINT64_FORMAT " %" GST_TIME_FORMAT,
+        res->DTS, GST_TIME_ARGS (MPEGTIME_TO_GSTTIME (res->DTS)));
+  }
+
+  if (flags & 0x20) {
+    /* ESCR */
+    if (G_UNLIKELY (length < 5))
+      goto need_more_data;
+    READ_TS (data, res->ESCR, bad_ESCR_value);
+    length -= 5;
+
+    GST_LOG ("ESCR %" G_GUINT64_FORMAT " %" GST_TIME_FORMAT,
+        res->ESCR, GST_TIME_ARGS (PCRTIME_TO_GSTTIME (res->ESCR)));
+  }
+
+  if (flags & 0x10) {
+    /* ES_rate */
+    if (G_UNLIKELY (length < 3))
+      goto need_more_data;
+    val32 = GST_READ_UINT32_BE (data);
+    data += 3;
+    length -= 3;
+    if (G_UNLIKELY ((val32 & 0x80000100) != 0x80000100))
+      goto bad_ES_rate;
+    res->ES_rate = ((val32 >> 9) & 0x003fffff) * 50;
+    GST_LOG ("ES_rate : %d", res->ES_rate);
+  }
+
+  if (flags & 0x08) {
+    /* DSM trick mode */
+    if (G_UNLIKELY (length < 1))
+      goto need_more_data;
+    val8 = *data++;
+    length -= 1;
+
+    res->trick_mode = val8 >> 5;
+    GST_LOG ("trick_mode 0x%x", res->trick_mode);
+
+    switch (res->trick_mode) {
+      case PES_TRICK_MODE_FAST_FORWARD:
+      case PES_TRICK_MODE_FAST_REVERSE:
+        res->intra_slice_refresh = (val8 >> 2) & 0x1;
+        res->frequency_truncation = val8 & 0x3;
+        /* passthrough */
+      case PES_TRICK_MODE_FREEZE_FRAME:
+        res->field_id = (val8 >> 3) & 0x3;
+        break;
+      case PES_TRICK_MODE_SLOW_MOTION:
+      case PES_TRICK_MODE_SLOW_REVERSE:
+        res->rep_cntrl = val8 & 0x1f;
+        break;
+      default:
+        break;
+    }
+  }
+
+  if (flags & 0x04) {
+    /* additional copy info */
+    if (G_UNLIKELY (length < 1))
+      goto need_more_data;
+    val8 = *data++;
+    length -= 1;
+
+    if (G_UNLIKELY (!(val8 & 0x80)))
+      goto bad_original_copy_info_marker;
+    res->additional_copy_info = val8 & 0x7f;
+    GST_LOG ("additional_copy_info : 0x%x", res->additional_copy_info);
+  }
+
+  if (flags & 0x02) {
+    /* CRC */
+    if (G_UNLIKELY (length < 2))
+      goto need_more_data;
+    res->previous_PES_packet_CRC = GST_READ_UINT16_BE (data);
+    GST_LOG ("previous_PES_packet_CRC : 0x%x", res->previous_PES_packet_CRC);
+    data += 2;
+    length -= 2;
+  }
+
+
+  /* jump if we don't have a PES extension */
+  if (!(flags & 0x01))
+    goto stuffing_byte;
+
+  if (G_UNLIKELY (length < 1))
+    goto need_more_data;
+
+  /* PES extension */
+  flags = *data++;
+  length -= 1;
+  GST_DEBUG ("PES_extension_flag: %s%s%s%s%s%s",
+      flags & 0x80 ? "PES_private_data " : "",
+      flags & 0x40 ? "pack_header_field " : "",
+      flags & 0x20 ? "program_packet_sequence_counter " : "",
+      flags & 0x10 ? "P-STD_buffer " : "",
+      flags & 0x01 ? "PES_extension_flag_2" : "", flags & 0xf1 ? "" : "<none>");
+
+  if (flags & 0x80) {
+    /* PES_private data */
+    if (G_UNLIKELY (length < 16))
+      goto need_more_data;
+    res->private_data = data;
+    GST_MEMDUMP ("private_data", data, 16);
+    data += 16;
+    length -= 16;
+  }
+
+  if (flags & 0x40) {
+    /* pack_header_field */
+    if (G_UNLIKELY (length < 1))
+      goto need_more_data;
+
+    val8 = *data++;
+    length -= 1;
+    if (G_UNLIKELY (length < val8))
+      goto need_more_data;
+    res->pack_header_size = val8;
+    res->pack_header = data;
+
+    GST_MEMDUMP ("Pack header data", res->pack_header, res->pack_header_size);
+
+    data += val8;
+    length -= val8;
+  }
+
+  if (flags & 0x20) {
+    /* sequence counter */
+    if (G_UNLIKELY (length < 2))
+      goto need_more_data;
+
+    val8 = *data++;
+    if (G_UNLIKELY ((val8 & 0x80) != 0x80))
+      goto bad_sequence_marker1;
+    res->program_packet_sequence_counter = val8 & 0x7f;
+    GST_LOG ("program_packet_sequence_counter %d",
+        res->program_packet_sequence_counter);
+
+    val8 = *data++;
+    if (G_UNLIKELY ((val8 & 0x80) != 0x80))
+      goto bad_sequence_marker2;
+    res->MPEG1_MPEG2_identifier = (val8 >> 6) & 0x1;
+    res->original_stuff_length = val8 & 0x3f;
+    GST_LOG ("MPEG1_MPEG2_identifier : %d , original_stuff_length : %d",
+        res->MPEG1_MPEG2_identifier, res->original_stuff_length);
+    length -= 2;
+  }
+
+  if (flags & 0x10) {
+    /* P-STD */
+    if (G_UNLIKELY (length < 2))
+      goto need_more_data;
+    val8 = *data;
+    if (G_UNLIKELY ((val8 & 0xc0) != 0x40))
+      goto bad_P_STD_marker;
+    res->P_STD_buffer_size =
+        (GST_READ_UINT16_BE (data) & 0x1fff) << (val8 & 0x20) ? 10 : 7;
+    GST_LOG ("P_STD_buffer_size : %d", res->P_STD_buffer_size);
+    data += 2;
+    length -= 2;
+  }
+
+  /* jump if we don't have a PES 2nd extension */
+  if (!(flags & 0x01))
+    goto stuffing_byte;
+
+  /* Extension flag 2 */
+  if (G_UNLIKELY (length < 1))
+    goto need_more_data;
+
+  val8 = *data++;
+  length -= 1;
+
+  if (!(val8 & 0x80))
+    goto bad_extension_marker_2;
+
+  res->extension_field_length = val8 & 0x7f;
+
+  /* Skip empty extensions */
+  if (G_UNLIKELY (res->extension_field_length == 0))
+    goto stuffing_byte;
+
+  if (G_UNLIKELY (length < res->extension_field_length))
+    goto need_more_data;
+
+  flags = *data++;
+  res->extension_field_length -= 1;
+
+  if (!(flags & 0x80)) {
+    /* Only valid if stream_id_extension_flag == 0x0 */
+    res->stream_id_extension = flags;
+    GST_LOG ("stream_id_extension : 0x%02x", res->stream_id_extension);
+  } else if (!(flags & 0x01)) {
+    /* Skip broken streams (that use stream_id_extension with highest bit set
+     * for example ...) */
+    if (G_UNLIKELY (res->extension_field_length < 5))
+      goto stuffing_byte;
+
+    GST_LOG ("TREF field present");
+    data += 5;
+    res->extension_field_length -= 5;
+  }
+
+  /* Extension field data */
+  if (res->extension_field_length) {
+    res->stream_id_extension_data = data;
+    GST_MEMDUMP ("stream_id_extension_data",
+        res->stream_id_extension_data, res->extension_field_length);
+  }
+
+stuffing_byte:
+  /* Go to the expected data start position */
+  data = origdata + res->header_size;
+  length = origlength - res->header_size;
+
+#ifdef WFD_SPEC
+  if (*(data) == 0xa0 && *(data+1) == 0x06) {
+    GST_WARNING ("This is LPCM");
+    res->lpcm_data.endianness = G_BIG_ENDIAN;
+    res->lpcm_data.sub_stream_ID = *data;
+    res->lpcm_data.emphasis = *(data+2);
+
+    /* data+3 => bit-rate (2) samp-freq (3) num-of-channels (3)*/
+    res->lpcm_data.width = ((*(data+3) & 0xC0) >> 4) | 0x10;
+    res->lpcm_data.channels = (*(data+3) & 0x07)+1; //num-of-channels starts from one
+
+    switch ( (*(data+3) & 0x38)>>3 ) {
+      case 1: res->lpcm_data.rate = 44100;
+      break;
+      case 2: res->lpcm_data.rate = 48000;
+      break;
+      case 4: res->lpcm_data.rate = 96000;
+      break;
+      default: res->lpcm_data.rate = 48000;
+      break;
+    }
+
+    /* Skip additional bytes for LPCM */
+    data += 4;
+    length -= 4;
+    res->is_lpcm = TRUE;
+  }
+#endif
+
+done_parsing:
+  res->header_size = origlength - length;
+  ret = PES_PARSING_OK;
+
+  return ret;
+
+  /* Errors */
+need_more_data:
+  GST_DEBUG ("Not enough data to parse PES header");
+  return ret;
+
+bad_start_code:
+  GST_WARNING ("Wrong packet start code 0x%x != 0x000001xx", val32);
+  return PES_PARSING_BAD;
+
+bad_marker_1:
+  GST_WARNING ("Wrong '0x10' marker before PES_scrambling_control (0x%02x)",
+      val8);
+  return PES_PARSING_BAD;
+
+bad_PTS_value:
+  GST_WARNING ("bad PTS value");
+  return PES_PARSING_BAD;
+
+bad_DTS_value:
+  GST_WARNING ("bad DTS value");
+  return PES_PARSING_BAD;
+
+bad_ESCR_value:
+  GST_WARNING ("bad ESCR value");
+  return PES_PARSING_BAD;
+
+bad_ES_rate:
+  GST_WARNING ("Invalid ES_rate markers 0x%0x", val32);
+  return PES_PARSING_BAD;
+
+bad_original_copy_info_marker:
+  GST_WARNING ("Invalid original_copy_info marker bit: 0x%0x", val8);
+  return PES_PARSING_BAD;
+
+bad_sequence_marker1:
+  GST_WARNING ("Invalid program_packet_sequence_counter marker 0x%0x", val8);
+  return PES_PARSING_BAD;
+
+bad_sequence_marker2:
+  GST_WARNING ("Invalid program_packet_sequence_counter marker 0x%0x", val8);
+  return PES_PARSING_BAD;
+
+bad_P_STD_marker:
+  GST_WARNING ("Invalid P-STD_buffer marker 0x%0x", val8);
+  return PES_PARSING_BAD;
+
+bad_extension_marker_2:
+  GST_WARNING ("Invalid extension_field_2 marker 0x%0x", val8);
+  return PES_PARSING_BAD;
+}
+
+void
+wfd_pes_parser_init (void)
+{
+  GST_DEBUG_CATEGORY_INIT (wfd_pes_parser_debug, "wfdpesparser", 0, "Wi-Fi Display PES parser");
+}
diff --git a/wfdtsdemux/wfdpesparse.h b/wfdtsdemux/wfdpesparse.h
new file mode 100755 (executable)
index 0000000..36fb6ae
--- /dev/null
@@ -0,0 +1,219 @@
+/*
+ * pesparse.h : MPEG PES parsing utility
+ * Copyright (C) 2011 Edward Hervey <bilboed@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef __PES_PARSE_H__
+#define __PES_PARSE_H__
+
+#include <gst/gst.h>
+#include "gstwfdtsdefs.h"
+
+G_BEGIN_DECLS
+
+
+/*
+ * PES stream_id assignments:
+ *
+ * 1011 1100                program_stream_map
+ * 1011 1101                private_stream_1
+ * 1011 1110                padding_stream
+ * 1011 1111                private_stream_2
+ * 110x xxxx                ISO/IEC 13818-3 or ISO/IEC 11172-3 audio stream number x xxxx
+ * 1110 xxxx                ITU-T Rec. H.262 | ISO/IEC 13818-2 or ISO/IEC 11172-2 video stream number xxxx
+ * 1111 0000                ECM_stream
+ * 1111 0001                EMM_stream
+ * 1111 0010                ITU-T Rec. H.222.0 | ISO/IEC 13818-1 Annex A or ISO/IEC 13818-6_DSMCC_stream
+ * 1111 0011                ISO/IEC_13522_stream
+ * 1111 0100                ITU-T Rec. H.222.1 type A
+ * 1111 0101                ITU-T Rec. H.222.1 type B
+ * 1111 0110                ITU-T Rec. H.222.1 type C
+ * 1111 0111                ITU-T Rec. H.222.1 type D
+ * 1111 1000                ITU-T Rec. H.222.1 type E
+ * 1111 1001                ancillary_stream
+ * 1111 1010                ISO/IEC 14496-1_SL-packetized_stream
+ * 1111 1011                ISO/IEC 14496-1_FlexMux_stream
+ * 1111 1100                metadata stream
+ * 1111 1101                extended_stream_id
+ * 1111 1110                reserved data stream
+ * 1111 1111                program_stream_directory
+ */
+
+#define ID_PS_END_CODE                          0xB9
+#define ID_PS_PACK_START_CODE                   0xBA
+#define ID_PS_SYSTEM_HEADER_START_CODE          0xBB
+#define ID_PS_PROGRAM_STREAM_MAP                0xBC
+#define ID_PRIVATE_STREAM_1                     0xBD
+#define ID_PADDING_STREAM                       0xBE
+#define ID_PRIVATE_STREAM_2                     0xBF
+#define ID_ISO_IEC_MPEG12_AUDIO_STREAM_0        0xC0
+#define ID_ISO_IEC_MPEG12_AUDIO_STREAM_32       0xDF
+#define ID_ISO_IEC_MPEG12_VIDEO_STREAM_0        0xE0
+#define ID_ISO_IEC_MPEG12_VIDEO_STREAM_16       0xEF
+#define ID_ECM_STREAM                           0xF0
+#define ID_EMM_STREAM                           0xF1
+#define ID_DSMCC_STREAM                         0xF2
+#define ID_ISO_IEC_13522_STREAM                 0xF3
+#define ID_ITU_TREC_H222_TYPE_A_STREAM          0xF4
+#define ID_ITU_TREC_H222_TYPE_B_STREAM          0xF5
+#define ID_ITU_TREC_H222_TYPE_C_STREAM          0xF6
+#define ID_ITU_TREC_H222_TYPE_D_STREAM          0xF7
+#define ID_ITU_TREC_H222_TYPE_E_STREAM          0xF8
+#define ID_ANCILLARY_STREAM                     0xF9
+#define ID_14496_1_SL_PACKETIZED_STREAM         0xFA
+#define ID_14496_1_SL_FLEXMUX_STREAM            0xFB
+#define ID_METADATA_STREAM                      0xFC
+#define ID_EXTENDED_STREAM_ID                   0xFD
+#define ID_RESERVED_STREAM_3                    0xFE
+#define ID_PROGRAM_STREAM_DIRECTORY             0xFF
+
+/*
+ * PES stream_id_extension assignments (if stream_id == ID_EXTENDED_STREAM_ID)
+ *
+ *  000 0000             IPMP Control Information stream
+ *  000 0001             IPMP Stream
+ *  000 0010 - 001 0001  ISO/IEC 14496-17 text Streams
+ *  001 0010 - 010 0001  ISO/IEC 23002-3 auxiliary video data Streams
+ *  ... .... - 011 1111  Reserved
+ *
+ *  PRIVATE STREAM RANGES (But known as used)
+ *  101 0101 - 101 1111  VC-1
+ *  110 0000 - 110 1111  Dirac (VC-1)
+ *
+ *  111 0001             AC3 or independent sub-stream 0 of EAC3/DD+
+ *                       DTS or core sub-stream
+ *  111 0010             dependent sub-stream of EAC3/DD+
+ *                       DTS extension sub-stream
+ *                       Secondary EAC3/DD+
+ *                       Secondary DTS-HD LBR
+ *  111 0110             AC3 in MLP/TrueHD
+ *  1xx xxxx    private_stream
+ */
+#define EXT_ID_IPMP_CONTORL_INFORMATION_STREAM  0x00
+#define EXT_ID_IPMP_STREAM                     0x01
+
+/* VC-1 */
+#define EXT_ID_VC1_FIRST                       0x55
+#define EXT_ID_VC1_LAST                        0x5F
+
+typedef enum {
+  PES_FLAG_PRIORITY            = 1 << 3,       /* PES_priority (present: high-priority) */
+  PES_FLAG_DATA_ALIGNMENT      = 1 << 2,       /* data_alignment_indicator */
+  PES_FLAG_COPYRIGHT           = 1 << 1,       /* copyright */
+  PES_FLAG_ORIGINAL_OR_COPY    = 1 << 0        /* original_or_copy */
+} WFDPESHeaderFlags;
+
+typedef enum {
+  PES_TRICK_MODE_FAST_FORWARD  = 0x000,
+  PES_TRICK_MODE_SLOW_MOTION    = 0x001,
+  PES_TRICK_MODE_FREEZE_FRAME  = 0x010,
+  PES_TRICK_MODE_FAST_REVERSE  = 0x011,
+  PES_TRICK_MODE_SLOW_REVERSE  = 0x100,
+  /* ... */
+  PES_TRICK_MODE_INVALID       = 0xfff /* Not present or invalid */
+} WFDPESTrickModeControl;
+
+typedef enum {
+  PES_FIELD_ID_TOP_ONLY                = 0x00, /* Display from top field only */
+  PES_FIELD_ID_BOTTOM_ONLY     = 0x01, /* Display from bottom field only */
+  PES_FIELD_ID_COMPLETE_FRAME  = 0x10, /* Display complete frame */
+  PES_FIELD_ID_INVALID         = 0x11  /* Reserved/Invalid */
+} WFDPESFieldID;
+
+typedef enum {
+  PES_PARSING_OK       = 0,    /* Header fully parsed and valid */
+  PES_PARSING_BAD      = 1,    /* Header invalid (CRC error for ex) */
+  PES_PARSING_NEED_MORE = 2    /* Not enough data to parse header */
+} WFDPESParsingResult;
+
+#ifdef WFD_SPEC
+typedef struct _GstWFDLPCMdata GstWFDLPCMdata;
+struct _GstWFDLPCMdata {
+  guint8 sub_stream_ID;
+  guint8 width;
+  guint8 channels;
+  guint endianness;
+  guint rate;
+  gboolean emphasis;
+};
+#endif
+
+typedef struct {
+  guint8       stream_id;      /* See ID_* above */
+  guint32      packet_length;  /* The size of the PES header and PES data
+                                * (if 0 => unbounded packet) */
+  guint16      header_size;    /* The complete size of the PES header */
+
+  /* All remaining entries in this structure are optional */
+  guint8       scrambling_control; /* 0x00  : Not scrambled/unspecified,
+                                    * The following are according to ETSI TS 101 154
+                                    * 0x01  : reserved for future DVB use
+                                    * 0x10  : PES packet scrambled with Even key
+                                    * 0x11  : PES packet scrambled with Odd key
+                                    */
+  WFDPESHeaderFlags flags;
+
+  guint64      PTS;            /* PTS (-1 if not present or invalid) */
+  guint64      DTS;            /* DTS (-1 if not present or invalid) */
+  guint64      ESCR;           /* ESCR (-1 if not present or invalid) */
+
+  guint32      ES_rate;        /* in bytes/seconds (0 if not present or invalid) */
+  WFDPESTrickModeControl       trick_mode;
+
+  /* Only valid for _FAST_FORWARD, _FAST_REVERSE and _FREEZE_FRAME */
+  WFDPESFieldID        field_id;
+  /* Only valid for _FAST_FORWARD and _FAST_REVERSE */
+  gboolean     intra_slice_refresh;
+  guint8       frequency_truncation;
+  /* Only valid for _SLOW_FORWARD and _SLOW_REVERSE */
+  guint8       rep_cntrl;
+
+  guint8       additional_copy_info; /* Private data */
+  guint16      previous_PES_packet_CRC;
+
+  /* Extension fields */
+  const guint8*        private_data;                   /* PES_private_data, 16 bytes long */
+  guint8       pack_header_size;               /* Size of pack_header in bytes */
+  const guint8*        pack_header;
+  gint8                program_packet_sequence_counter; /* -1 if not present or invalid */
+  gboolean     MPEG1_MPEG2_identifier;
+  guint8       original_stuff_length;
+
+  guint32      P_STD_buffer_size; /* P-STD buffer size in bytes (0 if invalid
+                                   * or not present */
+
+  guint8       stream_id_extension; /* Public range (0x00 - 0x3f) only valid if stream_id == ID_EXTENDED_STREAM_ID
+                                     * Private range (0x40 - 0xff) can be present in any stream type */
+
+  gsize                extension_field_length;   /* Length of remaining extension field data */
+  const guint8*        stream_id_extension_data; /* Valid if extension_field_length != 0 */
+
+#ifdef WFD_SPEC
+gboolean is_lpcm;
+GstWFDLPCMdata lpcm_data;
+#endif
+} WFDPESHeader;
+
+
+G_GNUC_INTERNAL WFDPESParsingResult wfd_ts_parse_pes_header (const guint8* data,
+                                                         gsize size,
+                                                         WFDPESHeader *res);
+G_GNUC_INTERNAL void wfd_pes_parser_init (void);
+
+G_END_DECLS
+#endif /* __PES_PARSE_H__ */
diff --git a/wfdtsdemux/wfdtsbase.c b/wfdtsdemux/wfdtsbase.c
new file mode 100755 (executable)
index 0000000..00f3533
--- /dev/null
@@ -0,0 +1,1605 @@
+/*
+ * mpegtsbase.c -
+ * Copyright (C) 2007 Alessandro Decina
+ *               2010 Edward Hervey
+ * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
+ *  Author: Youness Alaoui <youness.alaoui@collabora.co.uk>, Collabora Ltd.
+ *  Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
+ *  Author: Edward Hervey <bilboed@bilboed.com>, Collabora Ltd.
+ *
+ * Authors:
+ *   Alessandro Decina <alessandro@nnva.org>
+ *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
+ *   Edward Hervey <edward.hervey@collabora.co.uk>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <glib.h>
+
+//#include <gst/gst-i18n-plugin.h>
+#include "wfdtsbase.h"
+#include "gstwfdtsdesc.h"
+
+/* latency in mseconds */
+#define TS_LATENCY 700
+
+#define RUNNING_STATUS_RUNNING 4
+
+GST_DEBUG_CATEGORY_STATIC (wfd_ts_base_debug);
+#define GST_CAT_DEFAULT wfd_ts_base_debug
+
+static GQuark QUARK_PROGRAMS;
+static GQuark QUARK_PROGRAM_NUMBER;
+static GQuark QUARK_PID;
+static GQuark QUARK_PCR_PID;
+static GQuark QUARK_STREAMS;
+static GQuark QUARK_STREAM_TYPE;
+
+static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
+    GST_PAD_SINK,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("video/mpegts, " "systemstream = (boolean) true ")
+    );
+
+enum
+{
+  PROP_0,
+  PROP_PARSE_PRIVATE_SECTIONS,
+  /* FILL ME */
+};
+
+static void wfd_ts_base_dispose (GObject * object);
+static void wfd_ts_base_finalize (GObject * object);
+static void wfd_ts_base_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void wfd_ts_base_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+
+static void wfd_ts_base_free_program (WFDTSBaseProgram * program);
+static gboolean wfd_ts_base_sink_activate (GstPad * pad, GstObject * parent);
+static gboolean wfd_ts_base_sink_activate_mode (GstPad * pad,
+    GstObject * parent, GstPadMode mode, gboolean active);
+static GstFlowReturn wfd_ts_base_chain (GstPad * pad, GstObject * parent,
+    GstBuffer * buf);
+static gboolean wfd_ts_base_sink_event (GstPad * pad, GstObject * parent,
+    GstEvent * event);
+static GstStateChangeReturn wfd_ts_base_change_state (GstElement * element,
+    GstStateChange transition);
+#ifdef ENABLE_ALL
+static gboolean wfd_ts_base_get_tags_from_eit (WFDTSBase * base,
+    GstWFDTSSection * section);
+static gboolean wfd_ts_base_parse_atsc_mgt (WFDTSBase * base,
+    GstWFDTSSection * section);
+#endif
+static gboolean remove_each_program (gpointer key, WFDTSBaseProgram * program,
+    WFDTSBase * base);
+
+static void
+_extra_init (void)
+{
+  QUARK_PROGRAMS = g_quark_from_string ("programs");
+  QUARK_PROGRAM_NUMBER = g_quark_from_string ("program-number");
+  QUARK_PID = g_quark_from_string ("pid");
+  QUARK_PCR_PID = g_quark_from_string ("pcr-pid");
+  QUARK_STREAMS = g_quark_from_string ("streams");
+  QUARK_STREAM_TYPE = g_quark_from_string ("stream-type");
+}
+
+#define wfd_ts_base_parent_class parent_class
+G_DEFINE_TYPE_WITH_CODE (WFDTSBase, wfd_ts_base, GST_TYPE_ELEMENT,
+    _extra_init ());
+
+static void
+wfd_ts_base_class_init (WFDTSBaseClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstElementClass *element_class;
+
+  element_class = GST_ELEMENT_CLASS (klass);
+  element_class->change_state = wfd_ts_base_change_state;
+
+  gst_element_class_add_pad_template (element_class,
+      gst_static_pad_template_get (&sink_template));
+
+  gobject_class = G_OBJECT_CLASS (klass);
+  gobject_class->dispose = wfd_ts_base_dispose;
+  gobject_class->finalize = wfd_ts_base_finalize;
+  gobject_class->set_property = wfd_ts_base_set_property;
+  gobject_class->get_property = wfd_ts_base_get_property;
+
+  g_object_class_install_property (gobject_class, PROP_PARSE_PRIVATE_SECTIONS,
+      g_param_spec_boolean ("parse-private-sections", "Parse private sections",
+          "Parse private sections", FALSE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+}
+
+static void
+wfd_ts_base_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  WFDTSBase *base = GST_WFD_TS_BASE (object);
+
+  switch (prop_id) {
+    case PROP_PARSE_PRIVATE_SECTIONS:
+      base->parse_private_sections = g_value_get_boolean (value);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+  }
+}
+
+static void
+wfd_ts_base_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec)
+{
+  WFDTSBase *base = GST_WFD_TS_BASE (object);
+
+  switch (prop_id) {
+    case PROP_PARSE_PRIVATE_SECTIONS:
+      g_value_set_boolean (value, base->parse_private_sections);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+  }
+}
+
+
+static void
+wfd_ts_base_reset (WFDTSBase * base)
+{
+  WFDTSBaseClass *klass = GST_WFD_TS_BASE_GET_CLASS (base);
+
+  wfd_ts_packetizer_clear (base->packetizer);
+  memset (base->is_pes, 0, 1024);
+  memset (base->known_psi, 0, 1024);
+
+  /* FIXME : Actually these are not *always* know SI streams
+   * depending on the variant of mpeg-ts being used. */
+
+  /* Known PIDs : PAT, TSDT, IPMP CIT */
+  WFD_TS_BIT_SET (base->known_psi, 0);
+  WFD_TS_BIT_SET (base->known_psi, 2);
+  WFD_TS_BIT_SET (base->known_psi, 3);
+  /* TDT, TOT, ST */
+  WFD_TS_BIT_SET (base->known_psi, 0x14);
+  /* network synchronization */
+  WFD_TS_BIT_SET (base->known_psi, 0x15);
+
+  /* ATSC */
+  WFD_TS_BIT_SET (base->known_psi, 0x1ffb);
+
+  if (base->pat) {
+    g_ptr_array_unref (base->pat);
+    base->pat = NULL;
+  }
+
+  gst_segment_init (&base->segment, GST_FORMAT_UNDEFINED);
+  base->last_seek_seqnum = (guint32) - 1;
+
+  base->mode = BASE_MODE_STREAMING;
+  base->seen_pat = FALSE;
+  base->seek_offset = -1;
+
+  base->upstream_live = FALSE;
+  base->queried_latency = FALSE;
+
+  g_hash_table_foreach_remove (base->programs, (GHRFunc) remove_each_program,
+      base);
+
+  if (klass->reset)
+    klass->reset (base);
+}
+
+static void
+wfd_ts_base_init (WFDTSBase * base)
+{
+  base->sinkpad = gst_pad_new_from_static_template (&sink_template, "sink");
+  gst_pad_set_activate_function (base->sinkpad, wfd_ts_base_sink_activate);
+  gst_pad_set_activatemode_function (base->sinkpad,
+      wfd_ts_base_sink_activate_mode);
+  gst_pad_set_chain_function (base->sinkpad, wfd_ts_base_chain);
+  gst_pad_set_event_function (base->sinkpad, wfd_ts_base_sink_event);
+  gst_element_add_pad (GST_ELEMENT (base), base->sinkpad);
+
+  base->disposed = FALSE;
+  base->packetizer = wfd_ts_packetizer_new ();
+  base->programs = g_hash_table_new_full (g_direct_hash, g_direct_equal,
+      NULL, (GDestroyNotify) wfd_ts_base_free_program);
+
+  base->parse_private_sections = FALSE;
+  base->is_pes = g_new0 (guint8, 1024);
+  base->known_psi = g_new0 (guint8, 1024);
+  base->program_size = sizeof (WFDTSBaseProgram);
+  base->stream_size = sizeof (WFDTSBaseStream);
+
+  base->push_data = TRUE;
+  base->push_section = TRUE;
+
+  wfd_ts_base_reset (base);
+}
+
+static void
+wfd_ts_base_dispose (GObject * object)
+{
+  WFDTSBase *base = GST_WFD_TS_BASE (object);
+
+  if (!base->disposed) {
+    g_object_unref (base->packetizer);
+    base->disposed = TRUE;
+    g_free (base->known_psi);
+    g_free (base->is_pes);
+  }
+
+  if (G_OBJECT_CLASS (parent_class)->dispose)
+    G_OBJECT_CLASS (parent_class)->dispose (object);
+}
+
+static void
+wfd_ts_base_finalize (GObject * object)
+{
+  WFDTSBase *base = GST_WFD_TS_BASE (object);
+
+  if (base->pat) {
+    g_ptr_array_unref (base->pat);
+    base->pat = NULL;
+  }
+  g_hash_table_destroy (base->programs);
+
+  if (G_OBJECT_CLASS (parent_class)->finalize)
+    G_OBJECT_CLASS (parent_class)->finalize (object);
+}
+
+
+/* returns NULL if no matching descriptor found *
+ * otherwise returns a descriptor that needs to *
+ * be freed */
+const GstWFDTSDescriptor *
+wfd_ts_get_descriptor_from_stream (WFDTSBaseStream * stream, guint8 tag)
+{
+  GstWFDTSPMTStream *pmt = stream->stream;
+
+  GST_DEBUG ("Searching for tag 0x%02x in stream 0x%04x (stream_type 0x%02x)",
+      tag, stream->pid, stream->stream_type);
+
+  return gst_wfd_ts_find_descriptor (pmt->descriptors, tag);
+}
+
+typedef struct
+{
+  gboolean res;
+  guint16 pid;
+} WFDPIDLookup;
+
+static void
+foreach_pid_in_program (gpointer key, WFDTSBaseProgram * program,
+    WFDPIDLookup * lookup)
+{
+  if (!program->active)
+    return;
+  if (program->streams[lookup->pid])
+    lookup->res = TRUE;
+}
+
+static gboolean
+wfd_ts_pid_in_active_programs (WFDTSBase * base, guint16 pid)
+{
+  WFDPIDLookup lookup;
+
+  lookup.res = FALSE;
+  lookup.pid = pid;
+  g_hash_table_foreach (base->programs, (GHFunc) foreach_pid_in_program,
+      &lookup);
+
+  return lookup.res;
+}
+
+/* returns NULL if no matching descriptor found *
+ * otherwise returns a descriptor that needs to *
+ * be freed */
+const GstWFDTSDescriptor *
+wfd_ts_get_descriptor_from_program (WFDTSBaseProgram * program, guint8 tag)
+{
+  const GstWFDTSPMT *pmt = program->pmt;
+
+  return gst_wfd_ts_find_descriptor (pmt->descriptors, tag);
+}
+
+static WFDTSBaseProgram *
+wfd_ts_base_new_program (WFDTSBase * base,
+    gint program_number, guint16 pmt_pid)
+{
+  WFDTSBaseProgram *program;
+
+  GST_DEBUG_OBJECT (base, "program_number : %d, pmt_pid : %d",
+      program_number, pmt_pid);
+
+  program = g_malloc0 (base->program_size);
+  program->program_number = program_number;
+  program->pmt_pid = pmt_pid;
+  program->pcr_pid = G_MAXUINT16;
+  program->streams = g_new0 (WFDTSBaseStream *, 0x2000);
+  program->patcount = 0;
+
+  return program;
+}
+
+WFDTSBaseProgram *
+wfd_ts_base_add_program (WFDTSBase * base,
+    gint program_number, guint16 pmt_pid)
+{
+  WFDTSBaseProgram *program;
+
+  GST_DEBUG_OBJECT (base, "program_number : %d, pmt_pid : %d",
+      program_number, pmt_pid);
+
+  program = wfd_ts_base_new_program (base, program_number, pmt_pid);
+
+  /* Mark the PMT PID as being a known PSI PID */
+  if (G_UNLIKELY (WFD_TS_BIT_IS_SET (base->known_psi, pmt_pid))) {
+    GST_FIXME ("Refcounting. Setting twice a PID (0x%04x) as known PSI",
+        pmt_pid);
+  }
+  WFD_TS_BIT_SET (base->known_psi, pmt_pid);
+
+  g_hash_table_insert (base->programs,
+      GINT_TO_POINTER (program_number), program);
+
+  return program;
+}
+
+WFDTSBaseProgram *
+wfd_ts_base_get_program (WFDTSBase * base, gint program_number)
+{
+  WFDTSBaseProgram *program;
+
+  program = (WFDTSBaseProgram *) g_hash_table_lookup (base->programs,
+      GINT_TO_POINTER ((gint) program_number));
+
+  return program;
+}
+
+static WFDTSBaseProgram *
+wfd_ts_base_steal_program (WFDTSBase * base, gint program_number)
+{
+  WFDTSBaseProgram *program;
+
+  program = (WFDTSBaseProgram *) g_hash_table_lookup (base->programs,
+      GINT_TO_POINTER ((gint) program_number));
+
+  if (program)
+    g_hash_table_steal (base->programs,
+        GINT_TO_POINTER ((gint) program_number));
+
+  return program;
+}
+
+static void
+wfd_ts_base_free_program (WFDTSBaseProgram * program)
+{
+  GList *tmp;
+
+  if (program->pmt) {
+    gst_wfd_ts_section_unref (program->section);
+    program->pmt = NULL;
+  }
+
+  for (tmp = program->stream_list; tmp; tmp = tmp->next)
+    g_free (tmp->data);
+  if (program->stream_list)
+    g_list_free (program->stream_list);
+
+  g_free (program->streams);
+
+  if (program->tags)
+    gst_tag_list_unref (program->tags);
+
+  g_free (program);
+}
+
+void
+wfd_ts_base_remove_program (WFDTSBase * base, gint program_number)
+{
+  GST_DEBUG_OBJECT (base, "program_number : %d", program_number);
+
+  g_hash_table_remove (base->programs, GINT_TO_POINTER (program_number));
+}
+
+static guint32
+get_registration_from_descriptors (GPtrArray * descriptors)
+{
+  const GstWFDTSDescriptor *desc;
+
+  if ((desc =
+          gst_wfd_ts_find_descriptor (descriptors,
+              GST_MTS_DESC_REGISTRATION))) {
+    if (G_UNLIKELY (desc->length < 4)) {
+      GST_WARNING ("Registration descriptor with length < 4. (Corrupted ?)");
+    } else
+      return GST_READ_UINT32_BE (desc->data + 2);
+  }
+
+  return 0;
+}
+
+static WFDTSBaseStream *
+wfd_ts_base_program_add_stream (WFDTSBase * base,
+    WFDTSBaseProgram * program, guint16 pid, guint8 stream_type,
+    GstWFDTSPMTStream * stream)
+{
+  WFDTSBaseClass *klass = GST_WFD_TS_BASE_GET_CLASS (base);
+  WFDTSBaseStream *bstream;
+
+  GST_DEBUG ("pid:0x%04x, stream_type:0x%03x", pid, stream_type);
+
+  if (G_UNLIKELY (program->streams[pid])) {
+    if (stream_type != 0xff)
+      GST_WARNING ("Stream already present !");
+    return NULL;
+  }
+
+  bstream = g_malloc0 (base->stream_size);
+  bstream->pid = pid;
+  bstream->stream_type = stream_type;
+  bstream->stream = stream;
+  if (stream) {
+    bstream->registration_id =
+        get_registration_from_descriptors (stream->descriptors);
+    GST_DEBUG ("PID 0x%04x, registration_id %" SAFE_FOURCC_FORMAT,
+        bstream->pid, SAFE_FOURCC_ARGS (bstream->registration_id));
+  }
+
+
+  program->streams[pid] = bstream;
+  program->stream_list = g_list_append (program->stream_list, bstream);
+
+  if (klass->stream_added)
+    klass->stream_added (base, bstream, program);
+
+  return bstream;
+}
+
+void
+wfd_ts_base_program_remove_stream (WFDTSBase * base,
+    WFDTSBaseProgram * program, guint16 pid)
+{
+  WFDTSBaseClass *klass;
+  WFDTSBaseStream *stream = program->streams[pid];
+
+  GST_DEBUG ("pid:0x%04x", pid);
+
+  if (G_UNLIKELY (stream == NULL)) {
+    /* Can happen if the PCR PID is the same as a audio/video PID */
+    GST_DEBUG ("Stream already removed");
+    return;
+  }
+
+  klass = GST_WFD_TS_BASE_GET_CLASS (base);
+
+  /* If subclass needs it, inform it of the stream we are about to remove */
+  if (klass->stream_removed)
+    klass->stream_removed (base, stream);
+
+  program->stream_list = g_list_remove_all (program->stream_list, stream);
+  g_free (stream);
+  program->streams[pid] = NULL;
+}
+
+/* Return TRUE if programs are equal */
+static gboolean
+wfd_ts_base_is_same_program (WFDTSBase * base, WFDTSBaseProgram * oldprogram,
+    guint16 new_pmt_pid, const GstWFDTSPMT * new_pmt)
+{
+  guint i, nbstreams;
+  WFDTSBaseStream *oldstream;
+  gboolean sawpcrpid = FALSE;
+
+  if (oldprogram->pmt_pid != new_pmt_pid) {
+    GST_DEBUG ("Different pmt_pid (new:0x%04x, old:0x%04x)", new_pmt_pid,
+        oldprogram->pmt_pid);
+    return FALSE;
+  }
+
+  if (oldprogram->pcr_pid != new_pmt->pcr_pid) {
+    GST_DEBUG ("Different pcr_pid (new:0x%04x, old:0x%04x)",
+        new_pmt->pcr_pid, oldprogram->pcr_pid);
+    return FALSE;
+  }
+
+  /* Check the streams */
+  nbstreams = new_pmt->streams->len;
+  for (i = 0; i < nbstreams; ++i) {
+    GstWFDTSPMTStream *stream = g_ptr_array_index (new_pmt->streams, i);
+
+    oldstream = oldprogram->streams[stream->pid];
+    if (!oldstream) {
+      GST_DEBUG ("New stream 0x%04x not present in old program", stream->pid);
+      return FALSE;
+    }
+    if (oldstream->stream_type != stream->stream_type) {
+      GST_DEBUG
+          ("New stream 0x%04x has a different stream type (new:%d, old:%d)",
+          stream->pid, stream->stream_type, oldstream->stream_type);
+      return FALSE;
+    }
+    if (stream->pid == oldprogram->pcr_pid)
+      sawpcrpid = TRUE;
+  }
+
+  /* If the pcr is not shared with an existing stream, we'll have one extra stream */
+  if (!sawpcrpid)
+    nbstreams += 1;
+
+  if (nbstreams != g_list_length (oldprogram->stream_list)) {
+    GST_DEBUG ("Different number of streams (new:%d, old:%d)",
+        nbstreams, g_list_length (oldprogram->stream_list));
+    return FALSE;
+  }
+
+  GST_DEBUG ("Programs are equal");
+  return TRUE;
+}
+
+static void
+wfd_ts_base_deactivate_program (WFDTSBase * base, WFDTSBaseProgram * program)
+{
+  gint i;
+  WFDTSBaseClass *klass = GST_WFD_TS_BASE_GET_CLASS (base);
+
+  if (G_UNLIKELY (program->active == FALSE))
+    return;
+
+  GST_DEBUG_OBJECT (base, "Deactivating PMT");
+
+  program->active = FALSE;
+
+  if (program->pmt) {
+    for (i = 0; i < program->pmt->streams->len; ++i) {
+      GstWFDTSPMTStream *stream = g_ptr_array_index (program->pmt->streams, i);
+
+      wfd_ts_base_program_remove_stream (base, program, stream->pid);
+
+      /* Only unset the is_pes/known_psi bit if the PID isn't used in any other active
+       * program */
+      if (!wfd_ts_pid_in_active_programs (base, stream->pid)) {
+        switch (stream->stream_type) {
+#ifdef ENABLE_ALL
+          case GST_WFD_TS_STREAM_TYPE_SCTE_DSMCC_DCB:
+          case GST_WFD_TS_STREAM_TYPE_SCTE_SIGNALING:
+          {
+            guint32 registration_id =
+                get_registration_from_descriptors (stream->descriptors);
+
+            /* Not a private section stream */
+            if (registration_id != DRF_ID_CUEI
+                && registration_id != DRF_ID_ETV1)
+              break;
+            /* Fall through on purpose - remove this PID from known_psi */
+          }
+#endif
+          case GST_WFD_TS_STREAM_TYPE_PRIVATE_SECTIONS:
+          case GST_WFD_TS_STREAM_TYPE_MHEG:
+          case GST_WFD_TS_STREAM_TYPE_DSM_CC:
+          case GST_WFD_TS_STREAM_TYPE_DSMCC_A:
+          case GST_WFD_TS_STREAM_TYPE_DSMCC_B:
+          case GST_WFD_TS_STREAM_TYPE_DSMCC_C:
+          case GST_WFD_TS_STREAM_TYPE_DSMCC_D:
+          case GST_WFD_TS_STREAM_TYPE_SL_FLEXMUX_SECTIONS:
+          case GST_WFD_TS_STREAM_TYPE_METADATA_SECTIONS:
+            /* Set known PSI streams */
+            if (base->parse_private_sections)
+              WFD_TS_BIT_UNSET (base->known_psi, stream->pid);
+            break;
+          default:
+            WFD_TS_BIT_UNSET (base->is_pes, stream->pid);
+            break;
+        }
+      }
+    }
+
+    /* remove pcr stream */
+    /* FIXME : This might actually be shared with another stream ? */
+    wfd_ts_base_program_remove_stream (base, program, program->pcr_pid);
+    if (!wfd_ts_pid_in_active_programs (base, program->pcr_pid))
+      WFD_TS_BIT_UNSET (base->is_pes, program->pcr_pid);
+
+    GST_DEBUG ("program stream_list is now %p", program->stream_list);
+  }
+
+  /* Inform subclasses we're deactivating this program */
+  if (klass->program_stopped)
+    klass->program_stopped (base, program);
+}
+
+static void
+wfd_ts_base_activate_program (WFDTSBase * base, WFDTSBaseProgram * program,
+    guint16 pmt_pid, GstWFDTSSection * section, const GstWFDTSPMT * pmt,
+    gboolean initial_program)
+{
+  guint i;
+  WFDTSBaseClass *klass;
+
+  if (G_UNLIKELY (program->active))
+    return;
+
+  GST_DEBUG ("Activating program %d", program->program_number);
+
+  /* activate new pmt */
+  if (program->section)
+    gst_wfd_ts_section_unref (program->section);
+  program->section = gst_wfd_ts_section_ref (section);
+
+  program->pmt = pmt;
+  program->pmt_pid = pmt_pid;
+  program->pcr_pid = pmt->pcr_pid;
+
+  /* extract top-level registration_id if present */
+  program->registration_id =
+      get_registration_from_descriptors (pmt->descriptors);
+  GST_DEBUG ("program 0x%04x, registration_id %" SAFE_FOURCC_FORMAT,
+      program->program_number, SAFE_FOURCC_ARGS (program->registration_id));
+
+  for (i = 0; i < pmt->streams->len; ++i) {
+    GstWFDTSPMTStream *stream = g_ptr_array_index (pmt->streams, i);
+
+    switch (stream->stream_type) {
+#ifdef ENABLE_ALL
+      case GST_WFD_TS_STREAM_TYPE_SCTE_DSMCC_DCB:
+      case GST_WFD_TS_STREAM_TYPE_SCTE_SIGNALING:
+      {
+        guint32 registration_id =
+            get_registration_from_descriptors (stream->descriptors);
+        /* Not a private section stream */
+        if (registration_id != DRF_ID_CUEI && registration_id != DRF_ID_ETV1)
+          break;
+        /* Fall through on purpose - remove this PID from known_psi */
+      }
+#endif
+      case GST_WFD_TS_STREAM_TYPE_PRIVATE_SECTIONS:
+      case GST_WFD_TS_STREAM_TYPE_MHEG:
+      case GST_WFD_TS_STREAM_TYPE_DSM_CC:
+      case GST_WFD_TS_STREAM_TYPE_DSMCC_A:
+      case GST_WFD_TS_STREAM_TYPE_DSMCC_B:
+      case GST_WFD_TS_STREAM_TYPE_DSMCC_C:
+      case GST_WFD_TS_STREAM_TYPE_DSMCC_D:
+      case GST_WFD_TS_STREAM_TYPE_SL_FLEXMUX_SECTIONS:
+      case GST_WFD_TS_STREAM_TYPE_METADATA_SECTIONS:
+        /* Set known PSI streams */
+        if (base->parse_private_sections)
+          WFD_TS_BIT_SET (base->known_psi, stream->pid);
+        break;
+      default:
+        if (G_UNLIKELY (WFD_TS_BIT_IS_SET (base->is_pes, stream->pid)))
+          GST_FIXME
+              ("Refcounting issue. Setting twice a PID (0x%04x) as known PES",
+              stream->pid);
+        if (G_UNLIKELY (WFD_TS_BIT_IS_SET (base->known_psi, stream->pid))) {
+          GST_FIXME
+              ("Refcounting issue. Setting a known PSI PID (0x%04x) as known PES",
+              stream->pid);
+          WFD_TS_BIT_UNSET (base->known_psi, stream->pid);
+        }
+
+        WFD_TS_BIT_SET (base->is_pes, stream->pid);
+        break;
+    }
+    wfd_ts_base_program_add_stream (base, program,
+        stream->pid, stream->stream_type, stream);
+
+  }
+  /* We add the PCR pid last. If that PID is already used by one of the media
+   * streams above, no new stream will be created */
+  wfd_ts_base_program_add_stream (base, program, pmt->pcr_pid, -1, NULL);
+  WFD_TS_BIT_SET (base->is_pes, pmt->pcr_pid);
+
+  program->active = TRUE;
+  program->initial_program = initial_program;
+
+  klass = GST_WFD_TS_BASE_GET_CLASS (base);
+  if (klass->program_started != NULL)
+    klass->program_started (base, program);
+
+  GST_DEBUG_OBJECT (base, "new pmt activated");
+}
+
+
+static gboolean
+wfd_ts_base_apply_pat (WFDTSBase * base, GstWFDTSSection * section)
+{
+  GPtrArray *pat = gst_wfd_ts_section_get_pat (section);
+  GPtrArray *old_pat;
+  WFDTSBaseProgram *program;
+  gint i;
+
+  if (G_UNLIKELY (pat == NULL))
+    return FALSE;
+
+  GST_INFO_OBJECT (base, "PAT");
+
+  /* Applying a new PAT does two things:
+   * * It adds the new programs to the list of programs this element handles
+   *   and increments at the same time the number of times a program is referenced.
+   *
+   * * If there was a previously active PAT, It decrements the reference count
+   *   of all program it used. If a program is no longer needed, it is removed.
+   */
+
+  old_pat = base->pat;
+  base->pat = pat;
+
+  GST_LOG ("Activating new Program Association Table");
+  /* activate the new table */
+  for (i = 0; i < pat->len; ++i) {
+    GstMpegtsPatProgram *patp = g_ptr_array_index (pat, i);
+
+    program = wfd_ts_base_get_program (base, patp->program_number);
+    if (program) {
+      /* IF the program already existed, just check if the PMT PID changed */
+      if (program->pmt_pid != patp->network_or_program_map_PID) {
+        if (program->pmt_pid != G_MAXUINT16) {
+          /* pmt pid changed */
+          /* FIXME: when this happens it may still be pmt pid of another
+           * program, so setting to False may make it go through expensive
+           * path in is_psi unnecessarily */
+          WFD_TS_BIT_UNSET (base->known_psi, program->pmt_pid);
+        }
+
+        program->pmt_pid = patp->network_or_program_map_PID;
+        if (G_UNLIKELY (WFD_TS_BIT_IS_SET (base->known_psi, program->pmt_pid)))
+          GST_FIXME
+              ("Refcounting issue. Setting twice a PMT PID (0x%04x) as know PSI",
+              program->pmt_pid);
+        WFD_TS_BIT_SET (base->known_psi, patp->network_or_program_map_PID);
+      }
+    } else {
+      /* Create a new program */
+      program =
+          wfd_ts_base_add_program (base, patp->program_number,
+          patp->network_or_program_map_PID);
+    }
+    /* We mark this program as being referenced by one PAT */
+    program->patcount += 1;
+  }
+
+  if (old_pat) {
+    /* deactivate the old table */
+    GST_LOG ("Deactivating old Program Association Table");
+
+    for (i = 0; i < old_pat->len; ++i) {
+      GstMpegtsPatProgram *patp = g_ptr_array_index (old_pat, i);
+
+      program = wfd_ts_base_get_program (base, patp->program_number);
+      if (G_UNLIKELY (program == NULL)) {
+        GST_DEBUG_OBJECT (base, "broken PAT, duplicated entry for program %d",
+            patp->program_number);
+        continue;
+      }
+
+      if (--program->patcount > 0)
+        /* the program has been referenced by the new pat, keep it */
+        continue;
+
+      GST_INFO_OBJECT (base, "PAT removing program 0x%04x 0x%04x",
+          patp->program_number, patp->network_or_program_map_PID);
+
+      wfd_ts_base_deactivate_program (base, program);
+      wfd_ts_base_remove_program (base, patp->program_number);
+      /* FIXME: when this happens it may still be pmt pid of another
+       * program, so setting to False may make it go through expensive
+       * path in is_psi unnecessarily */
+      if (G_UNLIKELY (WFD_TS_BIT_IS_SET (base->known_psi,
+                  patp->network_or_program_map_PID))) {
+        GST_FIXME
+            ("Program refcounting : Setting twice a pid (0x%04x) as known PSI",
+            patp->network_or_program_map_PID);
+      }
+      WFD_TS_BIT_SET (base->known_psi, patp->network_or_program_map_PID);
+      wfd_ts_packetizer_remove_stream (base->packetizer,
+          patp->network_or_program_map_PID);
+    }
+
+    g_ptr_array_unref (old_pat);
+  }
+
+  return TRUE;
+}
+
+static gboolean
+wfd_ts_base_apply_pmt (WFDTSBase * base, GstWFDTSSection * section)
+{
+  const GstWFDTSPMT *pmt;
+  WFDTSBaseProgram *program, *old_program;
+  guint program_number;
+  gboolean initial_program = TRUE;
+
+  pmt = gst_wfd_ts_section_get_pmt (section);
+  if (G_UNLIKELY (pmt == NULL)) {
+    GST_ERROR ("Could not get PMT (corrupted ?)");
+    return FALSE;
+  }
+
+  /* FIXME : not so sure this is valid anymore */
+  if (G_UNLIKELY (base->seen_pat == FALSE)) {
+    GST_WARNING ("Got pmt without pat first. Returning");
+    /* remove the stream since we won't get another PMT otherwise */
+    wfd_ts_packetizer_remove_stream (base->packetizer, section->pid);
+    return TRUE;
+  }
+
+  program_number = section->subtable_extension;
+  GST_DEBUG ("Applying PMT (program_number:%d, pid:0x%04x)",
+      program_number, section->pid);
+
+  /* In order for stream switching to happen properly in decodebin(2),
+   * we need to first add the new pads (i.e. activate the new program)
+   * before removing the old ones (i.e. deactivating the old program)
+   */
+
+  old_program = wfd_ts_base_get_program (base, program_number);
+  if (G_UNLIKELY (old_program == NULL))
+    goto no_program;
+
+  if (G_UNLIKELY (wfd_ts_base_is_same_program (base, old_program, section->pid,
+              pmt)))
+    goto same_program;
+
+  /* If the current program is active, this means we have a new program */
+  if (old_program->active) {
+    old_program = wfd_ts_base_steal_program (base, program_number);
+    if(G_UNLIKELY (old_program == NULL))
+      goto no_program;
+
+    program = wfd_ts_base_new_program (base, program_number, section->pid);
+    g_hash_table_insert (base->programs,
+        GINT_TO_POINTER (program_number), program);
+
+    /* Desactivate the old program */
+    wfd_ts_base_deactivate_program (base, old_program);
+    wfd_ts_base_free_program (old_program);
+    initial_program = FALSE;
+  } else
+    program = old_program;
+
+  /* activate program */
+  /* Ownership of pmt_info is given to the program */
+  wfd_ts_base_activate_program (base, program, section->pid, section, pmt,
+      initial_program);
+
+  return TRUE;
+
+no_program:
+  {
+    GST_ERROR ("Attempted to apply a PMT on a program that wasn't created");
+    return TRUE;
+  }
+
+same_program:
+  {
+    GST_DEBUG ("Not applying identical program");
+    return TRUE;
+  }
+}
+
+static void
+wfd_ts_base_handle_psi (WFDTSBase * base, GstWFDTSSection * section)
+{
+  gboolean post_message = TRUE;
+
+  GST_DEBUG ("Handling PSI (pid: 0x%04x , table_id: 0x%02x)",
+      section->pid, section->table_id);
+
+  switch (section->section_type) {
+    case GST_WFD_TS_SECTION_PAT:
+      post_message = wfd_ts_base_apply_pat (base, section);
+      if (base->seen_pat == FALSE) {
+        base->seen_pat = TRUE;
+        GST_DEBUG ("First PAT offset: %" G_GUINT64_FORMAT, section->offset);
+        wfd_ts_packetizer_set_reference_offset (base->packetizer,
+            section->offset);
+      }
+      break;
+    case GST_WFD_TS_SECTION_PMT:
+      post_message = wfd_ts_base_apply_pmt (base, section);
+      break;
+#ifdef ENABLE_ALL
+    case GST_WFD_TS_SECTION_EIT:
+      /* some tag xtraction + posting */
+      post_message = wfd_ts_base_get_tags_from_eit (base, section);
+      break;
+    case GST_WFD_TS_SECTION_ATSC_MGT:
+      post_message = wfd_ts_base_parse_atsc_mgt (base, section);
+      break;
+#endif
+    default:
+      break;
+  }
+
+  /* Finally post message (if it wasn't corrupted) */
+  if (post_message)
+    gst_element_post_message (GST_ELEMENT_CAST (base),
+        gst_message_new_wfd_ts_section (GST_OBJECT (base), section));
+  gst_wfd_ts_section_unref (section);
+}
+
+#ifdef ENABLE_ALL
+static gboolean
+wfd_ts_base_parse_atsc_mgt (WFDTSBase * base, GstWFDTSSection * section)
+{
+  const GstMpegtsAtscMGT *mgt;
+  gint i;
+
+  mgt = gst_mpegts_section_get_atsc_mgt (section);
+  if (G_UNLIKELY (mgt == NULL))
+    return FALSE;
+
+  for (i = 0; i < mgt->tables->len; ++i) {
+    GstMpegtsAtscMGTTable *table = g_ptr_array_index (mgt->tables, i);
+
+    if ((table->table_type >= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_EIT0 &&
+            table->table_type <= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_EIT127) ||
+        (table->table_type >= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_ETT0 &&
+            table->table_type <= GST_MPEGTS_ATSC_MGT_TABLE_TYPE_ETT127)) {
+      WFD_TS_BIT_SET (base->known_psi, table->pid);
+    }
+  }
+
+  return TRUE;
+}
+
+static gboolean
+wfd_ts_base_get_tags_from_eit (WFDTSBase * base, GstWFDTSSection * section)
+{
+  const GstMpegtsEIT *eit;
+  guint i;
+  WFDTSBaseProgram *program;
+
+  /* Early exit if it's not from the present/following table_id */
+  if (section->table_id != GST_MTS_TABLE_ID_EVENT_INFORMATION_ACTUAL_TS_PRESENT
+      || section->table_id !=
+      GST_MTS_TABLE_ID_EVENT_INFORMATION_OTHER_TS_PRESENT)
+    return TRUE;
+
+  eit = gst_mpegts_section_get_eit (section);
+  if (G_UNLIKELY (eit == NULL))
+    return FALSE;
+
+  program = wfd_ts_base_get_program (base, section->subtable_extension);
+
+  GST_DEBUG
+      ("program_id:0x%04x, table_id:0x%02x, actual_stream:%d, present_following:%d, program:%p",
+      section->subtable_extension, section->table_id, eit->actual_stream,
+      eit->present_following, program);
+
+  if (program && eit->present_following) {
+    for (i = 0; i < eit->events->len; i++) {
+      GstMpegtsEITEvent *event = g_ptr_array_index (eit->events, i);
+      const GstWFDTSDescriptor *desc;
+
+      if (event->running_status == RUNNING_STATUS_RUNNING) {
+        program->event_id = event->event_id;
+        if ((desc =
+                gst_wfd_ts_find_descriptor (event->descriptors,
+                    GST_MTS_DESC_DVB_SHORT_EVENT))) {
+          gchar *name;
+          if (gst_mpegts_descriptor_parse_dvb_short_event (desc, NULL, &name,
+                  NULL)) {
+            /* FIXME : Is it correct to post an event duration as a GST_TAG_DURATION ??? */
+            program->tags =
+                gst_tag_list_new (GST_TAG_TITLE, name, GST_TAG_DURATION,
+                event->duration * GST_SECOND, NULL);
+            return TRUE;
+          }
+        }
+      }
+    }
+  }
+
+  return TRUE;
+}
+#endif
+
+static gboolean
+remove_each_program (gpointer key, WFDTSBaseProgram * program,
+    WFDTSBase * base)
+{
+  /* First deactivate it */
+  wfd_ts_base_deactivate_program (base, program);
+
+  return TRUE;
+}
+
+static inline GstFlowReturn
+wfd_ts_base_drain (WFDTSBase * base)
+{
+  WFDTSBaseClass *klass = GST_WFD_TS_BASE_GET_CLASS (base);
+
+  /* Call implementation */
+  if (klass->drain)
+    return klass->drain (base);
+
+  return GST_FLOW_OK;
+}
+
+static inline void
+wfd_ts_base_flush (WFDTSBase * base, gboolean hard)
+{
+  WFDTSBaseClass *klass = GST_WFD_TS_BASE_GET_CLASS (base);
+
+  /* Call implementation */
+  if (klass->flush)
+    klass->flush (base, hard);
+}
+
+static gboolean
+wfd_ts_base_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
+{
+  gboolean res = TRUE;
+  gboolean hard;
+  WFDTSBase *base = GST_WFD_TS_BASE (parent);
+
+  GST_DEBUG_OBJECT (base, "Got event %s",
+      gst_event_type_get_name (GST_EVENT_TYPE (event)));
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_SEGMENT:
+      gst_event_copy_segment (event, &base->segment);
+      GST_DEBUG_OBJECT (base, "Received segment %" GST_SEGMENT_FORMAT,
+          &base->segment);
+      /* Check if we need to switch PCR/PTS handling */
+      if (base->segment.format == GST_FORMAT_TIME) {
+        base->packetizer->calculate_offset = FALSE;
+        base->packetizer->calculate_skew = TRUE;
+      } else {
+        base->packetizer->calculate_offset = TRUE;
+        base->packetizer->calculate_skew = FALSE;
+      }
+      res = GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base, event);
+      break;
+    case GST_EVENT_STREAM_START:
+      gst_event_unref (event);
+      break;
+    case GST_EVENT_CAPS:
+      /* FIXME, do something */
+      gst_event_unref (event);
+      break;
+    case GST_EVENT_FLUSH_STOP:
+      res = GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base, event);
+      hard = (base->mode != BASE_MODE_SEEKING);
+      wfd_ts_packetizer_flush (base->packetizer, hard);
+      wfd_ts_base_flush (base, hard);
+      gst_segment_init (&base->segment, GST_FORMAT_UNDEFINED);
+      base->seen_pat = FALSE;
+      break;
+    default:
+      res = GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base, event);
+  }
+
+  /* Always return TRUE for sticky events */
+  if (GST_EVENT_IS_STICKY (event))
+    res = TRUE;
+
+  return res;
+}
+
+static void
+query_upstream_latency (WFDTSBase * base)
+{
+  GstQuery *query;
+
+  query = gst_query_new_latency ();
+  if (gst_pad_peer_query (base->sinkpad, query)) {
+    gst_query_parse_latency (query, &base->upstream_live, NULL, NULL);
+    GST_DEBUG_OBJECT (base, "Upstream is %s",
+        base->upstream_live ? "LIVE" : "NOT LIVE");
+  } else
+    GST_WARNING_OBJECT (base, "Failed to query upstream latency");
+  gst_query_unref (query);
+  base->queried_latency = TRUE;
+}
+
+static GstFlowReturn
+wfd_ts_base_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
+{
+  GstFlowReturn res = GST_FLOW_OK;
+  WFDTSBase *base;
+  WFDTSPacketizerPacketReturn pret;
+  WFDTSPacketizer *packetizer;
+  WFDTSPacketizerPacket packet;
+  WFDTSBaseClass *klass;
+
+  base = GST_WFD_TS_BASE (parent);
+  klass = GST_WFD_TS_BASE_GET_CLASS (base);
+
+  packetizer = base->packetizer;
+
+  if (G_UNLIKELY (base->queried_latency == FALSE)) {
+    query_upstream_latency (base);
+  }
+
+  if (klass->input_done)
+    gst_buffer_ref (buf);
+
+#if 0
+  if (GST_BUFFER_IS_DISCONT (buf)) {
+    GST_DEBUG_OBJECT (base, "Got DISCONT buffer, flushing");
+    res = wfd_ts_base_drain (base);
+    if (G_UNLIKELY (res != GST_FLOW_OK))
+      return res;
+
+    wfd_ts_base_flush (base, FALSE);
+    wfd_ts_packetizer_flush (base->packetizer, FALSE);
+  }
+#endif
+
+  wfd_ts_packetizer_push (base->packetizer, buf);
+
+  while (res == GST_FLOW_OK) {
+    pret = wfd_ts_packetizer_next_packet (base->packetizer, &packet);
+
+    /* If we don't have enough data, return */
+    if (G_UNLIKELY (pret == PACKET_NEED_MORE))
+      break;
+
+    if (G_UNLIKELY (pret == PACKET_BAD)) {
+      /* bad header, skip the packet */
+      GST_DEBUG_OBJECT (base, "bad packet, skipping");
+      goto next;
+    }
+
+    /* If it's a known PES, push it */
+    if (WFD_TS_BIT_IS_SET (base->is_pes, packet.pid)) {
+      /* push the packet downstream */
+      if (base->push_data)
+        res = klass->push (base, &packet, NULL);
+    } else if (packet.payload
+        && WFD_TS_BIT_IS_SET (base->known_psi, packet.pid)) {
+      /* base PSI data */
+      GList *others, *tmp;
+      GstWFDTSSection *section;
+
+      section = wfd_ts_packetizer_push_section (packetizer, &packet, &others);
+      if (section)
+        wfd_ts_base_handle_psi (base, section);
+      if (G_UNLIKELY (others)) {
+        for (tmp = others; tmp; tmp = tmp->next)
+          wfd_ts_base_handle_psi (base, (GstWFDTSSection *) tmp->data);
+        g_list_free (others);
+      }
+
+      /* we need to push section packet downstream */
+      if (base->push_section)
+        res = klass->push (base, &packet, section);
+
+    } else if (packet.payload && packet.pid != 0x1fff)
+      GST_LOG ("PID 0x%04x Saw packet on a pid we don't handle", packet.pid);
+
+  next:
+    wfd_ts_packetizer_clear_packet (base->packetizer, &packet);
+  }
+
+  if (klass->input_done) {
+    if (res == GST_FLOW_OK)
+      res = klass->input_done (base, buf);
+    else
+      gst_buffer_unref (buf);
+  }
+
+  return res;
+}
+
+static GstFlowReturn
+wfd_ts_base_scan (WFDTSBase * base)
+{
+  GstFlowReturn ret = GST_FLOW_OK;
+  GstBuffer *buf = NULL;
+  guint i;
+  gboolean done = FALSE;
+  WFDTSPacketizerPacketReturn pret;
+  gint64 tmpval;
+  gint64 upstream_size, seek_pos;
+  GstFormat format;
+  guint initial_pcr_seen;
+
+  GST_DEBUG ("Scanning for initial sync point");
+
+  /* Find initial sync point and at least 5 PCR values */
+  for (i = 0; i < 20 && !done; i++) {
+    GST_DEBUG ("Grabbing %d => %d", i * 65536, 65536);
+
+    ret = gst_pad_pull_range (base->sinkpad, i * 65536, 65536, &buf);
+    if (G_UNLIKELY (ret == GST_FLOW_EOS))
+      break;
+    if (G_UNLIKELY (ret != GST_FLOW_OK))
+      goto beach;
+
+    /* Push to packetizer */
+    wfd_ts_packetizer_push (base->packetizer, buf);
+    buf = NULL;
+
+    if (wfd_ts_packetizer_has_packets (base->packetizer)) {
+      if (base->seek_offset == -1) {
+        /* Mark the initial sync point and remember the packetsize */
+        base->seek_offset = base->packetizer->offset;
+        GST_DEBUG ("Sync point is now %" G_GUINT64_FORMAT, base->seek_offset);
+        base->packetsize = base->packetizer->packet_size;
+      }
+      while (1) {
+        /* Eat up all packets */
+        pret = wfd_ts_packetizer_process_next_packet (base->packetizer);
+        if (pret == PACKET_NEED_MORE)
+          break;
+        if (pret != PACKET_BAD && base->packetizer->nb_seen_offsets >= 5) {
+          GST_DEBUG ("Got enough initial PCR");
+          done = TRUE;
+          break;
+        }
+      }
+    }
+  }
+
+  initial_pcr_seen = base->packetizer->nb_seen_offsets;
+  if (G_UNLIKELY (initial_pcr_seen == 0))
+    goto no_initial_pcr;
+  GST_DEBUG ("Seen %d initial PCR", initial_pcr_seen);
+
+  /* Now send data from the end */
+  wfd_ts_packetizer_clear (base->packetizer);
+
+  /* Get the size of upstream */
+  format = GST_FORMAT_BYTES;
+  if (!gst_pad_peer_query_duration (base->sinkpad, format, &tmpval))
+    goto beach;
+  upstream_size = tmpval;
+  done = FALSE;
+
+  /* Find last PCR value */
+  for (seek_pos = MAX (0, upstream_size - 655360);
+      seek_pos < upstream_size && !done; seek_pos += 65536) {
+    GST_DEBUG ("Grabbing %" G_GUINT64_FORMAT " => %d", seek_pos, 65536);
+
+    ret = gst_pad_pull_range (base->sinkpad, seek_pos, 65536, &buf);
+    if (G_UNLIKELY (ret == GST_FLOW_EOS))
+      break;
+    if (G_UNLIKELY (ret != GST_FLOW_OK))
+      goto beach;
+
+    /* Push to packetizer */
+    wfd_ts_packetizer_push (base->packetizer, buf);
+    buf = NULL;
+
+    if (wfd_ts_packetizer_has_packets (base->packetizer)) {
+      while (1) {
+        /* Eat up all packets */
+        pret = wfd_ts_packetizer_process_next_packet (base->packetizer);
+        if (pret == PACKET_NEED_MORE)
+          break;
+        if (pret != PACKET_BAD &&
+            base->packetizer->nb_seen_offsets > initial_pcr_seen) {
+          GST_DEBUG ("Got last PCR");
+          done = TRUE;
+          break;
+        }
+      }
+    }
+  }
+
+beach:
+  wfd_ts_packetizer_clear (base->packetizer);
+  return ret;
+
+no_initial_pcr:
+  wfd_ts_packetizer_clear (base->packetizer);
+  GST_WARNING_OBJECT (base, "Couldn't find any PCR within the first %d bytes",
+      10 * 65536);
+  return GST_FLOW_ERROR;
+}
+
+
+static void
+wfd_ts_base_loop (WFDTSBase * base)
+{
+  GstFlowReturn ret = GST_FLOW_ERROR;
+
+  switch (base->mode) {
+    case BASE_MODE_SCANNING:
+      /* Find first sync point */
+      ret = wfd_ts_base_scan (base);
+      if (G_UNLIKELY (ret != GST_FLOW_OK))
+        goto error;
+      base->mode = BASE_MODE_STREAMING;
+      GST_DEBUG ("Changing to Streaming");
+      break;
+    case BASE_MODE_SEEKING:
+      /* FIXME : unclear if we still need mode_seeking... */
+      base->mode = BASE_MODE_STREAMING;
+      break;
+    case BASE_MODE_STREAMING:
+    {
+      GstBuffer *buf = NULL;
+
+      GST_DEBUG ("Pulling data from %" G_GUINT64_FORMAT, base->seek_offset);
+
+      ret = gst_pad_pull_range (base->sinkpad, base->seek_offset,
+          100 * base->packetsize, &buf);
+      if (G_UNLIKELY (ret != GST_FLOW_OK))
+        goto error;
+      base->seek_offset += gst_buffer_get_size (buf);
+      ret = wfd_ts_base_chain (base->sinkpad, GST_OBJECT_CAST (base), buf);
+      if (G_UNLIKELY (ret != GST_FLOW_OK))
+        goto error;
+    }
+      break;
+    case BASE_MODE_PUSHING:
+      GST_WARNING ("wrong BASE_MODE_PUSHING mode in pull loop");
+      break;
+  }
+
+  return;
+
+error:
+  {
+    const gchar *reason = gst_flow_get_name (ret);
+    GST_DEBUG_OBJECT (base, "Pausing task, reason %s", reason);
+    if (ret == GST_FLOW_EOS) {
+      if (!GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base,
+              gst_event_new_eos ()))
+        GST_ELEMENT_ERROR (base, STREAM, FAILED,
+            (("Internal data stream error.")),
+            ("No program activated before EOS"));
+    } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
+      GST_ELEMENT_ERROR (base, STREAM, FAILED,
+          (("Internal data stream error.")),
+          ("stream stopped, reason %s", reason));
+      GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base, gst_event_new_eos ());
+    }
+    gst_pad_pause_task (base->sinkpad);
+  }
+}
+
+
+gboolean
+wfd_ts_base_handle_seek_event (WFDTSBase * base, GstPad * pad,
+    GstEvent * event)
+{
+  WFDTSBaseClass *klass = GST_WFD_TS_BASE_GET_CLASS (base);
+  GstFlowReturn ret = GST_FLOW_ERROR;
+  gdouble rate;
+  gboolean flush;
+  GstFormat format;
+  GstSeekFlags flags;
+  GstSeekType start_type, stop_type;
+  gint64 start, stop;
+  GstEvent *flush_event = NULL;
+
+  gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
+      &stop_type, &stop);
+
+  if (format != GST_FORMAT_TIME)
+    return FALSE;
+
+  if (GST_EVENT_SEQNUM (event) == base->last_seek_seqnum) {
+    GST_DEBUG_OBJECT (base, "Skipping already handled seek");
+    return TRUE;
+  }
+
+  if (base->mode == BASE_MODE_PUSHING) {
+    /* First try if upstream supports seeking in TIME format */
+    if (gst_pad_push_event (base->sinkpad, gst_event_ref (event))) {
+      GST_DEBUG ("upstream handled SEEK event");
+      return TRUE;
+    }
+
+    /* If the subclass can seek, do that */
+    if (klass->seek) {
+      ret = klass->seek (base, event);
+      if (G_UNLIKELY (ret != GST_FLOW_OK))
+        GST_WARNING ("seeking failed %s", gst_flow_get_name (ret));
+      else {
+        GstEvent *new_seek;
+        base->mode = BASE_MODE_SEEKING;
+
+        new_seek = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
+            GST_SEEK_TYPE_SET, base->seek_offset, GST_SEEK_TYPE_NONE, -1);
+        gst_event_set_seqnum (new_seek, GST_EVENT_SEQNUM (event));
+        if (!gst_pad_push_event (base->sinkpad, new_seek))
+          ret = GST_FLOW_ERROR;
+        else
+          base->last_seek_seqnum = GST_EVENT_SEQNUM (event);
+        base->mode = BASE_MODE_PUSHING;
+      }
+    }
+
+    return ret == GST_FLOW_OK;
+  }
+
+  GST_DEBUG ("seek event, rate: %f start: %" GST_TIME_FORMAT
+      " stop: %" GST_TIME_FORMAT, rate, GST_TIME_ARGS (start),
+      GST_TIME_ARGS (stop));
+
+  flush = flags & GST_SEEK_FLAG_FLUSH;
+
+  /* stop streaming, either by flushing or by pausing the task */
+  base->mode = BASE_MODE_SEEKING;
+  if (flush) {
+    GST_DEBUG_OBJECT (base, "sending flush start");
+    flush_event = gst_event_new_flush_start ();
+    gst_event_set_seqnum (flush_event, GST_EVENT_SEQNUM (event));
+    gst_pad_push_event (base->sinkpad, gst_event_ref (flush_event));
+    GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base, flush_event);
+  } else
+    gst_pad_pause_task (base->sinkpad);
+
+  /* wait for streaming to finish */
+  GST_PAD_STREAM_LOCK (base->sinkpad);
+
+  if (flush) {
+    /* send a FLUSH_STOP for the sinkpad, since we need data for seeking */
+    GST_DEBUG_OBJECT (base, "sending flush stop");
+    flush_event = gst_event_new_flush_stop (TRUE);
+    gst_event_set_seqnum (flush_event, GST_EVENT_SEQNUM (event));
+
+    /* ref for it to be reused later */
+    gst_pad_push_event (base->sinkpad, gst_event_ref (flush_event));
+    /* And actually flush our pending data but allow to preserve some info
+     * to perform the seek */
+    wfd_ts_base_flush (base, FALSE);
+    wfd_ts_packetizer_flush (base->packetizer, FALSE);
+  }
+
+  if (flags & (GST_SEEK_FLAG_SEGMENT)) {
+    GST_WARNING ("seek flags 0x%x are not supported", (int) flags);
+    goto done;
+  }
+
+
+  /* If the subclass can seek, do that */
+  if (klass->seek) {
+    ret = klass->seek (base, event);
+    if (G_UNLIKELY (ret != GST_FLOW_OK))
+      GST_WARNING ("seeking failed %s", gst_flow_get_name (ret));
+    else
+      base->last_seek_seqnum = GST_EVENT_SEQNUM (event);
+  } else {
+    /* FIXME : Check this before so we don't do seeks we can't handle ? */
+    GST_WARNING ("subclass has no seek implementation");
+  }
+
+  if (flush_event) {
+    /* if we sent a FLUSH_START, we now send a FLUSH_STOP */
+    GST_DEBUG_OBJECT (base, "sending flush stop");
+    GST_WFD_TS_BASE_GET_CLASS (base)->push_event (base, flush_event);
+    flush_event = NULL;
+  }
+done:
+  if (flush_event)
+    gst_event_unref (flush_event);
+  gst_pad_start_task (base->sinkpad, (GstTaskFunction) wfd_ts_base_loop, base,
+      NULL);
+
+  GST_PAD_STREAM_UNLOCK (base->sinkpad);
+  return ret == GST_FLOW_OK;
+}
+
+
+static gboolean
+wfd_ts_base_sink_activate (GstPad * sinkpad, GstObject * parent)
+{
+  GstQuery *query;
+  gboolean pull_mode;
+
+  query = gst_query_new_scheduling ();
+
+  if (!gst_pad_peer_query (sinkpad, query)) {
+    gst_query_unref (query);
+    goto activate_push;
+  }
+
+  pull_mode = gst_query_has_scheduling_mode_with_flags (query,
+      GST_PAD_MODE_PULL, GST_SCHEDULING_FLAG_SEEKABLE);
+  gst_query_unref (query);
+
+  if (!pull_mode)
+    goto activate_push;
+
+  GST_DEBUG_OBJECT (sinkpad, "activating pull");
+  return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE);
+
+activate_push:
+  {
+    GST_DEBUG_OBJECT (sinkpad, "activating push");
+    return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
+  }
+}
+
+static gboolean
+wfd_ts_base_sink_activate_mode (GstPad * pad, GstObject * parent,
+    GstPadMode mode, gboolean active)
+{
+  gboolean res;
+  WFDTSBase *base = GST_WFD_TS_BASE (parent);
+
+  switch (mode) {
+    case GST_PAD_MODE_PUSH:
+      base->mode = BASE_MODE_PUSHING;
+      res = TRUE;
+      break;
+    case GST_PAD_MODE_PULL:
+      if (active) {
+        base->mode = BASE_MODE_SCANNING;
+        /* When working pull-based, we always use offsets for estimation */
+        base->packetizer->calculate_offset = TRUE;
+        base->packetizer->calculate_skew = FALSE;
+        gst_segment_init (&base->segment, GST_FORMAT_BYTES);
+        res =
+            gst_pad_start_task (pad, (GstTaskFunction) wfd_ts_base_loop, base,
+            NULL);
+      } else
+        res = gst_pad_stop_task (pad);
+      break;
+    default:
+      res = FALSE;
+      break;
+  }
+  return res;
+}
+
+static GstStateChangeReturn
+wfd_ts_base_change_state (GstElement * element, GstStateChange transition)
+{
+  WFDTSBase *base;
+  GstStateChangeReturn ret;
+
+  base = GST_WFD_TS_BASE (element);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      wfd_ts_base_reset (base);
+      break;
+    default:
+      break;
+  }
+
+  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
+
+  switch (transition) {
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      wfd_ts_base_reset (base);
+      if (base->mode != BASE_MODE_PUSHING)
+        base->mode = BASE_MODE_SCANNING;
+      break;
+    default:
+      break;
+  }
+
+  return ret;
+}
+
+gboolean
+gst_wfdtsbase_plugin_init (GstPlugin * plugin)
+{
+  GST_DEBUG_CATEGORY_INIT (wfd_ts_base_debug, "wfdtsbase", 0,
+      "Wi-Fi Display transport stream base class");
+
+  return TRUE;
+}
diff --git a/wfdtsdemux/wfdtsbase.h b/wfdtsdemux/wfdtsbase.h
new file mode 100755 (executable)
index 0000000..5a93d99
--- /dev/null
@@ -0,0 +1,229 @@
+/*
+ * wfdtsbase.h - GStreamer MPEG transport stream base class
+ * Copyright (C) 2009 Edward Hervey <edward.hervey@collabora.co.uk>
+ *               2007 Alessandro Decina
+ * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
+ *  Author: Youness Alaoui <youness.alaoui@collabora.co.uk>, Collabora Ltd.
+ *  Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
+ *
+ * Authors:
+ *   Alessandro Decina <alessandro@nnva.org>
+ *   Edward Hervey <edward.hervey@collabora.co.uk>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef GST_WFD_TS_BASE_H
+#define GST_WFD_TS_BASE_H
+
+#include <gst/gst.h>
+#include "wfdtspacketizer.h"
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_WFD_TS_BASE \
+  (wfd_ts_base_get_type())
+#define GST_WFD_TS_BASE(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_WFD_TS_BASE,WFDTSBase))
+#define GST_WFD_TS_BASE_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_WFD_TS_BASE,WFDTSBaseClass))
+#define GST_IS_WFD_TS_BASE(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_TS_BASE))
+#define GST_IS_WFD_TS_BASE_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_TS_BASE))
+#define GST_WFD_TS_BASE_GET_CLASS(obj) \
+  (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_WFD_TS_BASE, WFDTSBaseClass))
+
+#define MPEG_TS_BASE_PACKETIZER(b) (((WFDTSBase*)b)->packetizer)
+
+typedef struct _WFDTSBase WFDTSBase;
+typedef struct _WFDTSBaseClass WFDTSBaseClass;
+typedef struct _WFDTSBaseStream WFDTSBaseStream;
+typedef struct _WFDTSBaseProgram WFDTSBaseProgram;
+
+struct _WFDTSBaseStream
+{
+  guint16             pid;
+  guint8              stream_type;
+
+  /* Content of the registration descriptor (if present) */
+  guint32             registration_id;
+
+  GstWFDTSPMTStream *stream;
+};
+
+struct _WFDTSBaseProgram
+{
+  gint                program_number;
+  guint16             pmt_pid;
+  guint16             pcr_pid;
+
+  /* Content of the registration descriptor (if present) */
+  guint32             registration_id;
+
+  GstWFDTSSection   *section;
+  const GstWFDTSPMT *pmt;
+
+  WFDTSBaseStream  **streams;
+  GList              *stream_list;
+  gint                patcount;
+
+  /* Pending Tags for the program */
+  GstTagList *tags;
+  guint event_id;
+
+  /* TRUE if the program is currently being used */
+  gboolean active;
+  /* TRUE if this is the first program created */
+  gboolean initial_program;
+};
+
+typedef enum {
+  /* PULL MODE */
+  BASE_MODE_SCANNING,          /* Looking for PAT/PMT */
+  BASE_MODE_SEEKING,           /* Seeking */
+  BASE_MODE_STREAMING,         /* Normal mode (pushing out data) */
+
+  /* PUSH MODE */
+  BASE_MODE_PUSHING
+} WFDTSBaseMode;
+
+struct _WFDTSBase {
+  GstElement element;
+
+  GstPad *sinkpad;
+
+  /* pull-based behaviour */
+  WFDTSBaseMode mode;
+
+  /* Current pull offset (also set by seek handler) */
+  guint64      seek_offset;
+
+  /* Cached packetsize */
+  guint16      packetsize;
+
+  /* the following vars must be protected with the OBJECT_LOCK as they can be
+   * accessed from the application thread and the streaming thread */
+  GHashTable *programs;
+
+  GPtrArray  *pat;
+  WFDTSPacketizer *packetizer;
+
+  /* arrays that say whether a pid is a known psi pid or a pes pid */
+  /* Use WFD_TS_BIT_* to set/unset/check the values */
+  guint8 *known_psi;
+  guint8 *is_pes;
+
+  gboolean disposed;
+
+  /* size of the WFDTSBaseProgram structure, can be overridden
+   * by subclasses if they have their own WFDTSBaseProgram subclasses. */
+  gsize program_size;
+
+  /* size of the WFDTSBaseStream structure, can be overridden
+   * by subclasses if they have their own WFDTSBaseStream subclasses */
+  gsize stream_size;
+
+  /* Whether we saw a PAT yet */
+  gboolean seen_pat;
+
+  /* Whether upstream is live or not */
+  gboolean upstream_live;
+  /* Whether we queried the upstream latency or not */
+  gboolean queried_latency;
+
+  /* Upstream segment */
+  GstSegment segment;
+
+  /* Last received seek event seqnum (default -1) */
+  guint last_seek_seqnum;
+
+  /* Whether to parse private section or not */
+  gboolean parse_private_sections;
+
+  /* Whether to push data and/or sections to subclasses */
+  gboolean push_data;
+  gboolean push_section;
+};
+
+struct _WFDTSBaseClass {
+  GstElementClass parent_class;
+
+  /* Virtual methods */
+  void (*reset) (WFDTSBase *base);
+  GstFlowReturn (*push) (WFDTSBase *base, WFDTSPacketizerPacket *packet, GstWFDTSSection * section);
+  /* takes ownership of @event */
+  gboolean (*push_event) (WFDTSBase *base, GstEvent * event);
+
+  /* program_started gets called when program's pmt arrives for first time */
+  void (*program_started) (WFDTSBase *base, WFDTSBaseProgram *program);
+  /* program_stopped gets called when pat no longer has program's pmt */
+  void (*program_stopped) (WFDTSBase *base, WFDTSBaseProgram *program);
+
+  /* stream_added is called whenever a new stream has been identified */
+  void (*stream_added) (WFDTSBase *base, WFDTSBaseStream *stream, WFDTSBaseProgram *program);
+  /* stream_removed is called whenever a stream is no longer referenced */
+  void (*stream_removed) (WFDTSBase *base, WFDTSBaseStream *stream);
+
+  /* find_timestamps is called to find PCR */
+  GstFlowReturn (*find_timestamps) (WFDTSBase * base, guint64 initoff, guint64 *offset);
+
+  /* seek is called to wait for seeking */
+  GstFlowReturn (*seek) (WFDTSBase * base, GstEvent * event);
+
+  /* Drain all currently pending data */
+  GstFlowReturn (*drain) (WFDTSBase * base);
+
+  /* flush all streams
+   * The hard inicator is used to flush completelly on FLUSH_STOP events
+   * or partially in pull mode seeks of tsdemux */
+  void (*flush) (WFDTSBase * base, gboolean hard);
+
+  /* Notifies subclasses input buffer has been handled */
+  GstFlowReturn (*input_done) (WFDTSBase *base, GstBuffer *buffer);
+
+  /* signals */
+  void (*pat_info) (GstStructure *pat);
+  void (*pmt_info) (GstStructure *pmt);
+  void (*nit_info) (GstStructure *nit);
+  void (*sdt_info) (GstStructure *sdt);
+  void (*eit_info) (GstStructure *eit);
+};
+
+#define WFD_TS_BIT_SET(field, offs)    ((field)[(offs) >> 3] |=  (1 << ((offs) & 0x7)))
+#define WFD_TS_BIT_UNSET(field, offs)  ((field)[(offs) >> 3] &= ~(1 << ((offs) & 0x7)))
+#define WFD_TS_BIT_IS_SET(field, offs) ((field)[(offs) >> 3] &   (1 << ((offs) & 0x7)))
+
+G_GNUC_INTERNAL GType wfd_ts_base_get_type(void);
+
+G_GNUC_INTERNAL WFDTSBaseProgram *wfd_ts_base_get_program (WFDTSBase * base, gint program_number);
+G_GNUC_INTERNAL WFDTSBaseProgram *wfd_ts_base_add_program (WFDTSBase * base, gint program_number, guint16 pmt_pid);
+
+G_GNUC_INTERNAL const GstWFDTSDescriptor *wfd_ts_get_descriptor_from_stream (WFDTSBaseStream * stream, guint8 tag);
+G_GNUC_INTERNAL const GstWFDTSDescriptor *wfd_ts_get_descriptor_from_program (WFDTSBaseProgram * program, guint8 tag);
+
+G_GNUC_INTERNAL gboolean
+wfd_ts_base_handle_seek_event(WFDTSBase * base, GstPad * pad, GstEvent * event);
+
+G_GNUC_INTERNAL gboolean gst_wfdtsbase_plugin_init (GstPlugin * plugin);
+
+G_GNUC_INTERNAL void wfd_ts_base_program_remove_stream (WFDTSBase * base, WFDTSBaseProgram * program, guint16 pid);
+
+G_GNUC_INTERNAL void wfd_ts_base_remove_program(WFDTSBase *base, gint program_number);
+G_END_DECLS
+
+#endif /* GST_WFD_TS_BASE_H */
diff --git a/wfdtsdemux/wfdtsdemux.c b/wfdtsdemux/wfdtsdemux.c
new file mode 100755 (executable)
index 0000000..cf9cc38
--- /dev/null
@@ -0,0 +1,2253 @@
+/*
+ * tsdemux.c
+ * Copyright (C) 2009 Zaheer Abbas Merali
+ *               2010 Edward Hervey
+ * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
+ *  Author: Youness Alaoui <youness.alaoui@collabora.co.uk>, Collabora Ltd.
+ *  Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
+ *  Author: Edward Hervey <bilboed@bilboed.com>, Collabora Ltd.
+ *
+ * Authors:
+ *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
+ *   Edward Hervey <edward.hervey@collabora.co.uk>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <glib.h>
+#include <gst/tag/tag.h>
+#include <gst/pbutils/pbutils.h>
+
+#include "wfdtsbase.h"
+#include "wfdtsdemux.h"
+#include "gstwfdtsdesc.h"
+#include "gstwfdtsdefs.h"
+#include "wfdtspacketizer.h"
+#include "wfdpesparse.h"
+#include "gstwfdh264parser.h"
+#include <gst/base/gstbytewriter.h>
+
+/*
+ * tsdemux
+ *
+ * See TODO for explanations on improvements needed
+ */
+
+#define CONTINUITY_UNSET 255
+#define MAX_CONTINUITY 15
+
+/* Seeking/Scanning related variables */
+
+/* seek to SEEK_TIMESTAMP_OFFSET before the desired offset and search then
+ * either accurately or for the next timestamp
+ */
+#define SEEK_TIMESTAMP_OFFSET (2500 * GST_MSECOND)
+
+#define SEGMENT_FORMAT "[format:%s, rate:%f, start:%"                  \
+  GST_TIME_FORMAT", stop:%"GST_TIME_FORMAT", time:%"GST_TIME_FORMAT    \
+  ", base:%"GST_TIME_FORMAT", position:%"GST_TIME_FORMAT               \
+  ", duration:%"GST_TIME_FORMAT"]"
+
+#define SEGMENT_ARGS(a) gst_format_get_name((a).format), (a).rate,     \
+    GST_TIME_ARGS((a).start), GST_TIME_ARGS((a).stop),                 \
+    GST_TIME_ARGS((a).time), GST_TIME_ARGS((a).base),                  \
+    GST_TIME_ARGS((a).position), GST_TIME_ARGS((a).duration)
+
+#define GST_FLOW_REWINDING GST_FLOW_CUSTOM_ERROR
+
+GST_DEBUG_CATEGORY_STATIC (wfd_ts_demux_debug);
+#define GST_CAT_DEFAULT wfd_ts_demux_debug
+
+#define ABSDIFF(a,b) (((a) > (b)) ? ((a) - (b)) : ((b) - (a)))
+
+static GQuark QUARK_TSDEMUX;
+static GQuark QUARK_PID;
+static GQuark QUARK_PCR;
+static GQuark QUARK_OPCR;
+static GQuark QUARK_PTS;
+static GQuark QUARK_DTS;
+static GQuark QUARK_OFFSET;
+
+typedef enum
+{
+  PENDING_PACKET_EMPTY = 0,     /* No pending packet/buffer
+                                 * Push incoming buffers to the array */
+  PENDING_PACKET_HEADER,        /* PES header needs to be parsed
+                                 * Push incoming buffers to the array */
+  PENDING_PACKET_BUFFER,        /* Currently filling up output buffer
+                                 * Push incoming buffers to the bufferlist */
+  PENDING_PACKET_DISCONT        /* Discontinuity in incoming packets
+                                 * Drop all incoming buffers */
+} PendingPacketState;
+
+/* Pending buffer */
+typedef struct
+{
+  /* The fully reconstructed buffer */
+  GstBuffer *buffer;
+
+  /* Raw PTS/DTS (in 90kHz units) */
+  guint64 pts, dts;
+} PendingBuffer;
+
+typedef struct _WFDTSDemuxStream WFDTSDemuxStream;
+typedef struct _WFDTSDemuxLPCMData WFDTSDemuxLPCMData;
+typedef struct _WFDTSDemuxH264ParsingInfos WFDTSDemuxH264ParsingInfos;
+
+/* Returns TRUE if a keyframe was found */
+typedef gboolean (*GstWFDTsDemuxKeyFrameScanFunction) (WFDTSDemuxStream * stream,
+    guint8 * data, const gsize data_size, const gsize max_frame_offset);
+
+typedef struct
+{
+  guint8 *data;
+  gsize size;
+} SimpleBuffer;
+
+struct _WFDTSDemuxH264ParsingInfos
+{
+  /* H264 parsing data */
+  GstWFDH264NalParser *parser;
+  GstByteWriter *sps;
+  GstByteWriter *pps;
+  GstByteWriter *sei;
+  SimpleBuffer framedata;
+};
+
+#ifdef WFD_SPEC
+struct _WFDTSDemuxLPCMData
+{
+  guint8 width;
+  guint8 channels;
+  guint rate;
+};
+#endif
+
+struct _WFDTSDemuxStream
+{
+  WFDTSBaseStream stream;
+
+  GstPad *pad;
+
+  /* Whether the pad was added or not */
+  gboolean active;
+
+  /* TRUE if we are waiting for a valid timestamp */
+  gboolean pending_ts;
+
+  /* Output data */
+  PendingPacketState state;
+
+  /* Data being reconstructed (allocated) */
+  guint8 *data;
+
+  /* Size of data being reconstructed (if known, else 0) */
+  guint expected_size;
+
+  /* Amount of bytes in current ->data */
+  guint current_size;
+  /* Size of ->data */
+  guint allocated_size;
+
+  /* Current PTS/DTS for this stream (in running time) */
+  GstClockTime pts;
+  GstClockTime dts;
+
+  /* Current PTS/DTS for this stream (in 90kHz unit) */
+  guint64 raw_pts, raw_dts;
+
+  /* Whether this stream needs to send a newsegment */
+  gboolean need_newsegment;
+
+  /* Whether the next output buffer should be DISCONT */
+  gboolean discont;
+
+  /* The value to use when calculating the newsegment */
+  GstClockTime first_dts;
+
+  GstTagList *taglist;
+
+  gint continuity_counter;
+
+  /* List of pending buffers */
+  GList *pending;
+
+  /* if != 0, output only PES from that substream */
+  guint8 target_pes_substream;
+  gboolean needs_keyframe;
+
+  GstClockTime seeked_pts, seeked_dts;
+
+  GstWFDTsDemuxKeyFrameScanFunction scan_function;
+  WFDTSDemuxH264ParsingInfos h264infos;
+#ifdef WFD_SPEC
+  WFDTSDemuxLPCMData lpcm_data;
+#endif
+};
+
+#define VIDEO_CAPS \
+  GST_STATIC_CAPS (\
+    "video/x-h264,stream-format=(string)byte-stream," \
+      "alignment=(string)nal;" \
+  )
+
+#define LPCM_CAPS "audio/x-raw, " \
+    "format = (string) S16BE, " \
+    "rate = (int) { 48000, 96000 }, " \
+    "channels = (int) [ 1, 8 ]; " \
+    "audio/x-lpcm, " \
+    "width = (int) { 16, 20, 24 }, " \
+    "rate = (int) { 48000, 96000 }, " \
+    "channels = (int) [ 1, 8 ], " \
+    "dynamic_range = (int) [ 0, 255 ], " \
+    "emphasis = (boolean) { FALSE, TRUE }, " \
+    "mute = (boolean) { FALSE, TRUE }; "
+
+#define AUDIO_CAPS \
+  GST_STATIC_CAPS ( \
+    "audio/mpeg, " \
+      "mpegversion = (int) 1;" \
+    "audio/mpeg, " \
+      "mpegversion = (int) 2, " \
+      "stream-format = (string) adts; " \
+    "audio/mpeg, " \
+      "mpegversion = (int) 4, " \
+      "stream-format = (string) loas; " \
+    LPCM_CAPS \
+    "audio/x-ac3; audio/x-eac3;" \
+  )
+
+static GstStaticPadTemplate video_template =
+GST_STATIC_PAD_TEMPLATE ("video_%04x", GST_PAD_SRC,
+    GST_PAD_SOMETIMES,
+    VIDEO_CAPS);
+
+static GstStaticPadTemplate audio_template =
+GST_STATIC_PAD_TEMPLATE ("audio_%04x",
+    GST_PAD_SRC,
+    GST_PAD_SOMETIMES,
+    AUDIO_CAPS);
+
+static GstStaticPadTemplate private_template =
+GST_STATIC_PAD_TEMPLATE ("private_%04x",
+    GST_PAD_SRC,
+    GST_PAD_SOMETIMES,
+    GST_STATIC_CAPS_ANY);
+
+enum
+{
+  ARG_0,
+  PROP_PROGRAM_NUMBER,
+  PROP_EMIT_STATS,
+  /* FILL ME */
+};
+
+/* Pad functions */
+
+
+/* mpegtsbase methods */
+static void
+gst_wfd_ts_demux_program_started (WFDTSBase * base, WFDTSBaseProgram * program);
+static void
+gst_wfd_ts_demux_program_stopped (WFDTSBase * base, WFDTSBaseProgram * program);
+static void gst_wfd_ts_demux_reset (WFDTSBase * base);
+static GstFlowReturn
+gst_wfd_ts_demux_push (WFDTSBase * base, WFDTSPacketizerPacket * packet,
+    GstWFDTSSection * section);
+static void gst_wfd_ts_demux_flush (WFDTSBase * base, gboolean hard);
+static GstFlowReturn gst_wfd_ts_demux_drain (WFDTSBase * base);
+static void
+gst_wfd_ts_demux_stream_added (WFDTSBase * base, WFDTSBaseStream * stream,
+    WFDTSBaseProgram * program);
+static void
+gst_wfd_ts_demux_stream_removed (WFDTSBase * base, WFDTSBaseStream * stream);
+static GstFlowReturn gst_wfd_ts_demux_do_seek (WFDTSBase * base, GstEvent * event);
+static void gst_wfd_ts_demux_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void gst_wfd_ts_demux_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+static void gst_wfd_ts_demux_flush_streams (GstWFDTSDemux * tsdemux);
+static GstFlowReturn
+gst_wfd_ts_demux_push_pending_data (GstWFDTSDemux * demux, WFDTSDemuxStream * stream);
+static void gst_wfd_ts_demux_stream_flush (WFDTSDemuxStream * stream,
+    GstWFDTSDemux * demux);
+
+static gboolean push_event (WFDTSBase * base, GstEvent * event);
+
+static void
+_extra_init (void)
+{
+  QUARK_TSDEMUX = g_quark_from_string ("tsdemux");
+  QUARK_PID = g_quark_from_string ("pid");
+  QUARK_PCR = g_quark_from_string ("pcr");
+  QUARK_OPCR = g_quark_from_string ("opcr");
+  QUARK_PTS = g_quark_from_string ("pts");
+  QUARK_DTS = g_quark_from_string ("dts");
+  QUARK_OFFSET = g_quark_from_string ("offset");
+}
+
+#define gst_wfd_ts_demux_parent_class parent_class
+G_DEFINE_TYPE_WITH_CODE (GstWFDTSDemux, gst_wfd_ts_demux, GST_TYPE_WFD_TS_BASE,
+    _extra_init ());
+
+static void
+gst_wfd_ts_demux_dispose (GObject * object)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX_CAST (object);
+
+  gst_flow_combiner_free (demux->flowcombiner);
+
+  GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
+}
+
+static void
+gst_wfd_ts_demux_class_init (GstWFDTSDemuxClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstElementClass *element_class;
+  WFDTSBaseClass *ts_class;
+
+  gobject_class = G_OBJECT_CLASS (klass);
+  gobject_class->set_property = gst_wfd_ts_demux_set_property;
+  gobject_class->get_property = gst_wfd_ts_demux_get_property;
+  gobject_class->dispose = gst_wfd_ts_demux_dispose;
+
+  g_object_class_install_property (gobject_class, PROP_PROGRAM_NUMBER,
+      g_param_spec_int ("program-number", "Program number",
+          "Program Number to demux for (-1 to ignore)", -1, G_MAXINT,
+          -1, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  g_object_class_install_property (gobject_class, PROP_EMIT_STATS,
+      g_param_spec_boolean ("emit-stats", "Emit statistics",
+          "Emit messages for every pcr/opcr/pts/dts", FALSE,
+          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+  element_class = GST_ELEMENT_CLASS (klass);
+  gst_element_class_add_pad_template (element_class,
+      gst_static_pad_template_get (&video_template));
+  gst_element_class_add_pad_template (element_class,
+      gst_static_pad_template_get (&audio_template));
+  gst_element_class_add_pad_template (element_class,
+      gst_static_pad_template_get (&private_template));
+
+  gst_element_class_set_static_metadata (element_class,
+      "Wi-Fi Display transport stream demuxer",
+      "Codec/Demuxer",
+      "Demuxes Wi-Fi Display transport streams",
+      "Zaheer Abbas Merali <zaheerabbas at merali dot org>\n"
+      "Edward Hervey <edward.hervey@collabora.co.uk>");
+
+  ts_class = GST_WFD_TS_BASE_CLASS (klass);
+  ts_class->reset = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_reset);
+  ts_class->push = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_push);
+  ts_class->push_event = GST_DEBUG_FUNCPTR (push_event);
+  ts_class->program_started = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_program_started);
+  ts_class->program_stopped = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_program_stopped);
+  ts_class->stream_added = gst_wfd_ts_demux_stream_added;
+  ts_class->stream_removed = gst_wfd_ts_demux_stream_removed;
+  ts_class->seek = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_do_seek);
+  ts_class->flush = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_flush);
+  ts_class->drain = GST_DEBUG_FUNCPTR (gst_wfd_ts_demux_drain);
+}
+
+static void
+gst_wfd_ts_demux_reset (WFDTSBase * base)
+{
+  GstWFDTSDemux *demux = (GstWFDTSDemux *) base;
+
+  demux->calculate_update_segment = FALSE;
+
+  demux->rate = 1.0;
+  gst_segment_init (&demux->segment, GST_FORMAT_UNDEFINED);
+  if (demux->segment_event) {
+    gst_event_unref (demux->segment_event);
+    demux->segment_event = NULL;
+  }
+
+  if (demux->update_segment) {
+    gst_event_unref (demux->update_segment);
+    demux->update_segment = NULL;
+  }
+
+  if (demux->global_tags) {
+    gst_tag_list_unref (demux->global_tags);
+    demux->global_tags = NULL;
+  }
+
+  demux->have_group_id = FALSE;
+  demux->group_id = G_MAXUINT;
+
+  demux->last_seek_offset = -1;
+}
+
+static void
+gst_wfd_ts_demux_init (GstWFDTSDemux * demux)
+{
+  WFDTSBase *base = (WFDTSBase *) demux;
+
+  base->stream_size = sizeof (WFDTSDemuxStream);
+  base->parse_private_sections = TRUE;
+  /* We are not interested in sections (all handled by mpegtsbase) */
+  base->push_section = FALSE;
+
+  demux->flowcombiner = gst_flow_combiner_new ();
+  demux->requested_program_number = -1;
+  demux->program_number = -1;
+  gst_wfd_ts_demux_reset (base);
+}
+
+
+static void
+gst_wfd_ts_demux_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX (object);
+
+  switch (prop_id) {
+    case PROP_PROGRAM_NUMBER:
+      /* FIXME: do something if program is switched as opposed to set at
+       * beginning */
+      demux->requested_program_number = g_value_get_int (value);
+      break;
+    case PROP_EMIT_STATS:
+      demux->emit_statistics = g_value_get_boolean (value);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+  }
+}
+
+static void
+gst_wfd_ts_demux_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX (object);
+
+  switch (prop_id) {
+    case PROP_PROGRAM_NUMBER:
+      g_value_set_int (value, demux->requested_program_number);
+      break;
+    case PROP_EMIT_STATS:
+      g_value_set_boolean (value, demux->emit_statistics);
+      break;
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+  }
+}
+
+static gboolean
+gst_wfd_ts_demux_srcpad_query (GstPad * pad, GstObject * parent, GstQuery * query)
+{
+  gboolean res = TRUE;
+  GstFormat format;
+  GstWFDTSDemux *demux;
+  WFDTSBase *base;
+
+  demux = GST_WFD_TS_DEMUX (parent);
+  base = GST_WFD_TS_BASE (demux);
+
+  switch (GST_QUERY_TYPE (query)) {
+    case GST_QUERY_DURATION:
+    {
+      GST_DEBUG ("query duration");
+      gst_query_parse_duration (query, &format, NULL);
+      if (format == GST_FORMAT_TIME) {
+        if (!gst_pad_peer_query (base->sinkpad, query)) {
+          gint64 val;
+
+          format = GST_FORMAT_BYTES;
+          if (!gst_pad_peer_query_duration (base->sinkpad, format, &val))
+            res = FALSE;
+          else {
+            GstClockTime dur =
+                wfd_ts_packetizer_offset_to_ts (base->packetizer, val,
+                demux->program->pcr_pid);
+            if (GST_CLOCK_TIME_IS_VALID (dur))
+              gst_query_set_duration (query, GST_FORMAT_TIME, dur);
+            else
+              res = FALSE;
+          }
+        }
+      } else {
+        GST_DEBUG_OBJECT (demux, "only query duration on TIME is supported");
+        res = FALSE;
+      }
+      break;
+    }
+    case GST_QUERY_LATENCY:
+    {
+      GST_DEBUG ("query latency");
+      res = gst_pad_peer_query (base->sinkpad, query);
+      if (res && base->upstream_live) {
+        GstClockTime min_lat, max_lat;
+        gboolean live;
+
+        /* According to H.222.0
+           Annex D.0.3 (System Time Clock recovery in the decoder)
+           and D.0.2 (Audio and video presentation synchronization)
+
+           We can end up with an interval of up to 700ms between valid
+           PTS/DTS. We therefore allow a latency of 700ms for that.
+         */
+        gst_query_parse_latency (query, &live, &min_lat, &max_lat);
+        if (min_lat != -1)
+          min_lat += 700 * GST_MSECOND;
+        if (max_lat != -1)
+          max_lat += 700 * GST_MSECOND;
+        gst_query_set_latency (query, live, min_lat, max_lat);
+      }
+      break;
+    }
+    case GST_QUERY_SEEKING:
+    {
+      GST_DEBUG ("query seeking");
+      gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
+      if (format == GST_FORMAT_TIME) {
+        gboolean seekable = FALSE;
+
+        if (gst_pad_peer_query (base->sinkpad, query))
+          gst_query_parse_seeking (query, NULL, &seekable, NULL, NULL);
+
+        /* If upstream is not seekable in TIME format we use
+         * our own values here */
+        if (!seekable)
+          gst_query_set_seeking (query, GST_FORMAT_TIME, TRUE, 0,
+              demux->segment.duration);
+      } else {
+        GST_DEBUG_OBJECT (demux, "only TIME is supported for query seeking");
+        res = FALSE;
+      }
+      break;
+    }
+    case GST_QUERY_SEGMENT:{
+      GstFormat format;
+      gint64 start, stop;
+
+      format = demux->segment.format;
+
+      start =
+          gst_segment_to_stream_time (&demux->segment, format,
+          demux->segment.start);
+      if ((stop = demux->segment.stop) == -1)
+        stop = demux->segment.duration;
+      else
+        stop = gst_segment_to_stream_time (&demux->segment, format, stop);
+
+      gst_query_set_segment (query, demux->segment.rate, format, start, stop);
+      res = TRUE;
+      break;
+    }
+    default:
+      res = gst_pad_query_default (pad, parent, query);
+  }
+
+  return res;
+
+}
+
+static void
+clear_simple_buffer (SimpleBuffer * sbuf)
+{
+  if (!sbuf->data)
+    return;
+
+  g_free (sbuf->data);
+  sbuf->size = 0;
+  sbuf->data = NULL;
+}
+
+static gboolean
+scan_keyframe_h264 (WFDTSDemuxStream * stream, const guint8 * data,
+    const gsize data_size, const gsize max_frame_offset)
+{
+  gint offset = 0;
+  GstWFDH264NalUnit unit, frame_unit = { 0, };
+  GstWFDH264ParserResult res = GST_H264_PARSER_OK;
+  WFDTSDemuxH264ParsingInfos *h264infos = &stream->h264infos;
+
+  GstWFDH264NalParser *parser = h264infos->parser;
+
+  if (G_UNLIKELY (parser == NULL)) {
+    parser = h264infos->parser = gst_wfd_h264_nal_parser_new ();
+    h264infos->sps = gst_byte_writer_new ();
+    h264infos->pps = gst_byte_writer_new ();
+    h264infos->sei = gst_byte_writer_new ();
+  }
+
+  while (res == GST_H264_PARSER_OK) {
+    res =
+        gst_wfd_h264_parser_identify_nalu (parser, data, offset, data_size, &unit);
+
+    if (res != GST_H264_PARSER_OK && res != GST_H264_PARSER_NO_NAL_END) {
+      GST_INFO_OBJECT (stream->pad, "Error identifying nalu: %i", res);
+      break;
+    }
+
+    res = gst_wfd_h264_parser_parse_nal (parser, &unit);
+    if (res != GST_H264_PARSER_OK) {
+      break;
+    }
+
+    switch (unit.type) {
+      case GST_H264_NAL_SEI:
+        if (frame_unit.size)
+          break;
+
+        if (gst_byte_writer_put_data (h264infos->sei,
+                unit.data + unit.sc_offset,
+                unit.size + unit.offset - unit.sc_offset)) {
+          GST_DEBUG ("adding SEI %u", unit.size + unit.offset - unit.sc_offset);
+        } else {
+          GST_WARNING ("Could not write SEI");
+        }
+        break;
+      case GST_H264_NAL_PPS:
+        if (frame_unit.size)
+          break;
+
+        if (gst_byte_writer_put_data (h264infos->pps,
+                unit.data + unit.sc_offset,
+                unit.size + unit.offset - unit.sc_offset)) {
+          GST_DEBUG ("adding PPS %u", unit.size + unit.offset - unit.sc_offset);
+        } else {
+          GST_WARNING ("Could not write PPS");
+        }
+        break;
+      case GST_H264_NAL_SPS:
+        if (frame_unit.size)
+          break;
+
+        if (gst_byte_writer_put_data (h264infos->sps,
+                unit.data + unit.sc_offset,
+                unit.size + unit.offset - unit.sc_offset)) {
+          GST_DEBUG ("adding SPS %u", unit.size + unit.offset - unit.sc_offset);
+        } else {
+          GST_WARNING ("Could not write SPS");
+        }
+        break;
+        /* these units are considered keyframes in h264parse */
+      case GST_H264_NAL_SLICE:
+      case GST_H264_NAL_SLICE_DPA:
+      case GST_H264_NAL_SLICE_DPB:
+      case GST_H264_NAL_SLICE_DPC:
+      case GST_H264_NAL_SLICE_IDR:
+      {
+        GstWFDH264SliceHdr slice;
+
+        if (h264infos->framedata.size)
+          break;
+
+        res = gst_wfd_h264_parser_parse_slice_hdr (parser, &unit, &slice,
+            FALSE, FALSE);
+
+        if (GST_H264_IS_I_SLICE (&slice) || GST_H264_IS_SI_SLICE (&slice)) {
+          if (*(unit.data + unit.offset + 1) & 0x80) {
+            /* means first_mb_in_slice == 0 */
+            /* real frame data */
+            GST_DEBUG_OBJECT (stream->pad, "Found keyframe at: %u",
+                unit.sc_offset);
+            frame_unit = unit;
+          }
+        }
+
+        break;
+      }
+      default:
+        break;
+    }
+
+    if (offset == unit.sc_offset + unit.size)
+      break;
+
+    offset = unit.sc_offset + unit.size;
+  }
+
+  /* We've got all the infos we need (SPS / PPS and a keyframe, plus
+   * and possibly SEI units. We can stop rewinding the stream
+   */
+  if (gst_byte_writer_get_size (h264infos->sps) &&
+      gst_byte_writer_get_size (h264infos->pps) &&
+      (h264infos->framedata.size || frame_unit.size)) {
+    guint8 *data = NULL;
+
+    gsize tmpsize = gst_byte_writer_get_size (h264infos->pps);
+
+    /*  We know that the SPS is first so just put all our data in there */
+    data = gst_byte_writer_reset_and_get_data (h264infos->pps);
+    gst_byte_writer_put_data (h264infos->sps, data, tmpsize);
+    g_free (data);
+
+    tmpsize = gst_byte_writer_get_size (h264infos->sei);
+    if (tmpsize) {
+      GST_DEBUG ("Adding SEI");
+      data = gst_byte_writer_reset_and_get_data (h264infos->sei);
+      gst_byte_writer_put_data (h264infos->sps, data, tmpsize);
+      g_free (data);
+    }
+
+    if (frame_unit.size) {      /*  We found the everything in one go! */
+      GST_DEBUG ("Adding Keyframe");
+      gst_byte_writer_put_data (h264infos->sps,
+          frame_unit.data + frame_unit.sc_offset,
+          stream->current_size - frame_unit.sc_offset);
+    } else {
+      GST_DEBUG ("Adding Keyframe");
+      gst_byte_writer_put_data (h264infos->sps,
+          h264infos->framedata.data, h264infos->framedata.size);
+      clear_simple_buffer (&h264infos->framedata);
+    }
+
+    g_free (stream->data);
+    stream->current_size = gst_byte_writer_get_size (h264infos->sps);
+    stream->data = gst_byte_writer_reset_and_get_data (h264infos->sps);
+    gst_byte_writer_init (h264infos->sps);
+    gst_byte_writer_init (h264infos->pps);
+    gst_byte_writer_init (h264infos->sei);
+
+    return TRUE;
+  }
+
+  if (frame_unit.size) {
+    GST_DEBUG_OBJECT (stream->pad, "Keep the keyframe as this is the one"
+        " we will push later");
+
+    h264infos->framedata.data =
+        g_memdup (frame_unit.data + frame_unit.sc_offset,
+        stream->current_size - frame_unit.sc_offset);
+    h264infos->framedata.size = stream->current_size - frame_unit.sc_offset;
+  }
+
+  return FALSE;
+}
+
+/* We merge data from TS packets so that the scanning methods get a continuous chunk,
+ however the scanning method will return keyframe offset which needs to be translated
+ back to actual offset in file */
+typedef struct
+{
+  gint64 real_offset;           /* offset of TS packet */
+  gint merged_offset;           /* offset of merged data in buffer */
+} OffsetInfo;
+
+static gboolean
+gst_wfd_ts_demux_adjust_seek_offset_for_keyframe (WFDTSDemuxStream * stream,
+    guint8 * data, guint64 size)
+{
+  int scan_pid = -1;
+
+  if (!stream->scan_function)
+    return TRUE;
+
+  scan_pid = ((WFDTSBaseStream *) stream)->pid;
+
+  if (scan_pid != -1) {
+    return stream->scan_function (stream, data, size, size);
+  }
+
+  return TRUE;
+}
+
+static GstFlowReturn
+gst_wfd_ts_demux_do_seek (WFDTSBase * base, GstEvent * event)
+{
+  GList *tmp;
+
+  GstWFDTSDemux *demux = (GstWFDTSDemux *) base;
+  GstFlowReturn res = GST_FLOW_ERROR;
+  gdouble rate;
+  GstFormat format;
+  GstSeekFlags flags;
+  GstSeekType start_type, stop_type;
+  gint64 start, stop;
+  guint64 start_offset;
+
+  gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
+      &stop_type, &stop);
+
+  GST_DEBUG ("seek event, rate: %f start: %" GST_TIME_FORMAT
+      " stop: %" GST_TIME_FORMAT, rate, GST_TIME_ARGS (start),
+      GST_TIME_ARGS (stop));
+
+  if (rate <= 0.0) {
+    GST_WARNING ("Negative rate not supported");
+    goto done;
+  }
+
+  if (flags & (GST_SEEK_FLAG_SEGMENT)) {
+    GST_WARNING ("seek flags 0x%x are not supported", (int) flags);
+    goto done;
+  }
+
+  /* configure the segment with the seek variables */
+  GST_DEBUG_OBJECT (demux, "configuring seek");
+
+  start_offset =
+      wfd_ts_packetizer_ts_to_offset (base->packetizer, MAX (0,
+          start - SEEK_TIMESTAMP_OFFSET), demux->program->pcr_pid);
+
+  if (G_UNLIKELY (start_offset == -1)) {
+    GST_WARNING ("Couldn't convert start position to an offset");
+    goto done;
+  }
+
+  /* record offset and rate */
+  base->seek_offset = start_offset;
+  demux->last_seek_offset = base->seek_offset;
+  demux->rate = rate;
+  res = GST_FLOW_OK;
+
+  if (flags & GST_SEEK_FLAG_ACCURATE) {
+    /* keep the seek infos for our segment */
+    gst_segment_do_seek (&demux->segment, rate, format, flags, start_type,
+        start, stop_type, stop, NULL);
+  } else {
+    /* Drop segment infos, it will be  recreated with actual seek infos */
+    gst_segment_init (&demux->segment, GST_FORMAT_UNDEFINED);
+  }
+  if (demux->segment_event) {
+    gst_event_unref (demux->segment_event);
+    demux->segment_event = NULL;
+  }
+
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *stream = tmp->data;
+
+
+    if (flags & GST_SEEK_FLAG_ACCURATE)
+      stream->needs_keyframe = TRUE;
+
+    stream->seeked_pts = GST_CLOCK_TIME_NONE;
+    stream->seeked_dts = GST_CLOCK_TIME_NONE;
+  }
+
+done:
+  return res;
+}
+
+static gboolean
+gst_wfd_ts_demux_srcpad_event (GstPad * pad, GstObject * parent, GstEvent * event)
+{
+  gboolean res = TRUE;
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX (parent);
+
+  GST_DEBUG_OBJECT (pad, "Got event %s",
+      gst_event_type_get_name (GST_EVENT_TYPE (event)));
+
+  switch (GST_EVENT_TYPE (event)) {
+    case GST_EVENT_SEEK:
+      res = wfd_ts_base_handle_seek_event ((WFDTSBase *) demux, pad, event);
+      if (!res)
+        GST_WARNING ("seeking failed");
+      gst_event_unref (event);
+      break;
+    default:
+      res = gst_pad_event_default (pad, parent, event);
+  }
+
+  return res;
+}
+
+static void
+clean_global_taglist (GstTagList * taglist)
+{
+  gst_tag_list_remove_tag (taglist, GST_TAG_CONTAINER_FORMAT);
+  gst_tag_list_remove_tag (taglist, GST_TAG_CODEC);
+}
+
+static gboolean
+push_event (WFDTSBase * base, GstEvent * event)
+{
+  GstWFDTSDemux *demux = (GstWFDTSDemux *) base;
+  GList *tmp;
+  gboolean early_ret = FALSE;
+
+  if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
+    GST_DEBUG_OBJECT (base, "Ignoring segment event (recreated later)");
+    gst_event_unref (event);
+    return TRUE;
+
+  } else if (GST_EVENT_TYPE (event) == GST_EVENT_TAG) {
+    /* In case we receive tags before data, store them to send later
+     * If we already have the program, send it right away */
+    GstTagList *taglist;
+
+    gst_event_parse_tag (event, &taglist);
+
+    if (demux->global_tags == NULL) {
+      demux->global_tags = gst_tag_list_copy (taglist);
+
+      /* Tags that are stream specific for the container should be considered
+       * global for the container streams */
+      if (gst_tag_list_get_scope (taglist) == GST_TAG_SCOPE_STREAM) {
+        gst_tag_list_set_scope (demux->global_tags, GST_TAG_SCOPE_GLOBAL);
+      }
+    } else {
+      demux->global_tags = gst_tag_list_make_writable (demux->global_tags);
+      gst_tag_list_insert (demux->global_tags, taglist, GST_TAG_MERGE_REPLACE);
+    }
+    clean_global_taglist (demux->global_tags);
+
+    /* tags are stored to be used after if there are no streams yet,
+     * so we should never reject */
+    early_ret = TRUE;
+  }
+
+  if (G_UNLIKELY (demux->program == NULL)) {
+    gst_event_unref (event);
+    return early_ret;
+  }
+
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *stream = (WFDTSDemuxStream *) tmp->data;
+    if (stream->pad) {
+      /* If we are pushing out EOS, flush out pending data first */
+      if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
+          gst_pad_is_active (stream->pad))
+        gst_wfd_ts_demux_push_pending_data (demux, stream);
+
+      gst_event_ref (event);
+      gst_pad_push_event (stream->pad, event);
+    }
+  }
+
+  gst_event_unref (event);
+
+  return TRUE;
+}
+
+static inline void
+add_iso639_language_to_tags (WFDTSDemuxStream * stream, gchar * lang_code)
+{
+  const gchar *lc;
+
+  GST_LOG ("Add language code for stream: '%s'", lang_code);
+
+  if (!stream->taglist)
+    stream->taglist = gst_tag_list_new_empty ();
+
+  /* descriptor contains ISO 639-2 code, we want the ISO 639-1 code */
+  lc = gst_tag_get_language_code (lang_code);
+
+  /* Only set tag if we have a valid one */
+  if (lc || (lang_code[0] && lang_code[1]))
+    gst_tag_list_add (stream->taglist, GST_TAG_MERGE_REPLACE,
+        GST_TAG_LANGUAGE_CODE, (lc) ? lc : lang_code, NULL);
+}
+
+static void
+gst_wfd_ts_demux_create_tags (WFDTSDemuxStream * stream)
+{
+  WFDTSBaseStream *bstream = (WFDTSBaseStream *) stream;
+  const GstWFDTSDescriptor *desc = NULL;
+  int i, nb;
+
+  desc =
+      wfd_ts_get_descriptor_from_stream (bstream,
+      GST_MTS_DESC_ISO_639_LANGUAGE);
+  if (desc) {
+    gchar *lang_code;
+
+    nb = gst_wfd_ts_descriptor_parse_iso_639_language_nb (desc);
+
+    GST_DEBUG ("Found ISO 639 descriptor (%d entries)", nb);
+
+    for (i = 0; i < nb; i++)
+      if (gst_wfd_ts_descriptor_parse_iso_639_language_idx (desc, i, &lang_code,
+              NULL)) {
+        add_iso639_language_to_tags (stream, lang_code);
+        g_free (lang_code);
+      }
+
+    return;
+  }
+
+#ifdef ENABLE_ALL
+  desc =
+      wfd_ts_get_descriptor_from_stream (bstream, GST_MTS_DESC_DVB_SUBTITLING);
+
+  if (desc) {
+    gchar *lang_code;
+
+    nb = gst_wfd_ts_descriptor_parse_dvb_subtitling_nb (desc);
+
+    GST_DEBUG ("Found SUBTITLING descriptor (%d entries)", nb);
+
+    for (i = 0; i < nb; i++)
+      if (gst_wfd_ts_descriptor_parse_dvb_subtitling_idx (desc, i, &lang_code,
+              NULL, NULL, NULL)) {
+        add_iso639_language_to_tags (stream, lang_code);
+        g_free (lang_code);
+      }
+  }
+#endif
+}
+
+static GstPad *
+create_pad_for_stream (WFDTSBase * base, WFDTSBaseStream * bstream,
+    WFDTSBaseProgram * program)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX (base);
+  WFDTSDemuxStream *stream = (WFDTSDemuxStream *) bstream;
+  gchar *name = NULL;
+  GstCaps *caps = NULL;
+  GstPadTemplate *template = NULL;
+  //const GstWFDTSDescriptor *desc = NULL;
+  GstPad *pad = NULL;
+
+  gst_wfd_ts_demux_create_tags (stream);
+
+  GST_LOG ("Attempting to create pad for stream 0x%04x with stream_type %d",
+      bstream->pid, bstream->stream_type);
+
+  /* First handle BluRay-specific stream types since there is some overlap
+   * between BluRay and non-BluRay streay type identifiers */
+  if (program->registration_id == DRF_ID_HDMV) {
+    switch (bstream->stream_type) {
+      case ST_BD_AUDIO_AC3:
+      {
+        const GstWFDTSDescriptor *ac3_desc;
+
+        /* ATSC ac3 audio descriptor */
+        ac3_desc =
+            wfd_ts_get_descriptor_from_stream (bstream,
+            GST_MTS_DESC_AC3_AUDIO_STREAM);
+        if (ac3_desc && DESC_AC_AUDIO_STREAM_bsid (ac3_desc->data) != 16) {
+          GST_LOG ("ac3 audio");
+          template = gst_static_pad_template_get (&audio_template);
+          name = g_strdup_printf ("audio_%04x", bstream->pid);
+          caps = gst_caps_new_empty_simple ("audio/x-ac3");
+        } else {
+          template = gst_static_pad_template_get (&audio_template);
+          name = g_strdup_printf ("audio_%04x", bstream->pid);
+          caps = gst_caps_new_empty_simple ("audio/x-eac3");
+        }
+        break;
+      }
+      case ST_BD_AUDIO_EAC3:
+      case ST_BD_AUDIO_AC3_PLUS:
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-eac3");
+        break;
+      case ST_BD_AUDIO_AC3_TRUE_HD:
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-true-hd");
+        stream->target_pes_substream = 0x72;
+        break;
+      case ST_BD_AUDIO_LPCM:
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-private-ts-lpcm");
+        break;
+      case ST_BD_AUDIO_DTS_HD:
+      case ST_BD_AUDIO_DTS_HD_MASTER_AUDIO:
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-dts");
+        stream->target_pes_substream = 0x71;
+        break;
+    }
+  }
+  if (template && name && caps)
+    goto done;
+
+  /* Handle non-BluRay stream types */
+  switch (bstream->stream_type) {
+    case GST_WFD_TS_STREAM_TYPE_AUDIO_MPEG1:
+    case GST_WFD_TS_STREAM_TYPE_AUDIO_MPEG2:
+      GST_LOG ("mpeg audio");
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps =
+          gst_caps_new_simple ("audio/mpeg", "mpegversion", G_TYPE_INT, 1,
+          NULL);
+      /* HDV is always mpeg 1 audio layer 2 */
+      if (program->registration_id == DRF_ID_TSHV)
+        gst_caps_set_simple (caps, "layer", G_TYPE_INT, 2, NULL);
+      break;
+    case GST_WFD_TS_STREAM_TYPE_PRIVATE_PES_PACKETS:
+      GST_LOG ("private data");
+#ifdef ENABLE_ALL
+      /* FIXME: Move all of this into a common method (there might be other
+       * types also, depending on registratino descriptors also
+       */
+      desc = wfd_ts_get_descriptor_from_stream (bstream, GST_MTS_DESC_DVB_AC3);
+      if (desc) {
+        GST_LOG ("ac3 audio");
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-ac3");
+        break;
+      }
+
+      desc =
+          wfd_ts_get_descriptor_from_stream (bstream,
+          GST_MTS_DESC_DVB_ENHANCED_AC3);
+      if (desc) {
+        GST_LOG ("ac3 audio");
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-eac3");
+        break;
+      }
+      desc =
+          wfd_ts_get_descriptor_from_stream (bstream,
+          GST_MTS_DESC_DVB_TELETEXT);
+      if (desc) {
+        GST_LOG ("teletext");
+        template = gst_static_pad_template_get (&private_template);
+        name = g_strdup_printf ("private_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("application/x-teletext");
+        break;
+      }
+      desc =
+          wfd_ts_get_descriptor_from_stream (bstream,
+          GST_MTS_DESC_DVB_SUBTITLING);
+      if (desc) {
+        GST_LOG ("subtitling");
+        template = gst_static_pad_template_get (&private_template);
+        name = g_strdup_printf ("private_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("subpicture/x-dvb");
+        break;
+      }
+#endif
+      switch (bstream->registration_id) {
+        case DRF_ID_DTS1:
+        case DRF_ID_DTS2:
+        case DRF_ID_DTS3:
+          /* SMPTE registered DTS */
+          template = gst_static_pad_template_get (&private_template);
+          name = g_strdup_printf ("private_%04x", bstream->pid);
+          caps = gst_caps_new_empty_simple ("audio/x-dts");
+          break;
+        case DRF_ID_S302M:
+          template = gst_static_pad_template_get (&audio_template);
+          name = g_strdup_printf ("audio_%04x", bstream->pid);
+          caps = gst_caps_new_empty_simple ("audio/x-smpte-302m");
+          break;
+        case DRF_ID_HEVC:
+          template = gst_static_pad_template_get (&video_template);
+          name = g_strdup_printf ("video_%04x", bstream->pid);
+          caps = gst_caps_new_simple ("video/x-h265",
+              "stream-format", G_TYPE_STRING, "byte-stream",
+              "alignment", G_TYPE_STRING, "nal", NULL);
+          break;
+      }
+      if (template)
+        break;
+
+      /* hack for itv hd (sid 10510, video pid 3401 */
+      if (program->program_number == 10510 && bstream->pid == 3401) {
+        template = gst_static_pad_template_get (&video_template);
+        name = g_strdup_printf ("video_%04x", bstream->pid);
+        caps = gst_caps_new_simple ("video/x-h264",
+            "stream-format", G_TYPE_STRING, "byte-stream",
+            "alignment", G_TYPE_STRING, "nal", NULL);
+      }
+      break;
+    case ST_HDV_AUX_V:
+      /* FIXME : Should only be used with specific PMT registration_descriptor */
+      /* We don't expose those streams since they're only helper streams */
+      /* template = gst_static_pad_template_get (&private_template); */
+      /* name = g_strdup_printf ("private_%04x", bstream->pid); */
+      /* caps = gst_caps_new_simple ("hdv/aux-v", NULL); */
+      break;
+    case ST_HDV_AUX_A:
+      /* FIXME : Should only be used with specific PMT registration_descriptor */
+      /* We don't expose those streams since they're only helper streams */
+      /* template = gst_static_pad_template_get (&private_template); */
+      /* name = g_strdup_printf ("private_%04x", bstream->pid); */
+      /* caps = gst_caps_new_simple ("hdv/aux-a", NULL); */
+      break;
+    case GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_ADTS:
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps = gst_caps_new_simple ("audio/mpeg",
+          "mpegversion", G_TYPE_INT, 2,
+          "stream-format", G_TYPE_STRING, "adts", NULL);
+      break;
+    case GST_WFD_TS_STREAM_TYPE_AUDIO_AAC_LATM:
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps = gst_caps_new_simple ("audio/mpeg",
+          "mpegversion", G_TYPE_INT, 4,
+          "stream-format", G_TYPE_STRING, "loas", NULL);
+      break;
+    case GST_WFD_TS_STREAM_TYPE_VIDEO_H264:
+      template = gst_static_pad_template_get (&video_template);
+      name = g_strdup_printf ("video_%04x", bstream->pid);
+      caps = gst_caps_new_simple ("video/x-h264",
+          "stream-format", G_TYPE_STRING, "byte-stream",
+          "alignment", G_TYPE_STRING, "nal", NULL);
+      break;
+    case GST_WFD_TS_STREAM_TYPE_VIDEO_HEVC:
+      template = gst_static_pad_template_get (&video_template);
+      name = g_strdup_printf ("video_%04x", bstream->pid);
+      caps = gst_caps_new_simple ("video/x-h265",
+          "stream-format", G_TYPE_STRING, "byte-stream",
+          "alignment", G_TYPE_STRING, "nal", NULL);
+      break;
+    case ST_PS_AUDIO_AC3:
+      /* DVB_ENHANCED_AC3 */
+#ifdef ENABLE_ALL
+      desc =
+          wfd_ts_get_descriptor_from_stream (bstream,
+          GST_MTS_DESC_DVB_ENHANCED_AC3);
+      if (desc) {
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-eac3");
+        break;
+      }
+
+      /* If stream has ac3 descriptor
+       * OR program is ATSC (GA94)
+       * OR stream registration is AC-3
+       * then it's regular AC3 */
+      if (bstream->registration_id == DRF_ID_AC3 ||
+          program->registration_id == DRF_ID_GA94 ||
+          wfd_ts_get_descriptor_from_stream (bstream, GST_MTS_DESC_DVB_AC3)) {
+        template = gst_static_pad_template_get (&audio_template);
+        name = g_strdup_printf ("audio_%04x", bstream->pid);
+        caps = gst_caps_new_empty_simple ("audio/x-ac3");
+        break;
+      }
+#endif
+      GST_WARNING ("AC3 stream type found but no guaranteed "
+          "way found to differentiate between AC3 and EAC3. "
+          "Assuming plain AC3.");
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps = gst_caps_new_empty_simple ("audio/x-ac3");
+      break;
+    case ST_PS_AUDIO_DTS:
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps = gst_caps_new_empty_simple ("audio/x-dts");
+      break;
+#ifdef WFD_SPEC
+    case ST_PS_WFD_AUDIO_LPCM:
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps = gst_caps_new_simple ("audio/x-raw",
+      "format", G_TYPE_STRING, "S16BE",
+      "rate", G_TYPE_INT, 48000,
+      "channels", G_TYPE_INT, 2,
+      "layout", G_TYPE_STRING, "interleaved", NULL);
+      break;
+#endif
+    case ST_PS_AUDIO_LPCM:
+      template = gst_static_pad_template_get (&audio_template);
+      name = g_strdup_printf ("audio_%04x", bstream->pid);
+      caps = gst_caps_new_empty_simple ("audio/x-lpcm");
+      break;
+    default:
+      GST_WARNING ("Non-media stream (stream_type:0x%x). Not creating pad",
+          bstream->stream_type);
+      break;
+  }
+
+done:
+  if (template && name && caps) {
+    GstEvent *event;
+    gchar *stream_id;
+
+    GST_LOG ("stream:%p creating pad with name %s and caps %" GST_PTR_FORMAT,
+        stream, name, caps);
+    pad = gst_pad_new_from_template (template, name);
+    gst_pad_set_active (pad, TRUE);
+    gst_pad_use_fixed_caps (pad);
+    stream_id =
+        gst_pad_create_stream_id_printf (pad, GST_ELEMENT_CAST (base), "%08x",
+        bstream->pid);
+
+    event = gst_pad_get_sticky_event (base->sinkpad, GST_EVENT_STREAM_START, 0);
+    if (event) {
+      if (gst_event_parse_group_id (event, &demux->group_id))
+        demux->have_group_id = TRUE;
+      else
+        demux->have_group_id = FALSE;
+      gst_event_unref (event);
+    } else if (!demux->have_group_id) {
+      demux->have_group_id = TRUE;
+      demux->group_id = gst_util_group_id_next ();
+    }
+    event = gst_event_new_stream_start (stream_id);
+    if (demux->have_group_id)
+      gst_event_set_group_id (event, demux->group_id);
+
+    gst_pad_push_event (pad, event);
+    g_free (stream_id);
+    gst_pad_set_caps (pad, caps);
+    if (!stream->taglist)
+      stream->taglist = gst_tag_list_new_empty ();
+    gst_pb_utils_add_codec_description_to_tag_list (stream->taglist, NULL,
+        caps);
+    gst_pad_set_query_function (pad, gst_wfd_ts_demux_srcpad_query);
+    gst_pad_set_event_function (pad, gst_wfd_ts_demux_srcpad_event);
+  }
+
+  if (name)
+    g_free (name);
+  if (template)
+    gst_object_unref (template);
+  if (caps)
+    gst_caps_unref (caps);
+
+  return pad;
+}
+
+static void
+gst_wfd_ts_demux_stream_added (WFDTSBase * base, WFDTSBaseStream * bstream,
+    WFDTSBaseProgram * program)
+{
+  GstWFDTSDemux *demux = (GstWFDTSDemux *) base;
+  WFDTSDemuxStream *stream = (WFDTSDemuxStream *) bstream;
+
+  if (!stream->pad) {
+    /* Create the pad */
+    if (bstream->stream_type != 0xff) {
+      stream->pad = create_pad_for_stream (base, bstream, program);
+      if (stream->pad)
+        gst_flow_combiner_add_pad (demux->flowcombiner, stream->pad);
+    }
+
+    if (base->mode != BASE_MODE_PUSHING
+        && bstream->stream_type == GST_WFD_TS_STREAM_TYPE_VIDEO_H264) {
+      stream->scan_function =
+          (GstWFDTsDemuxKeyFrameScanFunction) scan_keyframe_h264;
+    } else {
+      stream->scan_function = NULL;
+    }
+
+    stream->active = FALSE;
+
+    stream->need_newsegment = TRUE;
+    stream->needs_keyframe = FALSE;
+    stream->discont = TRUE;
+    stream->pts = GST_CLOCK_TIME_NONE;
+    stream->dts = GST_CLOCK_TIME_NONE;
+    stream->raw_pts = -1;
+    stream->raw_dts = -1;
+    stream->pending_ts = TRUE;
+    stream->first_dts = GST_CLOCK_TIME_NONE;
+    stream->continuity_counter = CONTINUITY_UNSET;
+  }
+}
+
+static void
+tsdemux_h264_parsing_info_clear (WFDTSDemuxH264ParsingInfos * h264infos)
+{
+  clear_simple_buffer (&h264infos->framedata);
+
+  if (h264infos->parser) {
+    gst_wfd_h264_nal_parser_free (h264infos->parser);
+    gst_byte_writer_free (h264infos->sps);
+    gst_byte_writer_free (h264infos->pps);
+    gst_byte_writer_free (h264infos->sei);
+  }
+}
+
+static void
+gst_wfd_ts_demux_stream_removed (WFDTSBase * base, WFDTSBaseStream * bstream)
+{
+  WFDTSDemuxStream *stream = (WFDTSDemuxStream *) bstream;
+
+  if (stream->pad) {
+    gst_flow_combiner_remove_pad (GST_WFD_TS_DEMUX_CAST (base)->flowcombiner,
+        stream->pad);
+    if (stream->active) {
+
+      if (gst_pad_is_active (stream->pad)) {
+        /* Flush out all data */
+        GST_DEBUG_OBJECT (stream->pad, "Flushing out pending data");
+        gst_wfd_ts_demux_push_pending_data ((GstWFDTSDemux *) base, stream);
+
+        GST_DEBUG_OBJECT (stream->pad, "Pushing out EOS");
+        gst_pad_push_event (stream->pad, gst_event_new_eos ());
+        gst_pad_set_active (stream->pad, FALSE);
+      }
+
+      GST_DEBUG_OBJECT (stream->pad, "Removing pad");
+      gst_element_remove_pad (GST_ELEMENT_CAST (base), stream->pad);
+      stream->active = FALSE;
+    }
+    stream->pad = NULL;
+  }
+
+  gst_wfd_ts_demux_stream_flush (stream, GST_WFD_TS_DEMUX_CAST (base));
+
+  tsdemux_h264_parsing_info_clear (&stream->h264infos);
+}
+
+static void
+activate_pad_for_stream (GstWFDTSDemux * tsdemux, WFDTSDemuxStream * stream)
+{
+  GList *tmp;
+  gboolean alldone = TRUE;
+
+  if (stream->pad) {
+    GST_DEBUG_OBJECT (tsdemux, "Activating pad %s:%s for stream %p",
+        GST_DEBUG_PAD_NAME (stream->pad), stream);
+#ifdef WFD_SPEC
+  GST_WARNING ("This is LPCM PAD");
+  if (((WFDTSBaseStream *) stream)->stream_type == ST_PS_WFD_AUDIO_LPCM) {
+    GstCaps *caps = NULL;
+    gchar *format = g_strdup_printf ("S%dBE", stream->lpcm_data.width);
+
+    caps = gst_caps_new_simple ("audio/x-raw",
+      "format", G_TYPE_STRING, format,
+      "rate", G_TYPE_INT, stream->lpcm_data.rate,
+      "channels", G_TYPE_INT, stream->lpcm_data.channels,
+      "layout", G_TYPE_STRING, "interleaved", NULL);
+      gst_pad_set_caps (stream->pad, caps);
+
+    if (caps)
+      gst_caps_unref (caps);
+  }
+#endif
+
+    gst_element_add_pad ((GstElement *) tsdemux, stream->pad);
+    stream->active = TRUE;
+    GST_DEBUG_OBJECT (stream->pad, "done adding pad");
+
+    /* Check if all pads were activated, and if so emit no-more-pads */
+    for (tmp = tsdemux->program->stream_list; tmp; tmp = tmp->next) {
+      stream = (WFDTSDemuxStream *) tmp->data;
+      if (stream->pad && !stream->active)
+        alldone = FALSE;
+    }
+    if (alldone) {
+      GST_DEBUG_OBJECT (tsdemux, "All pads were activated, emit no-more-pads");
+      gst_element_no_more_pads ((GstElement *) tsdemux);
+    }
+  } else
+    GST_WARNING_OBJECT (tsdemux,
+        "stream %p (pid 0x%04x, type:0x%03x) has no pad", stream,
+        ((WFDTSBaseStream *) stream)->pid,
+        ((WFDTSBaseStream *) stream)->stream_type);
+}
+
+static void
+gst_wfd_ts_demux_stream_flush (WFDTSDemuxStream * stream, GstWFDTSDemux * tsdemux)
+{
+  GST_DEBUG ("flushing stream %p", stream);
+
+  if (stream->data)
+    g_free (stream->data);
+  stream->data = NULL;
+  stream->state = PENDING_PACKET_EMPTY;
+  stream->expected_size = 0;
+  stream->allocated_size = 0;
+  stream->current_size = 0;
+  stream->need_newsegment = TRUE;
+  stream->discont = TRUE;
+  stream->pts = GST_CLOCK_TIME_NONE;
+  stream->dts = GST_CLOCK_TIME_NONE;
+  stream->first_dts = GST_CLOCK_TIME_NONE;
+  stream->raw_pts = -1;
+  stream->raw_dts = -1;
+  stream->pending_ts = TRUE;
+  stream->continuity_counter = CONTINUITY_UNSET;
+}
+
+static void
+gst_wfd_ts_demux_flush_streams (GstWFDTSDemux * demux)
+{
+  if (!demux->program)
+    return;
+
+  g_list_foreach (demux->program->stream_list,
+      (GFunc) gst_wfd_ts_demux_stream_flush, demux);
+}
+
+static void
+gst_wfd_ts_demux_program_started (WFDTSBase * base, WFDTSBaseProgram * program)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX (base);
+
+  GST_DEBUG ("Current program %d, new program %d requested program %d",
+      (gint) demux->program_number, program->program_number,
+      demux->requested_program_number);
+
+  if (demux->requested_program_number == program->program_number ||
+      (demux->requested_program_number == -1 && demux->program_number == -1)) {
+
+    GST_LOG ("program %d started", program->program_number);
+    demux->program_number = program->program_number;
+    demux->program = program;
+
+    /* If this is not the initial program, we need to calculate
+     * an update newsegment */
+    demux->calculate_update_segment = !program->initial_program;
+
+    /* FIXME : When do we emit no_more_pads ? */
+  }
+}
+
+static void
+gst_wfd_ts_demux_program_stopped (WFDTSBase * base, WFDTSBaseProgram * program)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX (base);
+
+  if (demux->program == program) {
+    demux->program = NULL;
+    demux->program_number = -1;
+  }
+}
+
+
+static inline void
+gst_wfd_ts_demux_record_pts (GstWFDTSDemux * demux, WFDTSDemuxStream * stream,
+    guint64 pts, guint64 offset)
+{
+  WFDTSBaseStream *bs = (WFDTSBaseStream *) stream;
+
+  stream->raw_pts = pts;
+  if (pts == -1) {
+    stream->pts = GST_CLOCK_TIME_NONE;
+    return;
+  }
+
+  GST_LOG ("pid 0x%04x raw pts:%" G_GUINT64_FORMAT " at offset %"
+      G_GUINT64_FORMAT, bs->pid, pts, offset);
+
+  /* Compute PTS in GstClockTime */
+  stream->pts =
+      wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+      MPEGTIME_TO_GSTTIME (pts), demux->program->pcr_pid);
+
+  GST_LOG ("pid 0x%04x Stored PTS %" G_GUINT64_FORMAT, bs->pid, stream->pts);
+
+  if (G_UNLIKELY (demux->emit_statistics)) {
+    GstStructure *st;
+    st = gst_structure_new_id_empty (QUARK_TSDEMUX);
+    gst_structure_id_set (st,
+        QUARK_PID, G_TYPE_UINT, bs->pid,
+        QUARK_OFFSET, G_TYPE_UINT64, offset, QUARK_PTS, G_TYPE_UINT64, pts,
+        NULL);
+    gst_element_post_message (GST_ELEMENT_CAST (demux),
+        gst_message_new_element (GST_OBJECT (demux), st));
+  }
+}
+
+static inline void
+gst_wfd_ts_demux_record_dts (GstWFDTSDemux * demux, WFDTSDemuxStream * stream,
+    guint64 dts, guint64 offset)
+{
+  WFDTSBaseStream *bs = (WFDTSBaseStream *) stream;
+
+  stream->raw_dts = dts;
+  if (dts == -1) {
+    stream->dts = GST_CLOCK_TIME_NONE;
+    return;
+  }
+
+  GST_LOG ("pid 0x%04x raw dts:%" G_GUINT64_FORMAT " at offset %"
+      G_GUINT64_FORMAT, bs->pid, dts, offset);
+
+  /* Compute DTS in GstClockTime */
+  stream->dts =
+      wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+      MPEGTIME_TO_GSTTIME (dts), demux->program->pcr_pid);
+
+  GST_LOG ("pid 0x%04x Stored DTS %" G_GUINT64_FORMAT, bs->pid, stream->dts);
+
+  if (G_UNLIKELY (demux->emit_statistics)) {
+    GstStructure *st;
+    st = gst_structure_new_id_empty (QUARK_TSDEMUX);
+    gst_structure_id_set (st,
+        QUARK_PID, G_TYPE_UINT, bs->pid,
+        QUARK_OFFSET, G_TYPE_UINT64, offset, QUARK_DTS, G_TYPE_UINT64, dts,
+        NULL);
+    gst_element_post_message (GST_ELEMENT_CAST (demux),
+        gst_message_new_element (GST_OBJECT (demux), st));
+  }
+}
+
+/* This is called when we haven't got a valid initial PTS/DTS on all streams */
+static gboolean
+check_pending_buffers (GstWFDTSDemux * demux)
+{
+  gboolean have_observation = FALSE;
+  /* The biggest offset */
+  guint64 offset = 0;
+  GList *tmp;
+
+  /* 1. Go over all streams */
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *tmpstream = (WFDTSDemuxStream *) tmp->data;
+    /* 1.1 check if at least one stream got a valid DTS */
+    if ((tmpstream->raw_dts != -1 && tmpstream->dts != GST_CLOCK_TIME_NONE) ||
+        (tmpstream->raw_pts != -1 && tmpstream->pts != GST_CLOCK_TIME_NONE)) {
+      have_observation = TRUE;
+      break;
+    }
+  }
+
+  /* 2. If we don't have a valid value yet, break out */
+  if (have_observation == FALSE)
+    return FALSE;
+
+  /* 3. Go over all streams that have current/pending data */
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *tmpstream = (WFDTSDemuxStream *) tmp->data;
+    PendingBuffer *pend;
+    guint64 firstval, lastval, ts;
+
+    /* 3.1 Calculate the offset between current DTS and first DTS */
+    if (tmpstream->pending == NULL || tmpstream->state == PENDING_PACKET_EMPTY)
+      continue;
+    /* If we don't have any pending data, the offset is 0 for this stream */
+    if (tmpstream->pending == NULL)
+      break;
+    if (tmpstream->raw_dts != -1)
+      lastval = tmpstream->raw_dts;
+    else if (tmpstream->raw_pts != -1)
+      lastval = tmpstream->raw_pts;
+    else {
+      GST_WARNING ("Don't have a last DTS/PTS to use for offset recalculation");
+      continue;
+    }
+    pend = tmpstream->pending->data;
+    if (pend->dts != -1)
+      firstval = pend->dts;
+    else if (pend->pts != -1)
+      firstval = pend->pts;
+    else {
+      GST_WARNING
+          ("Don't have a first DTS/PTS to use for offset recalculation");
+      continue;
+    }
+    /* 3.2 Add to the offset the report TS for the current DTS */
+    ts = wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+        MPEGTIME_TO_GSTTIME (lastval), demux->program->pcr_pid);
+    if (ts == GST_CLOCK_TIME_NONE) {
+      GST_WARNING ("THIS SHOULD NOT HAPPEN !");
+      continue;
+    }
+    ts += MPEGTIME_TO_GSTTIME (lastval - firstval);
+    /* 3.3 If that offset is bigger than the current offset, store it */
+    if (ts > offset)
+      offset = ts;
+  }
+
+  GST_DEBUG ("New initial pcr_offset %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (offset));
+
+  /* 4. Set the offset on the packetizer */
+  wfd_ts_packetizer_set_current_pcr_offset (MPEG_TS_BASE_PACKETIZER (demux),
+      offset, demux->program->pcr_pid);
+
+  /* 4. Go over all streams */
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *stream = (WFDTSDemuxStream *) tmp->data;
+
+    stream->pending_ts = FALSE;
+    /* 4.1 Set pending_ts for FALSE */
+
+    /* 4.2 Recalculate PTS/DTS (in running time) for pending data */
+    if (stream->pending) {
+      GList *tmp2;
+      for (tmp2 = stream->pending; tmp2; tmp2 = tmp2->next) {
+        PendingBuffer *pend = (PendingBuffer *) tmp2->data;
+        if (pend->pts != -1)
+          GST_BUFFER_PTS (pend->buffer) =
+              wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+              MPEGTIME_TO_GSTTIME (pend->pts), demux->program->pcr_pid);
+        if (pend->dts != -1)
+          GST_BUFFER_DTS (pend->buffer) =
+              wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+              MPEGTIME_TO_GSTTIME (pend->dts), demux->program->pcr_pid);
+        /* 4.2.2 Set first_dts to TS of lowest DTS (for segment) */
+        if (stream->first_dts == GST_CLOCK_TIME_NONE) {
+          if (GST_BUFFER_DTS (pend->buffer) != GST_CLOCK_TIME_NONE)
+            stream->first_dts = GST_BUFFER_DTS (pend->buffer);
+          else if (GST_BUFFER_PTS (pend->buffer) != GST_CLOCK_TIME_NONE)
+            stream->first_dts = GST_BUFFER_PTS (pend->buffer);
+        }
+      }
+    }
+    /* Recalculate PTS/DTS (in running time) for current data */
+    if (stream->state != PENDING_PACKET_EMPTY) {
+      if (stream->raw_dts != -1) {
+        stream->dts =
+            wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+            MPEGTIME_TO_GSTTIME (stream->raw_dts), demux->program->pcr_pid);
+        if (stream->first_dts == GST_CLOCK_TIME_NONE)
+          stream->first_dts = stream->dts;
+      }
+      if (stream->raw_pts != -1) {
+        stream->pts =
+            wfd_ts_packetizer_pts_to_ts (MPEG_TS_BASE_PACKETIZER (demux),
+            MPEGTIME_TO_GSTTIME (stream->raw_pts), demux->program->pcr_pid);
+        if (stream->first_dts == GST_CLOCK_TIME_NONE)
+          stream->first_dts = stream->pts;
+      }
+    }
+  }
+
+  return TRUE;
+}
+
+static void
+gst_wfd_ts_demux_parse_pes_header (GstWFDTSDemux * demux, WFDTSDemuxStream * stream,
+    guint8 * data, guint32 length, guint64 bufferoffset)
+{
+  WFDPESHeader header;
+  WFDPESParsingResult parseres;
+
+  GST_MEMDUMP ("Header buffer", data, MIN (length, 32));
+
+  parseres = wfd_ts_parse_pes_header (data, length, &header);
+  if (G_UNLIKELY (parseres == PES_PARSING_NEED_MORE))
+    goto discont;
+  if (G_UNLIKELY (parseres == PES_PARSING_BAD)) {
+    GST_WARNING ("Error parsing PES header. pid: 0x%x stream_type: 0x%x",
+        stream->stream.pid, stream->stream.stream_type);
+    goto discont;
+  }
+
+#ifdef WFD_SPEC
+  if (header.is_lpcm) {
+    GST_WARNING ("This is LPCM header");
+    stream->lpcm_data.width = header.lpcm_data.width;
+    stream->lpcm_data.channels = header.lpcm_data.channels;
+    stream->lpcm_data.rate = header.lpcm_data.rate;
+  }
+#endif
+
+  if (stream->target_pes_substream != 0
+      && header.stream_id_extension != stream->target_pes_substream) {
+    GST_DEBUG ("Skipping unwanted substream");
+    goto discont;
+  }
+
+  gst_wfd_ts_demux_record_dts (demux, stream, header.DTS, bufferoffset);
+  gst_wfd_ts_demux_record_pts (demux, stream, header.PTS, bufferoffset);
+  if (G_UNLIKELY (stream->pending_ts &&
+          (stream->pts != GST_CLOCK_TIME_NONE
+              || stream->dts != GST_CLOCK_TIME_NONE))) {
+    GST_DEBUG ("Got pts/dts update, rechecking all streams");
+    check_pending_buffers (demux);
+  } else if (stream->first_dts == GST_CLOCK_TIME_NONE) {
+    if (GST_CLOCK_TIME_IS_VALID (stream->dts))
+      stream->first_dts = stream->dts;
+    else if (GST_CLOCK_TIME_IS_VALID (stream->pts))
+      stream->first_dts = stream->pts;
+  }
+
+  GST_DEBUG_OBJECT (demux,
+      "stream PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (stream->pts), GST_TIME_ARGS (stream->dts));
+
+  /* Remove PES headers */
+  GST_DEBUG ("Moving data forward by %d bytes (packet_size:%d, have:%d)",
+      header.header_size, header.packet_length, length);
+  stream->expected_size = header.packet_length;
+  if (stream->expected_size) {
+    if (G_LIKELY (stream->expected_size > header.header_size)) {
+      stream->expected_size -= header.header_size;
+    } else {
+      /* next packet will have to complete this one */
+      GST_ERROR ("invalid header and packet size combination");
+      stream->expected_size = 0;
+    }
+  }
+  data += header.header_size;
+  length -= header.header_size;
+
+  /* Create the output buffer */
+  if (stream->expected_size)
+    stream->allocated_size = MAX (stream->expected_size, length);
+  else
+    stream->allocated_size = MAX (8192, length);
+
+  g_assert (stream->data == NULL);
+  stream->data = g_malloc (stream->allocated_size);
+  memcpy (stream->data, data, length);
+  stream->current_size = length;
+
+  stream->state = PENDING_PACKET_BUFFER;
+
+  return;
+
+discont:
+  stream->state = PENDING_PACKET_DISCONT;
+  return;
+}
+
+ /* ONLY CALL THIS:
+  * * WITH packet->payload != NULL
+  * * WITH pending/current flushed out if beginning of new PES packet
+  */
+static inline void
+gst_wfd_ts_demux_queue_data (GstWFDTSDemux * demux, WFDTSDemuxStream * stream,
+    WFDTSPacketizerPacket * packet)
+{
+  guint8 *data;
+  guint size;
+  guint8 cc = FLAGS_CONTINUITY_COUNTER (packet->scram_afc_cc);
+
+  GST_LOG ("pid: 0x%04x state:%d", stream->stream.pid, stream->state);
+
+  size = packet->data_end - packet->payload;
+  data = packet->payload;
+
+  if (stream->continuity_counter == CONTINUITY_UNSET) {
+    GST_DEBUG ("CONTINUITY: Initialize to %d", cc);
+  } else if ((cc == stream->continuity_counter + 1 ||
+          (stream->continuity_counter == MAX_CONTINUITY && cc == 0))) {
+    GST_LOG ("CONTINUITY: Got expected %d", cc);
+  } else {
+    GST_WARNING ("CONTINUITY: Mismatch packet %d, stream %d",
+        cc, stream->continuity_counter);
+    if (stream->state != PENDING_PACKET_EMPTY)
+      stream->state = PENDING_PACKET_DISCONT;
+  }
+  stream->continuity_counter = cc;
+
+  if (stream->state == PENDING_PACKET_EMPTY) {
+    if (G_UNLIKELY (!packet->payload_unit_start_indicator)) {
+      stream->state = PENDING_PACKET_DISCONT;
+      GST_DEBUG ("Didn't get the first packet of this PES");
+    } else {
+      GST_LOG ("EMPTY=>HEADER");
+      stream->state = PENDING_PACKET_HEADER;
+    }
+  }
+
+  switch (stream->state) {
+    case PENDING_PACKET_HEADER:
+    {
+      GST_LOG ("HEADER: Parsing PES header");
+
+      /* parse the header */
+      gst_wfd_ts_demux_parse_pes_header (demux, stream, data, size, packet->offset);
+      break;
+    }
+    case PENDING_PACKET_BUFFER:
+    {
+      GST_LOG ("BUFFER: appending data");
+      if (G_UNLIKELY (stream->current_size + size > stream->allocated_size)) {
+        GST_LOG ("resizing buffer");
+        do {
+          stream->allocated_size *= 2;
+        } while (stream->current_size + size > stream->allocated_size);
+        stream->data = g_realloc (stream->data, stream->allocated_size);
+      }
+      memcpy (stream->data + stream->current_size, data, size);
+      stream->current_size += size;
+      break;
+    }
+    case PENDING_PACKET_DISCONT:
+    {
+      GST_LOG ("DISCONT: not storing/pushing");
+      if (G_UNLIKELY (stream->data)) {
+        g_free (stream->data);
+        stream->data = NULL;
+      }
+      stream->continuity_counter = CONTINUITY_UNSET;
+      break;
+    }
+    default:
+      break;
+  }
+
+  return;
+}
+
+static void
+calculate_and_push_newsegment (GstWFDTSDemux * demux, WFDTSDemuxStream * stream)
+{
+  WFDTSBase *base = (WFDTSBase *) demux;
+  GstClockTime lowest_pts = GST_CLOCK_TIME_NONE;
+  GstClockTime firstts = 0;
+  GList *tmp;
+
+  GST_DEBUG ("Creating new newsegment for stream %p", stream);
+
+  /* 1) If we need to calculate an update newsegment, do it
+   * 2) If we need to calculate a new newsegment, do it
+   * 3) If an update_segment is valid, push it
+   * 4) If a newsegment is valid, push it */
+
+  /* Speedup : if we don't need to calculate anything, go straight to pushing */
+  if (!demux->calculate_update_segment && demux->segment_event)
+    goto push_new_segment;
+
+  /* Calculate the 'new_start' value, used for both updates and newsegment */
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *pstream = (WFDTSDemuxStream *) tmp->data;
+
+    if (GST_CLOCK_TIME_IS_VALID (pstream->first_dts)) {
+      if (!GST_CLOCK_TIME_IS_VALID (lowest_pts)
+          || pstream->first_dts < lowest_pts)
+        lowest_pts = pstream->first_dts;
+    }
+  }
+  if (GST_CLOCK_TIME_IS_VALID (lowest_pts))
+    firstts = lowest_pts;
+  GST_DEBUG ("lowest_pts %" G_GUINT64_FORMAT " => clocktime %" GST_TIME_FORMAT,
+      lowest_pts, GST_TIME_ARGS (firstts));
+
+  if (demux->calculate_update_segment) {
+    GST_DEBUG ("Calculating update segment");
+    /* If we have a valid segment, create an update of that */
+    if (demux->segment.format == GST_FORMAT_TIME) {
+      GstSegment update_segment;
+      GST_DEBUG ("Re-using segment " SEGMENT_FORMAT,
+          SEGMENT_ARGS (demux->segment));
+      gst_segment_copy_into (&demux->segment, &update_segment);
+      update_segment.stop = firstts;
+      demux->update_segment = gst_event_new_segment (&update_segment);
+    }
+    demux->calculate_update_segment = FALSE;
+  }
+
+  if (demux->segment.format != GST_FORMAT_TIME) {
+    /* It will happen only if it's first program or after flushes. */
+    GST_DEBUG ("Calculating actual segment");
+#if 0
+    if (base->segment.format == GST_FORMAT_TIME) {
+      /* Try to recover segment info from base if it's in TIME format */
+      demux->segment = base->segment;
+    } else {
+      /* Start from the first ts/pts */
+      gst_segment_init (&demux->segment, GST_FORMAT_TIME);
+      demux->segment.start = firstts;
+      demux->segment.stop = GST_CLOCK_TIME_NONE;
+      demux->segment.position = firstts;
+      demux->segment.time = firstts;
+      demux->segment.rate = demux->rate;
+    }
+#else
+      /* Start from the first ts/pts */
+      gst_segment_init (&demux->segment, GST_FORMAT_TIME);
+      demux->segment.start = firstts;
+      demux->segment.stop = GST_CLOCK_TIME_NONE;
+      demux->segment.position = firstts;
+      demux->segment.time = firstts;
+      demux->segment.rate = demux->rate;
+#endif
+  } else if (demux->segment.start < firstts) {
+    /* Take into account the offset to the first buffer timestamp */
+    if (GST_CLOCK_TIME_IS_VALID (demux->segment.stop))
+      demux->segment.stop += firstts - demux->segment.start;
+    demux->segment.position = firstts;
+    demux->segment.start = firstts;
+  }
+
+  if (!demux->segment_event) {
+    demux->segment_event = gst_event_new_segment (&demux->segment);
+    if(demux->segment_event)
+      GST_EVENT_SEQNUM (demux->segment_event) = base->last_seek_seqnum;
+  }
+
+push_new_segment:
+  if (demux->update_segment) {
+    GST_DEBUG_OBJECT (stream->pad, "Pushing update segment");
+    gst_event_ref (demux->update_segment);
+    gst_pad_push_event (stream->pad, demux->update_segment);
+  }
+
+  if (demux->segment_event) {
+    GST_DEBUG_OBJECT (stream->pad, "Pushing newsegment event");
+    gst_event_ref (demux->segment_event);
+    gst_pad_push_event (stream->pad, demux->segment_event);
+  }
+
+  if (demux->global_tags) {
+    gst_pad_push_event (stream->pad,
+        gst_event_new_tag (gst_tag_list_ref (demux->global_tags)));
+  }
+
+  /* Push pending tags */
+  if (stream->taglist) {
+    GST_DEBUG_OBJECT (stream->pad, "Sending tags %" GST_PTR_FORMAT,
+        stream->taglist);
+    gst_pad_push_event (stream->pad, gst_event_new_tag (stream->taglist));
+    stream->taglist = NULL;
+  }
+
+  stream->need_newsegment = FALSE;
+}
+
+static GstFlowReturn
+gst_wfd_ts_demux_push_pending_data (GstWFDTSDemux * demux, WFDTSDemuxStream * stream)
+{
+  GstFlowReturn res = GST_FLOW_OK;
+#ifndef GST_DISABLE_GST_DEBUG
+  WFDTSBaseStream *bs = (WFDTSBaseStream *) stream;
+#endif
+  GstBuffer *buffer = NULL;
+
+  GST_DEBUG_OBJECT (stream->pad,
+      "stream:%p, pid:0x%04x stream_type:%d state:%d", stream, bs->pid,
+      bs->stream_type, stream->state);
+
+  if (G_UNLIKELY (stream->data == NULL)) {
+    GST_LOG ("stream->data == NULL");
+    goto beach;
+  }
+
+  if (G_UNLIKELY (stream->state == PENDING_PACKET_EMPTY)) {
+    GST_LOG ("EMPTY: returning");
+    goto beach;
+  }
+
+  if (G_UNLIKELY (stream->state != PENDING_PACKET_BUFFER)) {
+    GST_LOG ("state:%d, returning", stream->state);
+    goto beach;
+  }
+
+  if (G_UNLIKELY (demux->program == NULL)) {
+    GST_LOG_OBJECT (demux, "No program");
+    g_free (stream->data);
+    goto beach;
+  }
+
+  if (stream->needs_keyframe) {
+    WFDTSBase *base = (WFDTSBase *) demux;
+
+    if ((gst_wfd_ts_demux_adjust_seek_offset_for_keyframe (stream, stream->data,
+                stream->current_size)) || demux->last_seek_offset == 0) {
+      GST_DEBUG_OBJECT (stream->pad,
+          "Got Keyframe, ready to go at %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (stream->pts));
+      buffer = gst_buffer_new_wrapped (stream->data, stream->current_size);
+      stream->seeked_pts = stream->pts;
+      stream->seeked_dts = stream->dts;
+      stream->needs_keyframe = FALSE;
+    } else {
+      base->seek_offset = demux->last_seek_offset - 200 * base->packetsize;
+      if (demux->last_seek_offset < 200 * base->packetsize)
+        base->seek_offset = 0;
+      demux->last_seek_offset = base->seek_offset;
+      wfd_ts_packetizer_flush (base->packetizer, FALSE);
+      base->mode = BASE_MODE_SEEKING;
+
+      stream->continuity_counter = CONTINUITY_UNSET;
+      res = GST_FLOW_REWINDING;
+      g_free (stream->data);
+      goto beach;
+    }
+  } else {
+    buffer = gst_buffer_new_wrapped (stream->data, stream->current_size);
+
+    if (G_UNLIKELY (stream->pending_ts && !check_pending_buffers (demux))) {
+      PendingBuffer *pend;
+      pend = g_slice_new0 (PendingBuffer);
+      pend->buffer = buffer;
+      pend->pts = stream->raw_pts;
+      pend->dts = stream->raw_dts;
+      stream->pending = g_list_append (stream->pending, pend);
+      GST_DEBUG ("Not enough information to push buffers yet, storing buffer");
+      goto beach;
+    }
+  }
+
+  if (G_UNLIKELY (!stream->active))
+    activate_pad_for_stream (demux, stream);
+
+  if (G_UNLIKELY (stream->need_newsegment))
+    calculate_and_push_newsegment (demux, stream);
+
+  /* FIXME : Push pending buffers if any */
+  if (G_UNLIKELY (stream->pending)) {
+    GList *tmp;
+    for (tmp = stream->pending; tmp; tmp = tmp->next) {
+      PendingBuffer *pend = (PendingBuffer *) tmp->data;
+
+      GST_DEBUG_OBJECT (stream->pad,
+          "Pushing pending buffer PTS:%" GST_TIME_FORMAT " DTS:%"
+          GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (pend->buffer)),
+          GST_TIME_ARGS (GST_BUFFER_DTS (pend->buffer)));
+
+      if (stream->discont)
+        GST_BUFFER_FLAG_SET (pend->buffer, GST_BUFFER_FLAG_DISCONT);
+      stream->discont = FALSE;
+
+      res = gst_pad_push (stream->pad, pend->buffer);
+      g_slice_free (PendingBuffer, pend);
+    }
+    g_list_free (stream->pending);
+    stream->pending = NULL;
+  }
+
+  if ((GST_CLOCK_TIME_IS_VALID (stream->seeked_pts)
+          && stream->pts < stream->seeked_pts) ||
+      (GST_CLOCK_TIME_IS_VALID (stream->seeked_dts) &&
+          stream->pts < stream->seeked_dts)) {
+    GST_INFO_OBJECT (stream->pad,
+        "Droping with PTS: %" GST_TIME_FORMAT " DTS: %" GST_TIME_FORMAT
+        " after seeking as other stream needed to be seeked further"
+        "(seeked PTS: %" GST_TIME_FORMAT " DTS: %" GST_TIME_FORMAT ")",
+        GST_TIME_ARGS (stream->pts), GST_TIME_ARGS (stream->dts),
+        GST_TIME_ARGS (stream->seeked_pts), GST_TIME_ARGS (stream->seeked_dts));
+    gst_buffer_unref (buffer);
+    goto beach;
+  }
+
+  GST_DEBUG_OBJECT (stream->pad, "stream->pts %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (stream->pts));
+  if (GST_CLOCK_TIME_IS_VALID (stream->pts))
+    GST_BUFFER_PTS (buffer) = stream->pts;
+  if (GST_CLOCK_TIME_IS_VALID (stream->dts))
+    GST_BUFFER_DTS (buffer) = stream->dts;
+
+  GST_DEBUG_OBJECT (stream->pad,
+      "Pushing buffer with PTS: %" GST_TIME_FORMAT " , DTS: %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
+      GST_TIME_ARGS (GST_BUFFER_DTS (buffer)));
+
+  if (stream->discont)
+    GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
+  stream->discont = FALSE;
+
+  res = gst_pad_push (stream->pad, buffer);
+  GST_DEBUG_OBJECT (stream->pad, "Returned %s", gst_flow_get_name (res));
+  res = gst_flow_combiner_update_flow (demux->flowcombiner, res);
+  GST_DEBUG_OBJECT (stream->pad, "combined %s", gst_flow_get_name (res));
+
+beach:
+  /* Reset everything */
+  GST_LOG ("Resetting to EMPTY, returning %s", gst_flow_get_name (res));
+  stream->state = PENDING_PACKET_EMPTY;
+  stream->data = NULL;
+  stream->expected_size = 0;
+  stream->current_size = 0;
+
+  return res;
+}
+
+static GstFlowReturn
+gst_wfd_ts_demux_handle_packet (GstWFDTSDemux * demux, WFDTSDemuxStream * stream,
+    WFDTSPacketizerPacket * packet, GstWFDTSSection * section)
+{
+  GstFlowReturn res = GST_FLOW_OK;
+
+  GST_LOG ("pid 0x%04x pusi:%d, afc:%d, cont:%d, payload:%p", packet->pid,
+      packet->payload_unit_start_indicator, packet->scram_afc_cc & 0x30,
+      FLAGS_CONTINUITY_COUNTER (packet->scram_afc_cc), packet->payload);
+
+  if (G_UNLIKELY (packet->payload_unit_start_indicator) &&
+      FLAGS_HAS_PAYLOAD (packet->scram_afc_cc))
+    /* Flush previous data */
+    res = gst_wfd_ts_demux_push_pending_data (demux, stream);
+
+  if (packet->payload && (res == GST_FLOW_OK || res == GST_FLOW_NOT_LINKED)
+      && stream->pad) {
+    gst_wfd_ts_demux_queue_data (demux, stream, packet);
+    GST_LOG ("current_size:%d, expected_size:%d",
+        stream->current_size, stream->expected_size);
+    /* Finally check if the data we queued completes a packet */
+    if (stream->expected_size && stream->current_size == stream->expected_size) {
+      GST_LOG ("pushing complete packet");
+      res = gst_wfd_ts_demux_push_pending_data (demux, stream);
+    }
+  }
+
+  /* We are rewinding to find a keyframe,
+   * and didn't want the data to be queued
+   */
+  if (res == GST_FLOW_REWINDING)
+    res = GST_FLOW_OK;
+
+  return res;
+}
+
+static void
+gst_wfd_ts_demux_flush (WFDTSBase * base, gboolean hard)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX_CAST (base);
+
+  gst_wfd_ts_demux_flush_streams (demux);
+
+  if (demux->segment_event) {
+    gst_event_unref (demux->segment_event);
+    demux->segment_event = NULL;
+  }
+  demux->calculate_update_segment = FALSE;
+  if (demux->global_tags) {
+    gst_tag_list_unref (demux->global_tags);
+    demux->global_tags = NULL;
+  }
+  if (hard) {
+    /* For pull mode seeks the current segment needs to be preserved */
+    demux->rate = 1.0;
+    gst_segment_init (&demux->segment, GST_FORMAT_UNDEFINED);
+  }
+}
+
+static GstFlowReturn
+gst_wfd_ts_demux_drain (WFDTSBase * base)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX_CAST (base);
+  GList *tmp;
+  GstFlowReturn res = GST_FLOW_OK;
+
+  if (!demux->program)
+    return res;
+
+  for (tmp = demux->program->stream_list; tmp; tmp = tmp->next) {
+    WFDTSDemuxStream *stream = (WFDTSDemuxStream *) tmp->data;
+    if (stream->pad) {
+      res = gst_wfd_ts_demux_push_pending_data (demux, stream);
+      if (G_UNLIKELY (res != GST_FLOW_OK))
+        break;
+    }
+  }
+
+  return res;
+}
+
+static GstFlowReturn
+gst_wfd_ts_demux_push (WFDTSBase * base, WFDTSPacketizerPacket * packet,
+    GstWFDTSSection * section)
+{
+  GstWFDTSDemux *demux = GST_WFD_TS_DEMUX_CAST (base);
+  WFDTSDemuxStream *stream = NULL;
+  GstFlowReturn res = GST_FLOW_OK;
+
+  if (G_LIKELY (demux->program)) {
+    stream = (WFDTSDemuxStream *) demux->program->streams[packet->pid];
+
+    if (stream) {
+      res = gst_wfd_ts_demux_handle_packet (demux, stream, packet, section);
+    }
+  }
+  return res;
+}
+
+gboolean
+gst_wfd_ts_demux_plugin_init (GstPlugin * plugin)
+{
+  GST_DEBUG_CATEGORY_INIT (wfd_ts_demux_debug, "wfdtsdemux", 0,
+      "Wi-Fi Display transport stream demuxer");
+  wfd_pes_parser_init ();
+
+  return gst_element_register (plugin, "wfdtsdemux",
+      GST_RANK_NONE, GST_TYPE_WFD_TS_DEMUX);
+}
diff --git a/wfdtsdemux/wfdtsdemux.h b/wfdtsdemux/wfdtsdemux.h
new file mode 100755 (executable)
index 0000000..90f069b
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * tsdemux - GStreamer MPEG transport stream demuxer
+ * Copyright (C) 2009 Zaheer Abbas Merali
+ *               2010 Edward Hervey
+ *
+ * Authors:
+ *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
+ *   Edward Hervey <edward.hervey@collabora.co.uk>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef GST_WFD_TS_DEMUX_H
+#define GST_WFD_TS_DEMUX_H
+
+#include <gst/gst.h>
+#include <gst/base/gstbytereader.h>
+#include <gst/base/gstflowcombiner.h>
+#include "wfdtsbase.h"
+#include "wfdtspacketizer.h"
+
+G_BEGIN_DECLS
+#define GST_TYPE_WFD_TS_DEMUX \
+  (gst_wfd_ts_demux_get_type())
+#define GST_WFD_TS_DEMUX(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_WFD_TS_DEMUX,GstWFDTSDemux))
+#define GST_WFD_TS_DEMUX_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_WFD_TS_DEMUX,GstWFDTSDemuxClass))
+#define GST_IS_WFD_TS_DEMUX(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_TS_DEMUX))
+#define GST_IS_WFD_TS_DEMUX_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_TS_DEMUX))
+#define GST_WFD_TS_DEMUX_GET_CLASS(obj) \
+  (G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_WFD_TS_DEMUX, GstWFDTSDemuxClass))
+#define GST_WFD_TS_DEMUX_CAST(obj) ((GstWFDTSDemux*) obj)
+typedef struct _GstWFDTSDemux GstWFDTSDemux;
+typedef struct _GstWFDTSDemuxClass GstWFDTSDemuxClass;
+
+struct _GstWFDTSDemux
+{
+  WFDTSBase parent;
+
+  gboolean have_group_id;
+  guint group_id;
+
+  /* the following vars must be protected with the OBJECT_LOCK as they can be
+   * accessed from the application thread and the streaming thread */
+  gint requested_program_number; /* Required program number (ignore:-1) */
+  guint program_number;
+  gboolean emit_statistics;
+
+  /*< private >*/
+  WFDTSBaseProgram *program;   /* Current program */
+
+  /* segments to be sent */
+  GstSegment segment;
+  GstEvent *segment_event;
+
+  /* global taglist */
+  GstTagList *global_tags;
+
+  /* Set when program change */
+  gboolean calculate_update_segment;
+  /* update segment is */
+  GstEvent *update_segment;
+
+  /* Full stream duration */
+  GstClockTime duration;
+
+  /* Pending seek rate (default 1.0) */
+  gdouble rate;
+
+  GstFlowCombiner *flowcombiner;
+
+  /* Used when seeking for a keyframe to go backward in the stream */
+  guint64 last_seek_offset;
+};
+
+struct _GstWFDTSDemuxClass
+{
+  WFDTSBaseClass parent_class;
+};
+
+G_GNUC_INTERNAL GType gst_wfd_ts_demux_get_type (void);
+
+G_GNUC_INTERNAL gboolean gst_wfd_ts_demux_plugin_init (GstPlugin * plugin);
+
+G_END_DECLS
+#endif /* GST_WFD_TS_DEMUX_H */
diff --git a/wfdtsdemux/wfdtspacketizer.c b/wfdtsdemux/wfdtspacketizer.c
new file mode 100755 (executable)
index 0000000..4d40a73
--- /dev/null
@@ -0,0 +1,2486 @@
+/*
+ * wfdtspacketizer.c -
+ * Copyright (C) 2007, 2008 Alessandro Decina, Zaheer Merali
+ *
+ * Authors:
+ *   Zaheer Merali <zaheerabbas at merali dot org>
+ *   Alessandro Decina <alessandro@nnva.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+
+/* Skew calculation pameters */
+#define MAX_TIME       (2 * GST_SECOND)
+
+/* maximal PCR time */
+#define PCR_MAX_VALUE (((((guint64)1)<<33) * 300) + 298)
+#define PCR_GST_MAX_VALUE (PCR_MAX_VALUE * GST_MSECOND / (PCR_MSECOND))
+#define PTS_DTS_MAX_VALUE (((guint64)1) << 33)
+
+#include "wfdtspacketizer.h"
+#include "gstwfdtsdesc.h"
+
+GST_DEBUG_CATEGORY_STATIC (wfd_ts_packetizer_debug);
+#define GST_CAT_DEFAULT wfd_ts_packetizer_debug
+
+static void _init_local (void);
+G_DEFINE_TYPE_EXTENDED (WFDTSPacketizer, wfd_ts_packetizer, G_TYPE_OBJECT, 0,
+    _init_local ());
+
+#define ABSDIFF(a,b) ((a) < (b) ? (b) - (a) : (a) - (b))
+
+#define PACKETIZER_GROUP_LOCK(p) g_mutex_lock(&((p)->group_lock))
+#define PACKETIZER_GROUP_UNLOCK(p) g_mutex_unlock(&((p)->group_lock))
+
+static void wfd_ts_packetizer_dispose (GObject * object);
+static void wfd_ts_packetizer_finalize (GObject * object);
+static GstClockTime calculate_skew (WFDTSPCR * pcr, guint64 pcrtime,
+    GstClockTime time);
+static void _close_current_group (WFDTSPCR * pcrtable);
+static void record_pcr (WFDTSPacketizer * packetizer, WFDTSPCR * pcrtable,
+    guint64 pcr, guint64 offset);
+
+#define CONTINUITY_UNSET 255
+#define VERSION_NUMBER_UNSET 255
+#define TABLE_ID_UNSET 0xFF
+#define PACKET_SYNC_BYTE 0x47
+
+static inline WFDTSPCR *
+get_pcr_table (WFDTSPacketizer * packetizer, guint16 pid)
+{
+  WFDTSPCR *res;
+
+  res = packetizer->observations[packetizer->pcrtablelut[pid]];
+
+  if (G_UNLIKELY (res == NULL)) {
+    /* If we don't have a PCR table for the requested PID, create one .. */
+    res = g_new0 (WFDTSPCR, 1);
+    /* Add it to the last table position */
+    packetizer->observations[packetizer->lastobsid] = res;
+    /* Update the pcrtablelut */
+    packetizer->pcrtablelut[pid] = packetizer->lastobsid;
+    /* And increment the last know slot */
+    packetizer->lastobsid++;
+
+    /* Finally set the default values */
+    res->pid = pid;
+    res->base_time = GST_CLOCK_TIME_NONE;
+    res->base_pcrtime = GST_CLOCK_TIME_NONE;
+    res->last_pcrtime = GST_CLOCK_TIME_NONE;
+    res->window_pos = 0;
+    res->window_filling = TRUE;
+    res->window_min = 0;
+    res->skew = 0;
+    res->prev_send_diff = GST_CLOCK_TIME_NONE;
+    res->prev_out_time = GST_CLOCK_TIME_NONE;
+    res->pcroffset = 0;
+
+    res->current = g_slice_new0 (PCROffsetCurrent);
+  }
+
+  return res;
+}
+
+static void
+pcr_offset_group_free (PCROffsetGroup * group)
+{
+  g_free (group->values);
+  g_slice_free (PCROffsetGroup, group);
+}
+
+static void
+flush_observations (WFDTSPacketizer * packetizer)
+{
+  gint i;
+
+  for (i = 0; i < packetizer->lastobsid; i++) {
+    g_list_free_full (packetizer->observations[i]->groups,
+        (GDestroyNotify) pcr_offset_group_free);
+    if (packetizer->observations[i]->current)
+      g_slice_free (PCROffsetCurrent, packetizer->observations[i]->current);
+    g_free (packetizer->observations[i]);
+    packetizer->observations[i] = NULL;
+  }
+  memset (packetizer->pcrtablelut, 0xff, 0x2000);
+  packetizer->lastobsid = 0;
+}
+
+static inline WFDTSPacketizerStreamSubtable *
+find_subtable (GSList * subtables, guint8 table_id, guint16 subtable_extension)
+{
+  GSList *tmp;
+
+  /* FIXME: Make this an array ! */
+  for (tmp = subtables; tmp; tmp = tmp->next) {
+    WFDTSPacketizerStreamSubtable *sub =
+        (WFDTSPacketizerStreamSubtable *) tmp->data;
+    if (sub->table_id == table_id
+        && sub->subtable_extension == subtable_extension)
+      return sub;
+  }
+
+  return FALSE;
+}
+
+static gboolean
+seen_section_before (WFDTSPacketizerStream * stream, guint8 table_id,
+    guint16 subtable_extension, guint8 version_number, guint8 section_number,
+    guint8 last_section_number)
+{
+  WFDTSPacketizerStreamSubtable *subtable;
+
+  /* Check if we've seen this table_id/subtable_extension first */
+  subtable = find_subtable (stream->subtables, table_id, subtable_extension);
+  if (!subtable) {
+    GST_DEBUG ("Haven't seen subtable");
+    return FALSE;
+  }
+  /* If we have, check it has the same version_number */
+  if (subtable->version_number != version_number) {
+    GST_DEBUG ("Different version number");
+    return FALSE;
+  }
+  /* Did the number of sections change ? */
+  if (subtable->last_section_number != last_section_number) {
+    GST_DEBUG ("Different last_section_number");
+    return FALSE;
+  }
+  /* Finally return whether we saw that section or not */
+  return WFD_TS_BIT_IS_SET (subtable->seen_section, section_number);
+}
+
+static WFDTSPacketizerStreamSubtable *
+wfd_ts_packetizer_stream_subtable_new (guint8 table_id,
+    guint16 subtable_extension, guint8 last_section_number)
+{
+  WFDTSPacketizerStreamSubtable *subtable;
+
+  subtable = g_new0 (WFDTSPacketizerStreamSubtable, 1);
+  subtable->version_number = VERSION_NUMBER_UNSET;
+  subtable->table_id = table_id;
+  subtable->subtable_extension = subtable_extension;
+  subtable->last_section_number = last_section_number;
+  return subtable;
+}
+
+static WFDTSPacketizerStream *
+wfd_ts_packetizer_stream_new (guint16 pid)
+{
+  WFDTSPacketizerStream *stream;
+
+  stream = (WFDTSPacketizerStream *) g_new0 (WFDTSPacketizerStream, 1);
+  stream->continuity_counter = CONTINUITY_UNSET;
+  stream->subtables = NULL;
+  stream->table_id = TABLE_ID_UNSET;
+  stream->pid = pid;
+  return stream;
+}
+
+static void
+wfd_ts_packetizer_clear_section (WFDTSPacketizerStream * stream)
+{
+  stream->continuity_counter = CONTINUITY_UNSET;
+  stream->section_length = 0;
+  stream->section_offset = 0;
+  stream->table_id = TABLE_ID_UNSET;
+  if (stream->section_data)
+    g_free (stream->section_data);
+  stream->section_data = NULL;
+}
+
+static void
+wfd_ts_packetizer_stream_subtable_free (WFDTSPacketizerStreamSubtable *
+    subtable)
+{
+  g_free (subtable);
+}
+
+static void
+wfd_ts_packetizer_stream_free (WFDTSPacketizerStream * stream)
+{
+  wfd_ts_packetizer_clear_section (stream);
+  if (stream->section_data)
+    g_free (stream->section_data);
+  g_slist_foreach (stream->subtables,
+      (GFunc) wfd_ts_packetizer_stream_subtable_free, NULL);
+  g_slist_free (stream->subtables);
+  g_free (stream);
+}
+
+static void
+wfd_ts_packetizer_class_init (WFDTSPacketizerClass * klass)
+{
+  GObjectClass *gobject_class;
+
+  gobject_class = G_OBJECT_CLASS (klass);
+
+  gobject_class->dispose = wfd_ts_packetizer_dispose;
+  gobject_class->finalize = wfd_ts_packetizer_finalize;
+}
+
+static void
+wfd_ts_packetizer_init (WFDTSPacketizer * packetizer)
+{
+  g_mutex_init (&packetizer->group_lock);
+
+  packetizer->adapter = gst_adapter_new ();
+  packetizer->offset = 0;
+  packetizer->empty = TRUE;
+  packetizer->streams = g_new0 (WFDTSPacketizerStream *, 8192);
+  packetizer->packet_size = 0;
+  packetizer->calculate_skew = FALSE;
+  packetizer->calculate_offset = FALSE;
+
+  packetizer->map_data = NULL;
+  packetizer->map_size = 0;
+  packetizer->map_offset = 0;
+  packetizer->need_sync = FALSE;
+
+  memset (packetizer->pcrtablelut, 0xff, 0x2000);
+  memset (packetizer->observations, 0x0, sizeof (packetizer->observations));
+  packetizer->lastobsid = 0;
+
+  packetizer->nb_seen_offsets = 0;
+  packetizer->refoffset = -1;
+  packetizer->last_in_time = GST_CLOCK_TIME_NONE;
+}
+
+static void
+wfd_ts_packetizer_dispose (GObject * object)
+{
+  WFDTSPacketizer *packetizer = GST_WFD_TS_PACKETIZER (object);
+
+  if (!packetizer->disposed) {
+    if (packetizer->packet_size)
+      packetizer->packet_size = 0;
+    if (packetizer->streams) {
+      int i;
+      for (i = 0; i < 8192; i++) {
+        if (packetizer->streams[i])
+          wfd_ts_packetizer_stream_free (packetizer->streams[i]);
+      }
+      g_free (packetizer->streams);
+    }
+
+    gst_adapter_clear (packetizer->adapter);
+    g_object_unref (packetizer->adapter);
+    g_mutex_clear (&packetizer->group_lock);
+    packetizer->disposed = TRUE;
+    packetizer->offset = 0;
+    packetizer->empty = TRUE;
+
+    flush_observations (packetizer);
+  }
+
+  if (G_OBJECT_CLASS (wfd_ts_packetizer_parent_class)->dispose)
+    G_OBJECT_CLASS (wfd_ts_packetizer_parent_class)->dispose (object);
+}
+
+static void
+wfd_ts_packetizer_finalize (GObject * object)
+{
+  if (G_OBJECT_CLASS (wfd_ts_packetizer_parent_class)->finalize)
+    G_OBJECT_CLASS (wfd_ts_packetizer_parent_class)->finalize (object);
+}
+
+static inline guint64
+wfd_ts_packetizer_compute_pcr (const guint8 * data)
+{
+  guint32 pcr1;
+  guint16 pcr2;
+  guint64 pcr, pcr_ext;
+
+  pcr1 = GST_READ_UINT32_BE (data);
+  pcr2 = GST_READ_UINT16_BE (data + 4);
+  pcr = ((guint64) pcr1) << 1;
+  pcr |= (pcr2 & 0x8000) >> 15;
+  pcr_ext = (pcr2 & 0x01ff);
+  return pcr * 300 + pcr_ext % 300;
+}
+
+static gboolean
+wfd_ts_packetizer_parse_adaptation_field_control (WFDTSPacketizer *
+    packetizer, WFDTSPacketizerPacket * packet)
+{
+  guint8 length, afcflags;
+  guint8 *data;
+
+  length = *packet->data++;
+
+  /* an adaptation field with length 0 is valid and
+   * can be used to insert a single stuffing byte */
+  if (!length) {
+    packet->afc_flags = 0;
+    return TRUE;
+  }
+
+  if ((packet->scram_afc_cc & 0x30) == 0x20) {
+    /* no payload, adaptation field of 183 bytes */
+    if (length > 183) {
+      GST_WARNING ("PID %d afc == 0x%02x and length %d > 183",
+          packet->pid, packet->scram_afc_cc & 0x30, length);
+      return FALSE;
+    }
+    if (length != 183) {
+      GST_WARNING ("PID %d afc == 0x%02x and length %d != 183",
+          packet->pid, packet->scram_afc_cc & 0x30, length);
+      GST_MEMDUMP ("Unknown payload", packet->data + length,
+          packet->data_end - packet->data - length);
+    }
+  } else if (length > 182) {
+    GST_WARNING ("PID %d afc == 0x%02x and length %d > 182",
+        packet->pid, packet->scram_afc_cc & 0x30, length);
+    return FALSE;
+  }
+
+  if (packet->data + length > packet->data_end) {
+    GST_DEBUG ("PID %d afc length %d overflows the buffer current %d max %d",
+        packet->pid, length, (gint) (packet->data - packet->data_start),
+        (gint) (packet->data_end - packet->data_start));
+    return FALSE;
+  }
+
+  data = packet->data;
+  packet->data += length;
+
+  afcflags = packet->afc_flags = *data++;
+
+  GST_DEBUG ("flags: %s%s%s%s%s%s%s%s%s",
+      afcflags & 0x80 ? "discontinuity " : "",
+      afcflags & 0x40 ? "random_access " : "",
+      afcflags & 0x20 ? "elementary_stream_priority " : "",
+      afcflags & 0x10 ? "PCR " : "",
+      afcflags & 0x08 ? "OPCR " : "",
+      afcflags & 0x04 ? "splicing_point " : "",
+      afcflags & 0x02 ? "transport_private_data " : "",
+      afcflags & 0x01 ? "extension " : "", afcflags == 0x00 ? "<none>" : "");
+
+  /* PCR */
+  if (afcflags & MPEGTS_AFC_PCR_FLAG) {
+    WFDTSPCR *pcrtable = NULL;
+    packet->pcr = wfd_ts_packetizer_compute_pcr (data);
+    data += 6;
+    GST_DEBUG ("pcr 0x%04x %" G_GUINT64_FORMAT " (%" GST_TIME_FORMAT
+        ") offset:%" G_GUINT64_FORMAT, packet->pid, packet->pcr,
+        GST_TIME_ARGS (PCRTIME_TO_GSTTIME (packet->pcr)), packet->offset);
+
+    PACKETIZER_GROUP_LOCK (packetizer);
+    if (packetizer->calculate_skew
+        && GST_CLOCK_TIME_IS_VALID (packetizer->last_in_time)) {
+      pcrtable = get_pcr_table (packetizer, packet->pid);
+      if (pcrtable)
+        calculate_skew (pcrtable, packet->pcr, packetizer->last_in_time);
+    }
+    if (packetizer->calculate_offset) {
+      if (!pcrtable)
+        pcrtable = get_pcr_table (packetizer, packet->pid);
+
+      if (pcrtable)
+        record_pcr (packetizer, pcrtable, packet->pcr, packet->offset);
+    }
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+  }
+#ifndef GST_DISABLE_GST_DEBUG
+  /* OPCR */
+  if (afcflags & MPEGTS_AFC_OPCR_FLAG) {
+    /* Note: We don't use/need opcr for the time being */
+    guint64 opcr = wfd_ts_packetizer_compute_pcr (data);
+    data += 6;
+    GST_DEBUG ("opcr %" G_GUINT64_FORMAT " (%" GST_TIME_FORMAT ")",
+        opcr, GST_TIME_ARGS (PCRTIME_TO_GSTTIME (opcr)));
+  }
+
+  if (afcflags & MPEGTS_AFC_SPLICING_POINT_FLAG) {
+    GST_DEBUG ("splice_countdown: %u", *data++);
+  }
+
+  if (afcflags & MPEGTS_AFC_TRANSPORT_PRIVATE_DATA_FLAG) {
+    guint8 len = *data++;
+    GST_MEMDUMP ("private data", data, len);
+    data += len;
+  }
+
+  if (afcflags & MPEGTS_AFC_EXTENSION_FLAG) {
+    guint8 extlen = *data++;
+    guint8 flags = *data++;
+    GST_DEBUG ("extension size:%d flags : %s%s%s", extlen,
+        flags & 0x80 ? "ltw " : "",
+        flags & 0x40 ? "piecewise_rate " : "",
+        flags & 0x20 ? "seamless_splice " : "");
+    if (flags & 0x80) {
+      GST_DEBUG ("legal time window: valid_flag:%d offset:%d", *data >> 7,
+          GST_READ_UINT16_BE (data) & 0x7fff);
+      data += 2;
+    }
+  }
+#endif
+
+  return TRUE;
+}
+
+static WFDTSPacketizerPacketReturn
+wfd_ts_packetizer_parse_packet (WFDTSPacketizer * packetizer,
+    WFDTSPacketizerPacket * packet)
+{
+  guint8 *data;
+  guint8 tmp;
+
+  data = packet->data_start;
+  data += 1;
+  tmp = *data;
+
+  /* transport_error_indicator 1 */
+  if (G_UNLIKELY (tmp & 0x80))
+    return PACKET_BAD;
+
+  /* payload_unit_start_indicator 1 */
+  packet->payload_unit_start_indicator = tmp & 0x40;
+
+  /* transport_priority 1 */
+  /* PID 13 */
+  packet->pid = GST_READ_UINT16_BE (data) & 0x1FFF;
+  data += 2;
+
+  packet->scram_afc_cc = tmp = *data++;
+  /* transport_scrambling_control 2 */
+  if (G_UNLIKELY (tmp & 0xc0))
+    return PACKET_BAD;
+
+  packet->data = data;
+
+  packet->afc_flags = 0;
+  packet->pcr = G_MAXUINT64;
+
+  if (FLAGS_HAS_AFC (tmp)) {
+    if (!wfd_ts_packetizer_parse_adaptation_field_control (packetizer, packet))
+      return FALSE;
+  }
+
+  if (FLAGS_HAS_PAYLOAD (tmp))
+    packet->payload = packet->data;
+  else
+    packet->payload = NULL;
+
+  return PACKET_OK;
+}
+
+static GstWFDTSSection *
+wfd_ts_packetizer_parse_section_header (WFDTSPacketizer * packetizer,
+    WFDTSPacketizerStream * stream)
+{
+  WFDTSPacketizerStreamSubtable *subtable;
+  GstWFDTSSection *res;
+
+  subtable =
+      find_subtable (stream->subtables, stream->table_id,
+      stream->subtable_extension);
+  if (subtable) {
+    GST_DEBUG ("Found previous subtable_extension:0x%04x",
+        stream->subtable_extension);
+    if (G_UNLIKELY (stream->version_number != subtable->version_number)) {
+      /* If the version number changed, reset the subtable */
+      subtable->version_number = stream->version_number;
+      subtable->last_section_number = stream->last_section_number;
+      memset (subtable->seen_section, 0, 32);
+    }
+  } else {
+    GST_DEBUG ("Appending new subtable_extension: 0x%04x",
+        stream->subtable_extension);
+    subtable = wfd_ts_packetizer_stream_subtable_new (stream->table_id,
+        stream->subtable_extension, stream->last_section_number);
+    subtable->version_number = stream->version_number;
+
+    stream->subtables = g_slist_prepend (stream->subtables, subtable);
+  }
+
+  GST_MEMDUMP ("Full section data", stream->section_data,
+      stream->section_length);
+  /* TODO ? : Replace this by an efficient version (where we provide all
+   * pre-parsed header data) */
+  res =
+      gst_wfd_ts_section_new (stream->pid, stream->section_data,
+      stream->section_length);
+  stream->section_data = NULL;
+  wfd_ts_packetizer_clear_section (stream);
+
+  if (res) {
+    /* NOTE : Due to the new mpegts-si system, There is a insanely low probability
+     * that we might have gotten a section that was corrupted (i.e. wrong crc)
+     * and that we consider it as seen.
+     *
+     * The reason why we consider this as acceptable is because all the previous
+     * checks were already done:
+     * * transport layer checks (DVB)
+     * * 0x47 validation
+     * * continuity counter validation
+     * * subtable validation
+     * * section_number validation
+     * * section_length validation
+     *
+     * The probability of this happening vs the overhead of doing CRC checks
+     * on all sections (including those we would not use) is just not worth it.
+     * */
+    WFD_TS_BIT_SET (subtable->seen_section, stream->section_number);
+    res->offset = stream->offset;
+  }
+
+  return res;
+}
+
+void
+wfd_ts_packetizer_clear (WFDTSPacketizer * packetizer)
+{
+  guint i;
+
+  if (packetizer->packet_size)
+    packetizer->packet_size = 0;
+
+  if (packetizer->streams) {
+    int i;
+    for (i = 0; i < 8192; i++) {
+      if (packetizer->streams[i]) {
+        wfd_ts_packetizer_stream_free (packetizer->streams[i]);
+      }
+    }
+    memset (packetizer->streams, 0, 8192 * sizeof (WFDTSPacketizerStream *));
+  }
+
+  gst_adapter_clear (packetizer->adapter);
+  packetizer->offset = 0;
+  packetizer->empty = TRUE;
+  packetizer->need_sync = FALSE;
+  packetizer->map_data = NULL;
+  packetizer->map_size = 0;
+  packetizer->map_offset = 0;
+  packetizer->last_in_time = GST_CLOCK_TIME_NONE;
+
+  /* Close current PCR group */
+  PACKETIZER_GROUP_LOCK (packetizer);
+
+  for (i = 0; i < MAX_PCR_OBS_CHANNELS; i++) {
+    if (packetizer->observations[i])
+      _close_current_group (packetizer->observations[i]);
+    else
+      break;
+  }
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+}
+
+void
+wfd_ts_packetizer_flush (WFDTSPacketizer * packetizer, gboolean hard)
+{
+  guint i;
+  GST_DEBUG ("Flushing");
+
+  if (packetizer->streams) {
+    for (i = 0; i < 8192; i++) {
+      if (packetizer->streams[i]) {
+        wfd_ts_packetizer_clear_section (packetizer->streams[i]);
+      }
+    }
+  }
+  gst_adapter_clear (packetizer->adapter);
+
+  packetizer->offset = 0;
+  packetizer->empty = TRUE;
+  packetizer->need_sync = FALSE;
+  packetizer->map_data = NULL;
+  packetizer->map_size = 0;
+  packetizer->map_offset = 0;
+  packetizer->last_in_time = GST_CLOCK_TIME_NONE;
+
+  /* Close current PCR group */
+  PACKETIZER_GROUP_LOCK (packetizer);
+  for (i = 0; i < MAX_PCR_OBS_CHANNELS; i++) {
+    if (packetizer->observations[i])
+      _close_current_group (packetizer->observations[i]);
+    else
+      break;
+  }
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+
+  if (hard) {
+    /* For pull mode seeks in tsdemux the observation must be preserved */
+    flush_observations (packetizer);
+  }
+}
+
+void
+wfd_ts_packetizer_remove_stream (WFDTSPacketizer * packetizer, gint16 pid)
+{
+  WFDTSPacketizerStream *stream = packetizer->streams[pid];
+  if (stream) {
+    GST_INFO ("Removing stream for PID %d", pid);
+    wfd_ts_packetizer_stream_free (stream);
+    packetizer->streams[pid] = NULL;
+  }
+}
+
+WFDTSPacketizer *
+wfd_ts_packetizer_new (void)
+{
+  WFDTSPacketizer *packetizer;
+
+  packetizer =
+      GST_WFD_TS_PACKETIZER (g_object_new (GST_TYPE_WFD_TS_PACKETIZER, NULL));
+
+  return packetizer;
+}
+
+void
+wfd_ts_packetizer_push (WFDTSPacketizer * packetizer, GstBuffer * buffer)
+{
+  if (G_UNLIKELY (packetizer->empty)) {
+    packetizer->empty = FALSE;
+    packetizer->offset = GST_BUFFER_OFFSET (buffer);
+  }
+
+  GST_DEBUG ("Pushing %" G_GSIZE_FORMAT " byte from offset %"
+      G_GUINT64_FORMAT, gst_buffer_get_size (buffer),
+      GST_BUFFER_OFFSET (buffer));
+  gst_adapter_push (packetizer->adapter, buffer);
+  /* If buffer timestamp is valid, store it */
+  if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_TIMESTAMP (buffer)))
+    packetizer->last_in_time = GST_BUFFER_TIMESTAMP (buffer);
+}
+
+static void
+wfd_ts_packetizer_flush_bytes (WFDTSPacketizer * packetizer, gsize size)
+{
+  if (size > 0) {
+    GST_LOG ("flushing %" G_GSIZE_FORMAT " bytes from adapter", size);
+    gst_adapter_flush (packetizer->adapter, size);
+  }
+
+  packetizer->map_data = NULL;
+  packetizer->map_size = 0;
+  packetizer->map_offset = 0;
+}
+
+static gboolean
+wfd_ts_packetizer_map (WFDTSPacketizer * packetizer, gsize size)
+{
+  gsize available;
+
+  if (packetizer->map_size - packetizer->map_offset >= size)
+    return TRUE;
+
+  wfd_ts_packetizer_flush_bytes (packetizer, packetizer->map_offset);
+
+  available = gst_adapter_available (packetizer->adapter);
+  if (available < size)
+    return FALSE;
+
+  packetizer->map_data =
+      (guint8 *) gst_adapter_map (packetizer->adapter, available);
+  if (!packetizer->map_data)
+    return FALSE;
+
+  packetizer->map_size = available;
+  packetizer->map_offset = 0;
+
+  GST_LOG ("mapped %" G_GSIZE_FORMAT " bytes from adapter", available);
+
+  return TRUE;
+}
+
+static gboolean
+wfd_ts_try_discover_packet_size (WFDTSPacketizer * packetizer)
+{
+  guint8 *data;
+  gsize size, i, j;
+
+  static const guint psizes[] = {
+    WFD_TS_NORMAL_PACKETSIZE,
+    WFD_TS_M2TS_PACKETSIZE,
+    WFD_TS_DVB_ASI_PACKETSIZE,
+    WFD_TS_ATSC_PACKETSIZE
+  };
+
+  if (!wfd_ts_packetizer_map (packetizer, 4 * WFD_TS_MAX_PACKETSIZE))
+    return FALSE;
+
+  size = packetizer->map_size - packetizer->map_offset;
+  data = packetizer->map_data + packetizer->map_offset;
+
+  for (i = 0; i + 3 * WFD_TS_MAX_PACKETSIZE < size; i++) {
+    /* find a sync byte */
+    if (data[i] != PACKET_SYNC_BYTE)
+      continue;
+
+    /* check for 4 consecutive sync bytes with each possible packet size */
+    for (j = 0; j < G_N_ELEMENTS (psizes); j++) {
+      guint packet_size = psizes[j];
+
+      if (data[i + packet_size] == PACKET_SYNC_BYTE &&
+          data[i + 2 * packet_size] == PACKET_SYNC_BYTE &&
+          data[i + 3 * packet_size] == PACKET_SYNC_BYTE) {
+        packetizer->packet_size = packet_size;
+        goto out;
+      }
+    }
+  }
+
+out:
+  packetizer->map_offset += i;
+
+  if (packetizer->packet_size == 0) {
+    GST_DEBUG ("Could not determine packet size in %" G_GSIZE_FORMAT
+        " bytes buffer, flush %" G_GSIZE_FORMAT " bytes", size, i);
+    wfd_ts_packetizer_flush_bytes (packetizer, packetizer->map_offset);
+    return FALSE;
+  }
+
+  GST_INFO ("have packetsize detected: %u bytes", packetizer->packet_size);
+
+  if (packetizer->packet_size == WFD_TS_M2TS_PACKETSIZE &&
+      packetizer->map_offset >= 4)
+    packetizer->map_offset -= 4;
+
+  return TRUE;
+}
+
+static gboolean
+wfd_ts_packetizer_sync (WFDTSPacketizer * packetizer)
+{
+  gboolean found = FALSE;
+  guint8 *data;
+  guint packet_size;
+  gsize size, sync_offset, i;
+
+  packet_size = packetizer->packet_size;
+
+  if (!wfd_ts_packetizer_map (packetizer, 3 * packet_size))
+    return FALSE;
+
+  size = packetizer->map_size - packetizer->map_offset;
+  data = packetizer->map_data + packetizer->map_offset;
+
+  if (packet_size == WFD_TS_M2TS_PACKETSIZE)
+    sync_offset = 4;
+  else
+    sync_offset = 0;
+
+  for (i = sync_offset; i + 2 * packet_size < size; i++) {
+    if (data[i] == PACKET_SYNC_BYTE &&
+        data[i + packet_size] == PACKET_SYNC_BYTE &&
+        data[i + 2 * packet_size] == PACKET_SYNC_BYTE) {
+      found = TRUE;
+      break;
+    }
+  }
+
+  packetizer->map_offset += i - sync_offset;
+
+  if (!found)
+    wfd_ts_packetizer_flush_bytes (packetizer, packetizer->map_offset);
+
+  return found;
+}
+
+WFDTSPacketizerPacketReturn
+wfd_ts_packetizer_next_packet (WFDTSPacketizer * packetizer,
+    WFDTSPacketizerPacket * packet)
+{
+  guint8 *packet_data;
+  guint packet_size;
+  gsize sync_offset;
+
+  packet_size = packetizer->packet_size;
+  if (G_UNLIKELY (!packet_size)) {
+    if (!wfd_ts_try_discover_packet_size (packetizer))
+      return PACKET_NEED_MORE;
+    packet_size = packetizer->packet_size;
+  }
+
+  /* M2TS packets don't start with the sync byte, all other variants do */
+  if (packet_size == WFD_TS_M2TS_PACKETSIZE)
+    sync_offset = 4;
+  else
+    sync_offset = 0;
+
+  while (1) {
+    if (packetizer->need_sync) {
+      if (!wfd_ts_packetizer_sync (packetizer))
+        return PACKET_NEED_MORE;
+      packetizer->need_sync = FALSE;
+    }
+
+    if (!wfd_ts_packetizer_map (packetizer, packet_size))
+      return PACKET_NEED_MORE;
+
+    packet_data = &packetizer->map_data[packetizer->map_offset + sync_offset];
+
+    /* Check sync byte */
+    if (G_UNLIKELY (*packet_data != PACKET_SYNC_BYTE)) {
+      GST_DEBUG ("lost sync");
+      packetizer->need_sync = TRUE;
+    } else {
+      /* ALL mpeg-ts variants contain 188 bytes of data. Those with bigger
+       * packet sizes contain either extra data (timesync, FEC, ..) either
+       * before or after the data */
+      packet->data_start = packet_data;
+      packet->data_end = packet->data_start + 188;
+      packet->offset = packetizer->offset;
+      GST_LOG ("offset %" G_GUINT64_FORMAT, packet->offset);
+      packetizer->offset += packet_size;
+      GST_MEMDUMP ("data_start", packet->data_start, 16);
+
+      return wfd_ts_packetizer_parse_packet (packetizer, packet);
+    }
+  }
+}
+
+WFDTSPacketizerPacketReturn
+wfd_ts_packetizer_process_next_packet (WFDTSPacketizer * packetizer)
+{
+  WFDTSPacketizerPacket packet;
+  WFDTSPacketizerPacketReturn ret;
+
+  ret = wfd_ts_packetizer_next_packet (packetizer, &packet);
+  if (ret != PACKET_NEED_MORE)
+    wfd_ts_packetizer_clear_packet (packetizer, &packet);
+
+  return ret;
+}
+
+void
+wfd_ts_packetizer_clear_packet (WFDTSPacketizer * packetizer,
+    WFDTSPacketizerPacket * packet)
+{
+  guint8 packet_size = packetizer->packet_size;
+
+  if (packetizer->map_data) {
+    packetizer->map_offset += packet_size;
+    if (packetizer->map_size - packetizer->map_offset < packet_size)
+      wfd_ts_packetizer_flush_bytes (packetizer, packetizer->map_offset);
+  }
+}
+
+gboolean
+wfd_ts_packetizer_has_packets (WFDTSPacketizer * packetizer)
+{
+  if (G_UNLIKELY (!packetizer->packet_size)) {
+    if (!wfd_ts_try_discover_packet_size (packetizer))
+      return FALSE;
+  }
+  return gst_adapter_available (packetizer->adapter) >= packetizer->packet_size;
+}
+
+/*
+ * Ideally it should just return a section if:
+ * * The section is complete
+ * * The section is valid (sanity checks for length for example)
+ * * The section applies now (current_next_indicator)
+ * * The section is an update or was never seen
+ *
+ * The section should be a new GstWFDTSSection:
+ * * properly initialized
+ * * With pid, table_id AND section_type set (move logic from mpegtsbase)
+ * * With data copied into it (yes, minor overhead)
+ *
+ * In all other cases it should just return NULL
+ *
+ * If more than one section is available, the 'remaining' field will
+ * be set to the beginning of a valid GList containing other sections.
+ * */
+GstWFDTSSection *
+wfd_ts_packetizer_push_section (WFDTSPacketizer * packetizer,
+    WFDTSPacketizerPacket * packet, GList ** remaining)
+{
+  GstWFDTSSection *section;
+  GstWFDTSSection *res = NULL;
+  WFDTSPacketizerStream *stream;
+  gboolean long_packet;
+  guint8 pointer = 0, table_id;
+  guint16 subtable_extension = 0;
+  gsize to_read;
+  guint section_length;
+  /* data points to the current read location
+   * data_start points to the beginning of the data to accumulate */
+  guint8 *data, *data_start;
+  guint8 packet_cc;
+  GList *others = NULL;
+  guint8 version_number, section_number, last_section_number;
+
+  data = packet->data;
+  packet_cc = FLAGS_CONTINUITY_COUNTER (packet->scram_afc_cc);
+
+  /* Get our filter */
+  stream = packetizer->streams[packet->pid];
+  if (G_UNLIKELY (stream == NULL)) {
+    if (!packet->payload_unit_start_indicator) {
+      /* Early exit (we need to start with a section start) */
+      GST_DEBUG ("PID 0x%04x  waiting for section start", packet->pid);
+      goto out;
+    }
+    stream = wfd_ts_packetizer_stream_new (packet->pid);
+    packetizer->streams[packet->pid] = stream;
+  }
+
+  GST_MEMDUMP ("Full packet data", packet->data,
+      packet->data_end - packet->data);
+
+  /* This function is split into several parts:
+   *
+   * Pre checks (packet-wide). Determines where we go next
+   * accumulate_data: store data and check if section is complete
+   * section_start: handle beginning of a section, if needed loop back to
+   *                accumulate_data
+   *
+   * The trigger that makes the loop stop and return is if:
+   * 1) We do not have enough data for the current packet
+   * 2) There is remaining data after a packet which is only made
+   *    of stuffing bytes (0xff).
+   *
+   * Pre-loop checks, related to the whole incoming packet:
+   *
+   * If there is a CC-discont:
+   *  If it is a PUSI, skip the pointer and handle section_start
+   *  If not a PUSI, reset and return nothing
+   * If there is not a CC-discont:
+   *  If it is a PUSI
+   *    If pointer, accumulate that data and check for complete section
+   *    (loop)
+   *  If it is not a PUSI
+   *    Accumulate the expected data and check for complete section
+   *    (loop)
+   *
+   **/
+
+  if (packet->payload_unit_start_indicator) {
+    pointer = *data++;
+    /* If the pointer is zero, we're guaranteed to be able to handle it */
+    if (pointer == 0) {
+      GST_LOG
+          ("PID 0x%04x PUSI and pointer == 0, skipping straight to section_start parsing",
+          packet->pid);
+      goto section_start;
+    }
+  }
+
+  if (stream->continuity_counter == CONTINUITY_UNSET ||
+      (stream->continuity_counter + 1) % 16 != packet_cc) {
+    if (stream->continuity_counter != CONTINUITY_UNSET)
+      GST_WARNING ("PID 0x%04x section discontinuity (%d vs %d)", packet->pid,
+          stream->continuity_counter, packet_cc);
+    wfd_ts_packetizer_clear_section (stream);
+    /* If not a PUSI, not much we can do */
+    if (!packet->payload_unit_start_indicator) {
+      GST_LOG ("PID 0x%04x continuity discont/unset and not PUSI, bailing out",
+          packet->pid);
+      goto out;
+    }
+    /* If PUSI, skip pointer data and carry on to section start */
+    data += pointer;
+    pointer = 0;
+    GST_LOG ("discont, but PUSI, skipped %d bytes and doing section start",
+        pointer);
+    goto section_start;
+  }
+
+  GST_LOG ("Accumulating data from beginning of packet");
+
+  data_start = data;
+
+accumulate_data:
+  /* If not the beginning of a new section, accumulate what we have */
+  stream->continuity_counter = packet_cc;
+  to_read = MIN (stream->section_length - stream->section_offset,
+      packet->data_end - data_start);
+  memcpy (stream->section_data + stream->section_offset, data_start, to_read);
+  stream->section_offset += to_read;
+  /* Point data to after the data we accumulated */
+  data = data_start + to_read;
+  GST_DEBUG ("Appending data (need %d, have %d)", stream->section_length,
+      stream->section_offset);
+
+  /* Check if we have enough */
+  if (stream->section_offset < stream->section_length) {
+    GST_DEBUG ("PID 0x%04x, section not complete (Got %d, need %d)",
+        stream->pid, stream->section_offset, stream->section_length);
+    goto out;
+  }
+
+  /* Small sanity check. We should have collected *exactly* the right amount */
+  if (G_UNLIKELY (stream->section_offset != stream->section_length))
+    GST_WARNING ("PID 0x%04x Accumulated too much data (%d vs %d) !",
+        stream->pid, stream->section_offset, stream->section_length);
+  GST_DEBUG ("PID 0x%04x Section complete", stream->pid);
+
+  if ((section = wfd_ts_packetizer_parse_section_header (packetizer, stream))) {
+    if (res)
+      others = g_list_append (others, section);
+    else
+      res = section;
+  }
+
+  /* FIXME : We need at least 8 bytes with current algorithm :(
+   * We might end up losing sections that start across two packets (srsl...) */
+  if (data > packet->data_end - 8 || *data == 0xff) {
+    /* flush stuffing bytes and leave */
+    wfd_ts_packetizer_clear_section (stream);
+    goto out;
+  }
+
+  /* We have more data to process ... */
+  GST_DEBUG ("PID 0x%04x, More section present in packet (remaining bytes:%"
+      G_GSIZE_FORMAT ")", stream->pid, packet->data_end - data);
+
+section_start:
+  GST_MEMDUMP ("section_start", data, packet->data_end - data);
+  data_start = data;
+  /* Beginning of a new section */
+  /*
+   * section_syntax_indicator means that the header is of the following format:
+   * * table_id (8bit)
+   * * section_syntax_indicator (1bit) == 0
+   * * reserved/private fields (3bit)
+   * * section_length (12bit)
+   * * data (of size section_length)
+   * * NO CRC !
+   */
+  long_packet = data[1] & 0x80;
+
+  /* Fast path for short packets */
+  if (!long_packet) {
+    /* We can create the section now (function will check for size) */
+    GST_DEBUG ("Short packet");
+    section_length = (GST_READ_UINT16_BE (data + 1) & 0xfff) + 3;
+    /* Only do fast-path if we have enough byte */
+    if (section_length < packet->data_end - data) {
+      if ((section =
+              gst_wfd_ts_section_new (packet->pid, g_memdup (data,
+                      section_length), section_length))) {
+        GST_DEBUG ("PID 0x%04x Short section complete !", packet->pid);
+        section->offset = packet->offset;
+        if (res)
+          others = g_list_append (others, section);
+        else
+          res = section;
+      }
+      /* Advance reader and potentially read another section */
+      data += section_length;
+      if (data < packet->data_end && *data != 0xff)
+        goto section_start;
+      /* If not, exit */
+      goto out;
+    }
+    /* We don't have enough bytes to do short section shortcut */
+  }
+
+  /* Beginning of a new section, do as much pre-parsing as possible */
+  /* table_id                        : 8  bit */
+  table_id = *data++;
+
+  /* section_syntax_indicator        : 1  bit
+   * other_fields (reserved)         : 3  bit
+   * section_length                  : 12 bit */
+  section_length = (GST_READ_UINT16_BE (data) & 0x0FFF) + 3;
+  data += 2;
+
+  if (long_packet) {
+    /* subtable_extension (always present, we are in a long section) */
+    /* subtable extension              : 16 bit */
+    subtable_extension = GST_READ_UINT16_BE (data);
+    data += 2;
+
+    /* reserved                      : 2  bit
+     * version_number                : 5  bit
+     * current_next_indicator        : 1  bit */
+    /* Bail out now if current_next_indicator == 0 */
+    if (G_UNLIKELY (!(*data & 0x01))) {
+      GST_DEBUG
+          ("PID 0x%04x table_id 0x%02x section does not apply (current_next_indicator == 0)",
+          packet->pid, table_id);
+      goto out;
+    }
+
+    version_number = *data++ >> 1 & 0x1f;
+    /* section_number                : 8  bit */
+    section_number = *data++;
+    /* last_section_number                : 8  bit */
+    last_section_number = *data++;
+  } else {
+    subtable_extension = 0;
+    version_number = 0;
+    section_number = 0;
+    last_section_number = 0;
+  }
+  GST_DEBUG
+      ("PID 0x%04x length:%d table_id:0x%02x subtable_extension:0x%04x version_number:%d section_number:%d(last:%d)",
+      packet->pid, section_length, table_id, subtable_extension, version_number,
+      section_number, last_section_number);
+
+  to_read = MIN (section_length, packet->data_end - data_start);
+
+  /* Check as early as possible whether we already saw this section
+   * i.e. that we saw a subtable with:
+   * * same subtable_extension (might be zero)
+   * * same version_number
+   * * same last_section_number
+   * * same section_number was seen
+   */
+  if (seen_section_before (stream, table_id, subtable_extension,
+          version_number, section_number, last_section_number)) {
+    GST_DEBUG
+        ("PID 0x%04x Already processed table_id:0x%02x subtable_extension:0x%04x, version_number:%d, section_number:%d",
+        packet->pid, table_id, subtable_extension, version_number,
+        section_number);
+    /* skip data and see if we have more sections after */
+    data = data_start + to_read;
+    if (data == packet->data_end || *data == 0xff)
+      goto out;
+    goto section_start;
+  }
+  if (G_UNLIKELY (section_number > last_section_number)) {
+    GST_WARNING
+        ("PID 0x%04x corrupted packet (section_number:%d > last_section_number:%d)",
+        packet->pid, section_number, last_section_number);
+    goto out;
+  }
+
+
+  /* Copy over already parsed values */
+  stream->table_id = table_id;
+  stream->section_length = section_length;
+  stream->version_number = version_number;
+  stream->subtable_extension = subtable_extension;
+  stream->section_number = section_number;
+  stream->last_section_number = last_section_number;
+  stream->offset = packet->offset;
+
+  /* Create enough room to store chunks of sections */
+  stream->section_data = g_malloc (stream->section_length);
+  stream->section_offset = 0;
+
+  /* Finally, accumulate and check if we parsed enough */
+  goto accumulate_data;
+
+out:
+  packet->data = data;
+  *remaining = others;
+
+  GST_DEBUG ("result: %p", res);
+
+  return res;
+}
+
+static void
+_init_local (void)
+{
+  GST_DEBUG_CATEGORY_INIT (wfd_ts_packetizer_debug, "mpegtspacketizer", 0,
+      "MPEG transport stream parser");
+}
+
+
+static void
+wfd_ts_packetizer_resync (WFDTSPCR * pcr, GstClockTime time,
+    GstClockTime gstpcrtime, gboolean reset_skew)
+{
+  pcr->base_time = time;
+  pcr->base_pcrtime = gstpcrtime;
+  pcr->prev_out_time = GST_CLOCK_TIME_NONE;
+  pcr->prev_send_diff = GST_CLOCK_TIME_NONE;
+  if (reset_skew) {
+    pcr->window_filling = TRUE;
+    pcr->window_pos = 0;
+    pcr->window_min = 0;
+    pcr->window_size = 0;
+    pcr->skew = 0;
+  }
+}
+
+
+/* Code mostly copied from -good/gst/rtpmanager/rtpjitterbuffer.c */
+
+/* For the clock skew we use a windowed low point averaging algorithm as can be
+ * found in Fober, Orlarey and Letz, 2005, "Real Time Clock Skew Estimation
+ * over Network Delays":
+ * http://www.grame.fr/Ressources/pub/TR-050601.pdf
+ * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.102.1546
+ *
+ * The idea is that the jitter is composed of:
+ *
+ *  J = N + n
+ *
+ *   D   : a constant network delay.
+ *   n   : random added noise. The noise is concentrated around 0
+ *
+ * In the receiver we can track the elapsed time at the sender with:
+ *
+ *  send_diff(i) = (Tsi - Ts0);
+ *
+ *   Tsi : The time at the sender at packet i
+ *   Ts0 : The time at the sender at the first packet
+ *
+ * This is the difference between the RTP timestamp in the first received packet
+ * and the current packet.
+ *
+ * At the receiver we have to deal with the jitter introduced by the network.
+ *
+ *  recv_diff(i) = (Tri - Tr0)
+ *
+ *   Tri : The time at the receiver at packet i
+ *   Tr0 : The time at the receiver at the first packet
+ *
+ * Both of these values contain a jitter Ji, a jitter for packet i, so we can
+ * write:
+ *
+ *  recv_diff(i) = (Cri + D + ni) - (Cr0 + D + n0))
+ *
+ *    Cri    : The time of the clock at the receiver for packet i
+ *    D + ni : The jitter when receiving packet i
+ *
+ * We see that the network delay is irrelevant here as we can elliminate D:
+ *
+ *  recv_diff(i) = (Cri + ni) - (Cr0 + n0))
+ *
+ * The drift is now expressed as:
+ *
+ *  Drift(i) = recv_diff(i) - send_diff(i);
+ *
+ * We now keep the W latest values of Drift and find the minimum (this is the
+ * one with the lowest network jitter and thus the one which is least affected
+ * by it). We average this lowest value to smooth out the resulting network skew.
+ *
+ * Both the window and the weighting used for averaging influence the accuracy
+ * of the drift estimation. Finding the correct parameters turns out to be a
+ * compromise between accuracy and inertia.
+ *
+ * We use a 2 second window or up to 512 data points, which is statistically big
+ * enough to catch spikes (FIXME, detect spikes).
+ * We also use a rather large weighting factor (125) to smoothly adapt. During
+ * startup, when filling the window, we use a parabolic weighting factor, the
+ * more the window is filled, the faster we move to the detected possible skew.
+ *
+ * Returns: @time adjusted with the clock skew.
+ */
+static GstClockTime
+calculate_skew (WFDTSPCR * pcr, guint64 pcrtime, GstClockTime time)
+{
+  guint64 send_diff, recv_diff;
+  gint64 delta;
+  gint64 old;
+  gint pos, i;
+  GstClockTime gstpcrtime, out_time;
+#ifndef GST_DISABLE_GST_DEBUG
+  guint64 slope;
+#endif
+
+  gstpcrtime = PCRTIME_TO_GSTTIME (pcrtime) + pcr->pcroffset;
+
+  /* first time, lock on to time and gstpcrtime */
+  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (pcr->base_time))) {
+    pcr->base_time = time;
+    pcr->prev_out_time = GST_CLOCK_TIME_NONE;
+    GST_DEBUG ("Taking new base time %" GST_TIME_FORMAT, GST_TIME_ARGS (time));
+  }
+
+  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (pcr->base_pcrtime))) {
+    pcr->base_pcrtime = gstpcrtime;
+    pcr->prev_send_diff = -1;
+    GST_DEBUG ("Taking new base pcrtime %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (gstpcrtime));
+  }
+
+  /* Handle PCR wraparound and resets */
+  if (GST_CLOCK_TIME_IS_VALID (pcr->last_pcrtime) &&
+      gstpcrtime < pcr->last_pcrtime) {
+    if (pcr->last_pcrtime - gstpcrtime > PCR_GST_MAX_VALUE / 2) {
+      /* PCR wraparound */
+      GST_DEBUG ("PCR wrap");
+      pcr->pcroffset += PCR_GST_MAX_VALUE;
+      gstpcrtime = PCRTIME_TO_GSTTIME (pcrtime) + pcr->pcroffset;
+      send_diff = gstpcrtime - pcr->base_pcrtime;
+    } else if (GST_CLOCK_TIME_IS_VALID (time)
+        && pcr->last_pcrtime - gstpcrtime > 15 * GST_SECOND) {
+      /* Assume a reset */
+      GST_DEBUG ("PCR reset");
+      /* Calculate PCR we would have expected for the given input time,
+       * essentially applying the reverse correction process
+       *
+       * We want to find the PCR offset to apply
+       *   pcroffset = (corrected) gstpcrtime - (received) gstpcrtime
+       *
+       * send_diff = (corrected) gstpcrtime - pcr->base_pcrtime
+       * recv_diff = time - pcr->base_time
+       * out_time = pcr->base_time + send_diff
+       *
+       * We are assuming that send_diff == recv_diff
+       *   (corrected) gstpcrtime - pcr->base_pcrtime = time - pcr->base_time
+       * Giving us:
+       *   (corrected) gstpcrtime = time - pcr->base_time + pcr->base_pcrtime
+       *
+       * And therefore:
+       *   pcroffset = time - pcr->base_time + pcr->base_pcrtime - (received) gstpcrtime
+       **/
+      pcr->pcroffset += time - pcr->base_time + pcr->base_pcrtime - gstpcrtime;
+      gstpcrtime = PCRTIME_TO_GSTTIME (pcrtime) + pcr->pcroffset;
+      send_diff = gstpcrtime - pcr->base_pcrtime;
+      GST_DEBUG ("Introduced offset is now %" GST_TIME_FORMAT
+          " corrected pcr time %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (pcr->pcroffset), GST_TIME_ARGS (gstpcrtime));
+    } else {
+      GST_WARNING ("backward timestamps at server but no timestamps");
+      send_diff = 0;
+      /* at least try to get a new timestamp.. */
+      pcr->base_time = GST_CLOCK_TIME_NONE;
+    }
+  } else
+    send_diff = gstpcrtime - pcr->base_pcrtime;
+
+  GST_DEBUG ("gstpcr %" GST_TIME_FORMAT ", buftime %" GST_TIME_FORMAT
+      ", base %" GST_TIME_FORMAT ", send_diff %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (gstpcrtime), GST_TIME_ARGS (time),
+      GST_TIME_ARGS (pcr->base_pcrtime), GST_TIME_ARGS (send_diff));
+
+  /* keep track of the last extended pcrtime */
+  pcr->last_pcrtime = gstpcrtime;
+
+  /* we don't have an arrival timestamp so we can't do skew detection. we
+   * should still apply a timestamp based on RTP timestamp and base_time */
+  if (!GST_CLOCK_TIME_IS_VALID (time)
+      || !GST_CLOCK_TIME_IS_VALID (pcr->base_time))
+    goto no_skew;
+
+  /* elapsed time at receiver, includes the jitter */
+  recv_diff = time - pcr->base_time;
+
+  /* Ignore packets received at 100% the same time (i.e. from the same input buffer) */
+  if (G_UNLIKELY (time == pcr->prev_in_time
+          && GST_CLOCK_TIME_IS_VALID (pcr->prev_in_time)))
+    goto no_skew;
+
+  /* measure the diff */
+  delta = ((gint64) recv_diff) - ((gint64) send_diff);
+
+#ifndef GST_DISABLE_GST_DEBUG
+  /* measure the slope, this gives a rought estimate between the sender speed
+   * and the receiver speed. This should be approximately 8, higher values
+   * indicate a burst (especially when the connection starts) */
+  slope = recv_diff > 0 ? (send_diff * 8) / recv_diff : 8;
+#endif
+
+  GST_DEBUG ("time %" GST_TIME_FORMAT ", base %" GST_TIME_FORMAT
+      ", recv_diff %" GST_TIME_FORMAT ", slope %" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (time), GST_TIME_ARGS (pcr->base_time),
+      GST_TIME_ARGS (recv_diff), slope);
+
+  /* if the difference between the sender timeline and the receiver timeline
+   * changed too quickly we have to resync because the server likely restarted
+   * its timestamps. */
+  if (ABS (delta - pcr->skew) > GST_SECOND) {
+    GST_WARNING ("delta - skew: %" GST_TIME_FORMAT " too big, reset skew",
+        GST_TIME_ARGS (delta - pcr->skew));
+    wfd_ts_packetizer_resync (pcr, time, gstpcrtime, TRUE);
+    send_diff = 0;
+    delta = 0;
+  }
+
+  pos = pcr->window_pos;
+
+  if (G_UNLIKELY (pcr->window_filling)) {
+    /* we are filling the window */
+    GST_DEBUG ("filling %d, delta %" G_GINT64_FORMAT, pos, delta);
+    pcr->window[pos++] = delta;
+    /* calc the min delta we observed */
+    if (G_UNLIKELY (pos == 1 || delta < pcr->window_min))
+      pcr->window_min = delta;
+
+    if (G_UNLIKELY (send_diff >= MAX_TIME || pos >= MAX_WINDOW)) {
+      pcr->window_size = pos;
+
+      /* window filled */
+      GST_DEBUG ("min %" G_GINT64_FORMAT, pcr->window_min);
+
+      /* the skew is now the min */
+      pcr->skew = pcr->window_min;
+      pcr->window_filling = FALSE;
+    } else {
+      gint perc_time, perc_window, perc;
+
+      /* figure out how much we filled the window, this depends on the amount of
+       * time we have or the max number of points we keep. */
+      perc_time = send_diff * 100 / MAX_TIME;
+      perc_window = pos * 100 / MAX_WINDOW;
+      perc = MAX (perc_time, perc_window);
+
+      /* make a parabolic function, the closer we get to the MAX, the more value
+       * we give to the scaling factor of the new value */
+      perc = perc * perc;
+
+      /* quickly go to the min value when we are filling up, slowly when we are
+       * just starting because we're not sure it's a good value yet. */
+      pcr->skew =
+          (perc * pcr->window_min + ((10000 - perc) * pcr->skew)) / 10000;
+      pcr->window_size = pos + 1;
+    }
+  } else {
+    /* pick old value and store new value. We keep the previous value in order
+     * to quickly check if the min of the window changed */
+    old = pcr->window[pos];
+    pcr->window[pos++] = delta;
+
+    if (G_UNLIKELY (delta <= pcr->window_min)) {
+      /* if the new value we inserted is smaller or equal to the current min,
+       * it becomes the new min */
+      pcr->window_min = delta;
+    } else if (G_UNLIKELY (old == pcr->window_min)) {
+      gint64 min = G_MAXINT64;
+
+      /* if we removed the old min, we have to find a new min */
+      for (i = 0; i < pcr->window_size; i++) {
+        /* we found another value equal to the old min, we can stop searching now */
+        if (pcr->window[i] == old) {
+          min = old;
+          break;
+        }
+        if (pcr->window[i] < min)
+          min = pcr->window[i];
+      }
+      pcr->window_min = min;
+    }
+    /* average the min values */
+    pcr->skew = (pcr->window_min + (124 * pcr->skew)) / 125;
+    GST_DEBUG ("delta %" G_GINT64_FORMAT ", new min: %" G_GINT64_FORMAT,
+        delta, pcr->window_min);
+  }
+  /* wrap around in the window */
+  if (G_UNLIKELY (pos >= pcr->window_size))
+    pos = 0;
+
+  pcr->window_pos = pos;
+
+no_skew:
+  /* the output time is defined as the base timestamp plus the PCR time
+   * adjusted for the clock skew .*/
+  if (pcr->base_time != -1) {
+    out_time = pcr->base_time + send_diff;
+    /* skew can be negative and we don't want to make invalid timestamps */
+    if (pcr->skew < 0 && out_time < -pcr->skew) {
+      out_time = 0;
+    } else {
+      out_time += pcr->skew;
+    }
+    /* check if timestamps are not going backwards, we can only check this if we
+     * have a previous out time and a previous send_diff */
+    if (G_LIKELY (pcr->prev_out_time != -1 && pcr->prev_send_diff != -1)) {
+      /* now check for backwards timestamps */
+      if (G_UNLIKELY (
+              /* if the server timestamps went up and the out_time backwards */
+              (send_diff > pcr->prev_send_diff
+                  && out_time < pcr->prev_out_time) ||
+              /* if the server timestamps went backwards and the out_time forwards */
+              (send_diff < pcr->prev_send_diff
+                  && out_time > pcr->prev_out_time) ||
+              /* if the server timestamps did not change */
+              send_diff == pcr->prev_send_diff)) {
+        GST_DEBUG ("backwards timestamps, using previous time");
+        out_time = GSTTIME_TO_MPEGTIME (out_time);
+      }
+    }
+  } else {
+    /* We simply use the pcrtime without applying any skew compensation */
+    out_time = time;
+  }
+
+  pcr->prev_out_time = out_time;
+  pcr->prev_in_time = time;
+  pcr->prev_send_diff = send_diff;
+
+  GST_DEBUG ("skew %" G_GINT64_FORMAT ", out %" GST_TIME_FORMAT,
+      pcr->skew, GST_TIME_ARGS (out_time));
+
+  return out_time;
+}
+
+static void
+_reevaluate_group_pcr_offset (WFDTSPCR * pcrtable, PCROffsetGroup * group)
+{
+  PCROffsetGroup *prev = NULL;
+#ifndef GST_DISABLE_GST_DEBUG
+  PCROffsetGroup *first = pcrtable->groups->data;
+#endif
+  PCROffsetCurrent *current = pcrtable->current;
+  GList *tmp;
+
+  /* Go over all ESTIMATED groups until the target group */
+  for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
+    PCROffsetGroup *cur = (PCROffsetGroup *) tmp->data;
+
+    /* Skip groups that don't need re-evaluation */
+    if (!(cur->flags & PCR_GROUP_FLAG_ESTIMATED)) {
+      GST_DEBUG ("Skipping group %p pcr_offset (currently %" GST_TIME_FORMAT
+          ")", cur, GST_TIME_ARGS (PCRTIME_TO_GSTTIME (cur->pcr_offset)));
+      prev = cur;
+      continue;
+    }
+
+    /* This should not happen ! The first group is *always* correct (zero) */
+    if (G_UNLIKELY (prev == NULL)) {
+      GST_ERROR ("First PCR Group was not estimated (bug). Setting to zero");
+      cur->pcr_offset = 0;
+      cur->flags &= ~PCR_GROUP_FLAG_ESTIMATED;
+      return;
+    }
+
+    /* Finally do the estimation of this group's PCR offset based on the
+     * previous group information */
+
+    GST_DEBUG ("Re-evaluating group %p pcr_offset (currently %" GST_TIME_FORMAT
+        ")", group, GST_TIME_ARGS (PCRTIME_TO_GSTTIME (cur->pcr_offset)));
+
+    GST_DEBUG ("cur->first_pcr:%" GST_TIME_FORMAT " prev->first_pcr:%"
+        GST_TIME_FORMAT, GST_TIME_ARGS (PCRTIME_TO_GSTTIME (cur->first_pcr)),
+        GST_TIME_ARGS (PCRTIME_TO_GSTTIME (prev->first_pcr)));
+
+    if (G_UNLIKELY (cur->first_pcr < prev->first_pcr)) {
+      guint64 prevbr, lastbr;
+      guint64 prevpcr;
+      guint64 prevoffset, lastoffset;
+
+      /* Take the previous group pcr_offset and figure out how much to add
+       * to it for the current group */
+
+      /* Right now we do a dumb bitrate estimation
+       * estimate bitrate (prev - first) : bitrate from the start
+       * estimate bitrate (prev) : bitrate of previous group
+       * estimate bitrate (last - first) : bitrate from previous group
+       *
+       * We will use raw (non-corrected/non-absolute) PCR values in a first time
+       * to detect wraparound/resets/gaps...
+       *
+       * We will use the corrected/asolute PCR values to calculate
+       * bitrate and estimate the target group pcr_offset.
+       * */
+
+      /* If the current window estimator is over the previous group, used those
+       * values as the latest (since they are more recent) */
+      if (current->group == prev && current->pending[current->last].offset) {
+        prevoffset =
+            current->pending[current->last].offset + prev->first_offset;
+        prevpcr = current->pending[current->last].pcr + prev->first_pcr;
+        /* prevbr: bitrate(prev) */
+        prevbr =
+            gst_util_uint64_scale (PCR_SECOND,
+            current->pending[current->last].offset,
+            current->pending[current->last].pcr);
+        GST_DEBUG ("Previous group bitrate (%" G_GUINT64_FORMAT " / %"
+            GST_TIME_FORMAT ") : %" G_GUINT64_FORMAT,
+            current->pending[current->last].offset,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (current->pending[current->
+                        last].pcr)), prevbr);
+      } else if (prev->values[prev->last_value].offset) {
+        prevoffset = prev->values[prev->last_value].offset + prev->first_offset;
+        prevpcr = prev->values[prev->last_value].pcr + prev->first_pcr;
+        /* prevbr: bitrate(prev) (FIXME : Cache) */
+        prevbr =
+            gst_util_uint64_scale (PCR_SECOND,
+            prev->values[prev->last_value].offset,
+            prev->values[prev->last_value].pcr);
+        GST_DEBUG ("Previous group bitrate (%" G_GUINT64_FORMAT " / %"
+            GST_TIME_FORMAT ") : %" G_GUINT64_FORMAT,
+            prev->values[prev->last_value].offset,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (prev->values[prev->
+                        last_value].pcr)), prevbr);
+      } else {
+        GST_DEBUG ("Using overall bitrate");
+        prevoffset = prev->values[prev->last_value].offset + prev->first_offset;
+        prevpcr = prev->values[prev->last_value].pcr + prev->first_pcr;
+        prevbr = gst_util_uint64_scale (PCR_SECOND,
+            prev->first_offset, prev->pcr_offset);
+      }
+      lastoffset = cur->values[cur->last_value].offset + cur->first_offset;
+
+      GST_DEBUG ("Offset first:%" G_GUINT64_FORMAT " prev:%" G_GUINT64_FORMAT
+          " cur:%" G_GUINT64_FORMAT, first->first_offset, prevoffset,
+          lastoffset);
+      GST_DEBUG ("PCR first:%" GST_TIME_FORMAT " prev:%" GST_TIME_FORMAT
+          " cur:%" GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (first->first_pcr)),
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (prevpcr)),
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (cur->values[cur->last_value].pcr +
+                  cur->first_pcr)));
+
+      if (prevpcr - cur->first_pcr > (PCR_MAX_VALUE * 9 / 10)) {
+        gfloat diffprev;
+        guint64 guess_offset;
+
+        /* Let's assume there is a PCR wraparound between the previous and current
+         * group.
+         * [ prev ]... PCR_MAX | 0 ...[ current ]
+         * The estimated pcr_offset would therefore be:
+         * current.first + (PCR_MAX_VALUE - prev.first)
+         *
+         * 1) Check if bitrate(prev) would be consistent with bitrate (cur - prev)
+         */
+        guess_offset = PCR_MAX_VALUE - prev->first_pcr + cur->first_pcr;
+        lastbr = gst_util_uint64_scale (PCR_SECOND, lastoffset - prevoffset,
+            guess_offset + cur->values[cur->last_value].pcr - (prevpcr -
+                prev->first_pcr));
+        GST_DEBUG ("Wraparound prev-cur (guess_offset:%" GST_TIME_FORMAT
+            ") bitrate:%" G_GUINT64_FORMAT,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (guess_offset)), lastbr);
+        if(prevbr == 0) {
+          GST_ERROR ("Division by zero error, prevbr is 0");
+          continue;
+        }
+        diffprev = (float) 100.0 *(ABSDIFF (prevbr, lastbr)) / (float) prevbr;
+        GST_DEBUG ("Difference with previous bitrate:%f", diffprev);
+        if (diffprev < 10.0) {
+          GST_DEBUG ("Difference < 10.0, Setting pcr_offset to %"
+              G_GUINT64_FORMAT, guess_offset);
+          cur->pcr_offset = guess_offset;
+          if (diffprev < 1.0) {
+            GST_DEBUG ("Difference < 1.0, Removing ESTIMATED flags");
+            cur->flags &= ~PCR_GROUP_FLAG_ESTIMATED;
+          }
+        }
+        /* Indicate the the previous group is before a wrapover */
+        prev->flags |= PCR_GROUP_FLAG_WRAPOVER;
+      } else {
+        guint64 resetprev;
+        /* Let's assume there was a PCR reset between the previous and current
+         * group
+         * [ prev ] ... x | x - reset ... [ current ]
+         *
+         * The estimated pcr_offset would then be
+         * = current.first - (x - reset) + (x - prev.first) + 100ms (for safety)
+         * = current.first + reset - prev.first + 100ms (for safety)
+         */
+        /* In order to calculate the reset, we estimate what the PCR would have
+         * been by using prevbr */
+        /* FIXME : Which bitrate should we use ???  */
+        GST_DEBUG ("Using prevbr:%" G_GUINT64_FORMAT " and taking offsetdiff:%"
+            G_GUINT64_FORMAT, prevbr, cur->first_offset - prev->first_offset);
+        resetprev =
+            gst_util_uint64_scale (PCR_SECOND,
+            cur->first_offset - prev->first_offset, prevbr);
+        GST_DEBUG ("Estimated full PCR for offset %" G_GUINT64_FORMAT
+            ", using prevbr:%"
+            GST_TIME_FORMAT, cur->first_offset,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (resetprev)));
+        cur->pcr_offset = prev->pcr_offset + resetprev + 100 * PCR_MSECOND;
+        GST_DEBUG ("Adjusted group PCR_offset to %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (cur->pcr_offset)));
+        /* Indicate the the previous group is before a reset */
+        prev->flags |= PCR_GROUP_FLAG_RESET;
+      }
+    } else {
+      /* FIXME : Detect gaps if bitrate difference is really too big ? */
+      cur->pcr_offset = prev->pcr_offset + cur->first_pcr - prev->first_pcr;
+      GST_DEBUG ("Assuming there is no gap, setting pcr_offset to %"
+          GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (cur->pcr_offset)));
+      /* Remove the reset and wrapover flag (if it was previously there) */
+      prev->flags &= ~PCR_GROUP_FLAG_RESET;
+      prev->flags &= ~PCR_GROUP_FLAG_WRAPOVER;
+    }
+
+
+    /* Remember prev for the next group evaluation */
+    prev = cur;
+  }
+}
+
+static PCROffsetGroup *
+_new_group (guint64 pcr, guint64 offset, guint64 pcr_offset, guint flags)
+{
+  PCROffsetGroup *group = g_slice_new0 (PCROffsetGroup);
+
+  GST_DEBUG ("Input PCR %" GST_TIME_FORMAT " offset:%" G_GUINT64_FORMAT
+      " pcr_offset:%" G_GUINT64_FORMAT " flags:%d",
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (pcr)), offset, pcr_offset, flags);
+
+  group->flags = flags;
+  group->values = g_new0 (PCROffset, DEFAULT_ALLOCATED_OFFSET);
+  /* The first pcr/offset diff is always 0/0 */
+  group->values[0].pcr = group->values[0].offset = 0;
+  group->nb_allocated = DEFAULT_ALLOCATED_OFFSET;
+
+  /* Store the full values */
+  group->first_pcr = pcr;
+  group->first_offset = offset;
+  group->pcr_offset = pcr_offset;
+
+  GST_DEBUG ("Created group starting with pcr:%" GST_TIME_FORMAT " offset:%"
+      G_GUINT64_FORMAT " pcr_offset:%" GST_TIME_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->first_pcr)),
+      group->first_offset,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->pcr_offset)));
+
+  return group;
+}
+
+static void
+_insert_group_after (WFDTSPCR * pcrtable, PCROffsetGroup * group,
+    PCROffsetGroup * prev)
+{
+  if (prev == NULL) {
+    /* First group */
+    pcrtable->groups = g_list_prepend (pcrtable->groups, group);
+  } else {
+    GList *tmp, *toinsert, *prevlist = NULL, *nextlist = NULL;
+    /* Insert before next and prev */
+    for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
+      if (tmp->data == prev) {
+        prevlist = tmp;
+        nextlist = tmp->next;
+        break;
+      }
+    }
+    if (!prevlist) {
+      /* The non NULL prev given isn't in the list */
+      GST_WARNING ("Request to insert before a group which isn't in the list");
+      pcrtable->groups = g_list_prepend (pcrtable->groups, group);
+    } else {
+      toinsert = g_list_append (NULL, group);
+      toinsert->next = nextlist;
+      toinsert->prev = prevlist;
+      prevlist->next = toinsert;
+      if (nextlist)
+        nextlist->prev = toinsert;
+    }
+  }
+}
+
+static void
+_use_group (WFDTSPCR * pcrtable, PCROffsetGroup * group)
+{
+  PCROffsetCurrent *current = pcrtable->current;
+
+  memset (current, 0, sizeof (PCROffsetCurrent));
+  current->group = group;
+  current->pending[0] = group->values[group->last_value];
+  current->last_value = current->pending[0];
+  current->write = 1;
+  current->prev = group->values[group->last_value];
+  current->first_pcr = group->first_pcr;
+  current->first_offset = group->first_offset;
+}
+
+/* Create a new group with the specified values after prev
+ * Set current to that new group */
+static void
+_set_current_group (WFDTSPCR * pcrtable,
+    PCROffsetGroup * prev, guint64 pcr, guint64 offset, gboolean contiguous)
+{
+  PCROffsetGroup *group;
+  guint flags = 0;
+  guint64 pcr_offset = 0;
+
+  /* Handle wraparound/gap (only if contiguous with previous group) */
+  if (contiguous) {
+    guint64 lastpcr = prev->first_pcr + prev->values[prev->last_value].pcr;
+
+    /* Set CLOSED flag on previous group and remember pcr_offset */
+    prev->flags |= PCR_GROUP_FLAG_CLOSED;
+    pcr_offset = prev->pcr_offset;
+
+    /* Wraparound ? */
+    if (lastpcr > pcr) {
+      /* In offset-mode, a PCR wraparound is only actually consistent if
+       * we have a very high confidence (99% right now, might need to change
+       * later) */
+      if (lastpcr - pcr > (PCR_MAX_VALUE * 99 / 100)) {
+        GST_WARNING ("WRAPAROUND detected. diff %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (lastpcr - pcr)));
+        /* The previous group closed at PCR_MAX_VALUE */
+        pcr_offset += PCR_MAX_VALUE - prev->first_pcr + pcr;
+      } else {
+        GST_WARNING ("RESET detected. diff %" GST_TIME_FORMAT,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (lastpcr - pcr)));
+        /* The previous group closed at the raw last_pcr diff (+100ms for safety) */
+        pcr_offset += prev->values[prev->last_value].pcr + 100 * PCR_MSECOND;
+      }
+    } else if (lastpcr < pcr - 500 * PCR_MSECOND) {
+      GST_WARNING ("GAP detected. diff %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (pcr - lastpcr)));
+      /* The previous group closed at the raw last_pcr diff (+500ms for safety) */
+      pcr_offset += prev->values[prev->last_value].pcr + 500 * PCR_MSECOND;
+    } else
+      /* Normal continuation (contiguous in time) */
+      pcr_offset += pcr - prev->first_pcr;
+
+  } else if (prev != NULL)
+    /* If we are not contiguous and it's not the first group, the pcr_offset
+     * will be estimated */
+    flags = PCR_GROUP_FLAG_ESTIMATED;
+
+  group = _new_group (pcr, offset, pcr_offset, flags);
+  _use_group (pcrtable, group);
+  _insert_group_after (pcrtable, group, prev);
+  if (!contiguous)
+    _reevaluate_group_pcr_offset (pcrtable, group);
+}
+
+static inline void
+_append_group_values (PCROffsetGroup * group, PCROffset pcroffset)
+{
+  group->last_value++;
+  /* Resize values if needed */
+  if (G_UNLIKELY (group->nb_allocated == group->last_value)) {
+    group->nb_allocated += DEFAULT_ALLOCATED_OFFSET;
+    group->values =
+        g_realloc (group->values, group->nb_allocated * sizeof (PCROffset));
+  }
+  group->values[group->last_value] = pcroffset;
+
+  GST_DEBUG ("First PCR:%" GST_TIME_FORMAT " offset:%" G_GUINT64_FORMAT
+      " PCR_offset:%" GST_TIME_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->first_pcr)),
+      group->first_offset,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->pcr_offset)));
+  GST_DEBUG ("Last PCR: +%" GST_TIME_FORMAT " offset: +%" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (pcroffset.pcr)), pcroffset.offset);
+}
+
+/* Move last values from current (if any) to the current group
+ * and reset current.
+ * Note: This does not set the CLOSED flag (since we have no next
+ * contiguous group) */
+static void
+_close_current_group (WFDTSPCR * pcrtable)
+{
+  PCROffsetCurrent *current = pcrtable->current;
+  PCROffsetGroup *group = current->group;
+
+  if (group == NULL)
+    return;
+  GST_DEBUG ("Closing group and resetting current");
+
+  /* Store last values */
+  _append_group_values (group, current->pending[current->last]);
+  memset (current, 0, sizeof (PCROffsetCurrent));
+  /* And re-evaluate all groups */
+}
+
+static void
+record_pcr (WFDTSPacketizer * packetizer, WFDTSPCR * pcrtable,
+    guint64 pcr, guint64 offset)
+{
+  PCROffsetCurrent *current = pcrtable->current;
+  gint64 corpcr, coroffset;
+
+  packetizer->nb_seen_offsets += 1;
+
+  /* FIXME : Invert logic later (probability is higher that we have a
+   * current estimator) */
+
+  /* Check for current */
+  if (G_UNLIKELY (current->group == NULL)) {
+    PCROffsetGroup *prev = NULL;
+    GList *tmp;
+    /* No current estimator. This happens for the initial value, or after
+     * discont and flushes. Figure out where we need to record this position.
+     *
+     * Possible choices:
+     * 1) No groups at all:
+     *    Create a new group with pcr/offset
+     *    Initialize current to that group
+     * 2) Entirely within an existing group
+     *    bail out (FIXME: Make this detection faster)
+     * 3) Not in any group
+     *    Create a new group with pcr/offset at the right position
+     *    Initialize current to that group
+     */
+    GST_DEBUG ("No current window estimator, Checking for group to use");
+    for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
+      PCROffsetGroup *group = (PCROffsetGroup *) tmp->data;
+
+      GST_DEBUG ("First PCR:%" GST_TIME_FORMAT " offset:%" G_GUINT64_FORMAT
+          " PCR_offset:%" GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->first_pcr)),
+          group->first_offset,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->pcr_offset)));
+      GST_DEBUG ("Last PCR: +%" GST_TIME_FORMAT " offset: +%" G_GUINT64_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->values[group->
+                      last_value].pcr)),
+          group->values[group->last_value].offset);
+      /* Check if before group */
+      if (offset < group->first_offset) {
+        GST_DEBUG ("offset is before that group");
+        break;
+      }
+      /* Check if within group */
+      if (offset <=
+          (group->values[group->last_value].offset + group->first_offset)) {
+        GST_DEBUG ("Already observed PCR offset %" G_GUINT64_FORMAT, offset);
+        return;
+      }
+      /* Check if just after group (i.e. continuation of it) */
+      if (!(group->flags & PCR_GROUP_FLAG_CLOSED) &&
+          pcr - group->first_pcr - group->values[group->last_value].pcr <=
+          100 * PCR_MSECOND) {
+        GST_DEBUG ("Continuation of existing group");
+        _use_group (pcrtable, group);
+        return;
+      }
+      /* Else after group */
+      prev = group;
+    }
+    _set_current_group (pcrtable, prev, pcr, offset, FALSE);
+    return;
+  }
+
+  corpcr = pcr - current->first_pcr;
+  coroffset = offset - current->first_offset;
+
+  /* FIXME : Detect if we've gone into the next group !
+   * FIXME : Close group when that happens */
+  GST_DEBUG ("first:%d, last:%d, write:%d", current->first, current->last,
+      current->write);
+  GST_DEBUG ("First PCR:%" GST_TIME_FORMAT " offset:%" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (current->first_pcr)),
+      current->first_offset);
+  GST_DEBUG ("Last PCR: +%" GST_TIME_FORMAT " offset: +%" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (current->pending[current->last].pcr)),
+      current->pending[current->last].offset);
+  GST_DEBUG ("To add (corrected) PCR:%" GST_TIME_FORMAT " offset:%"
+      G_GINT64_FORMAT, GST_TIME_ARGS (PCRTIME_TO_GSTTIME (corpcr)), coroffset);
+
+  /* Do we need to close the current group ? */
+  /* Check for wrapover/discont */
+  if (G_UNLIKELY (corpcr < current->pending[current->last].pcr)) {
+    /* FIXME : ignore very small deltas (< 500ms ?) which are most likely
+     * stray values */
+    GST_DEBUG
+        ("PCR smaller than previously observed one, handling discont/wrapover");
+    /* Take values from current and put them in the current group (closing it) */
+    /* Create new group with new pcr/offset just after the current group
+     * and mark it as a wrapover */
+    /* Initialize current to that group with new values */
+    _append_group_values (current->group, current->pending[current->last]);
+    _set_current_group (pcrtable, current->group, pcr, offset, TRUE);
+    return;
+  }
+  /* If PCR diff is greater than 500ms, create new group */
+  if (G_UNLIKELY (corpcr - current->pending[current->last].pcr >
+          500 * PCR_MSECOND)) {
+    GST_DEBUG ("New PCR more than 500ms away, handling discont");
+    /* Take values from current and put them in the current group (closing it) */
+    /* Create new group with pcr/offset just after the current group
+     * and mark it as a discont */
+    /* Initialize current to that group with new values */
+    _append_group_values (current->group, current->pending[current->last]);
+    _set_current_group (pcrtable, current->group, pcr, offset, TRUE);
+    return;
+  }
+
+  if (G_UNLIKELY (corpcr == current->last_value.pcr)) {
+    GST_DEBUG ("Ignoring same PCR (stream is drunk)");
+    return;
+  }
+
+  /* update current window */
+  current->pending[current->write].pcr = corpcr;
+  current->pending[current->write].offset = coroffset;
+  current->last_value = current->pending[current->write];
+  current->last = (current->last + 1) % PCR_BITRATE_NEEDED;
+  current->write = (current->write + 1) % PCR_BITRATE_NEEDED;
+
+  GST_DEBUG ("first:%d, last:%d, write:%d", current->first, current->last,
+      current->write);
+  GST_DEBUG ("First PCR:%" GST_TIME_FORMAT " offset:%" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (current->first_pcr)),
+      current->first_offset);
+  GST_DEBUG ("Last PCR: +%" GST_TIME_FORMAT " offset: +%" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (current->pending[current->last].pcr)),
+      current->pending[current->last].offset);
+
+  /* If we haven't stored enough values, bail out */
+  if (current->write != current->first) {
+    GST_DEBUG
+        ("Not enough observations to calculate bitrate (first:%d, last:%d)",
+        current->first, current->last);
+    return;
+  }
+
+  /* If we are at least 1s away from reference value AND we have filled our
+   * window, we can start comparing bitrates */
+  if (current->pending[current->first].pcr - current->prev.pcr > PCR_SECOND) {
+    /* Calculate window bitrate */
+    current->cur_bitrate = gst_util_uint64_scale (PCR_SECOND,
+        current->pending[current->last].offset -
+        current->pending[current->first].offset,
+        current->pending[current->last].pcr -
+        current->pending[current->first].pcr);
+    GST_DEBUG ("Current bitrate is now %" G_GUINT64_FORMAT,
+        current->cur_bitrate);
+
+    /* Calculate previous bitrate */
+    current->prev_bitrate =
+        gst_util_uint64_scale (PCR_SECOND,
+        current->pending[current->first].offset - current->prev.offset,
+        current->pending[current->first].pcr - current->prev.pcr);
+    GST_DEBUG ("Previous group bitrate now %" G_GUINT64_FORMAT,
+        current->prev_bitrate);
+
+    /* FIXME : Better bitrate changes ? Currently 10% changes */
+    if (ABSDIFF (current->cur_bitrate,
+            current->prev_bitrate) * 10 > current->prev_bitrate) {
+      GST_DEBUG ("Current bitrate changed by more than 10%% (old:%"
+          G_GUINT64_FORMAT " new:%" G_GUINT64_FORMAT ")", current->prev_bitrate,
+          current->cur_bitrate);
+      /* If we detected a change in bitrate, this means that
+       * d(first - prev) is a different bitrate than d(last - first).
+       *
+       * Two conclusions can be made:
+       * 1) d(first - prev) is a complete bitrate "chain" (values between the
+       *    reference value and first pending value have consistent bitrate).
+       * 2) next values (from second pending value onwards) will no longer have
+       *    the same bitrate.
+       *
+       * The question remains as to how long the new bitrate change is going to
+       * last for (it might be short or longer term). For this we need to restart
+       * bitrate estimation.
+       *
+       * * We move over first to the last value of group (a new chain ends and
+       *   starts from there)
+       * * We remember that last group value as our new window reference
+       * * We restart our window filing from the last observed value
+       *
+       * Once our new window is filled we will end up in two different scenarios:
+       * 1) Either the bitrate change was consistent, and therefore the bitrate
+       *    will have remained constant over at least 2 window length
+       * 2) The bitrate change was very short (1 window duration) and we will
+       *    close that chain and restart again.
+       * X) And of course if any discont/gaps/wrapover happen in the meantime they
+       *    will also close the group.
+       */
+      _append_group_values (current->group, current->pending[current->first]);
+      current->prev = current->pending[current->first];
+      current->first = current->last;
+      current->write = (current->first + 1) % PCR_BITRATE_NEEDED;
+      return;
+    }
+  }
+
+  /* Update read position */
+  current->first = (current->first + 1) % PCR_BITRATE_NEEDED;
+}
+
+
+/* convert specified offset into stream time */
+GstClockTime
+wfd_ts_packetizer_offset_to_ts (WFDTSPacketizer * packetizer,
+    guint64 offset, guint16 pid)
+{
+  PCROffsetGroup *last;
+  WFDTSPCR *pcrtable;
+  GList *tmp;
+  GstClockTime res;
+  guint64 lastpcr, lastoffset;
+
+  GST_DEBUG ("offset %" G_GUINT64_FORMAT, offset);
+
+  if (G_UNLIKELY (!packetizer->calculate_offset))
+    return GST_CLOCK_TIME_NONE;
+
+  if (G_UNLIKELY (packetizer->refoffset == -1))
+    return GST_CLOCK_TIME_NONE;
+
+  if (G_UNLIKELY (offset < packetizer->refoffset))
+    return GST_CLOCK_TIME_NONE;
+
+  PACKETIZER_GROUP_LOCK (packetizer);
+
+  pcrtable = get_pcr_table (packetizer, pid);
+  if(pcrtable == NULL) {
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+    GST_WARNING ("The pcr table is null");
+    return GST_CLOCK_TIME_NONE;
+  }
+
+  if (g_list_length (pcrtable->groups) < 1) {
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+    GST_WARNING ("Not enough observations to return a duration estimate");
+    return GST_CLOCK_TIME_NONE;
+  }
+
+  if (g_list_length (pcrtable->groups) > 1) {
+    GST_LOG ("Using last group");
+
+    /* FIXME : Refine this later to use neighbouring groups */
+    tmp = g_list_last (pcrtable->groups);
+    last = tmp->data;
+
+    if (G_UNLIKELY (last->flags & PCR_GROUP_FLAG_ESTIMATED))
+      _reevaluate_group_pcr_offset (pcrtable, last);
+
+    /* lastpcr is the full value in PCR from the first first chunk of data */
+    lastpcr = last->values[last->last_value].pcr + last->pcr_offset;
+    /* lastoffset is the full offset from the first chunk of data */
+    lastoffset =
+        last->values[last->last_value].offset + last->first_offset -
+        packetizer->refoffset;
+  } else {
+    PCROffsetCurrent *current = pcrtable->current;
+
+    if (!current->group) {
+      PACKETIZER_GROUP_UNLOCK (packetizer);
+      GST_LOG ("No PCR yet");
+      return GST_CLOCK_TIME_NONE;
+    }
+    /* If doing progressive read, use current */
+    GST_LOG ("Using current group");
+    lastpcr = current->group->pcr_offset + current->pending[current->last].pcr;
+    lastoffset = current->first_offset + current->pending[current->last].offset;
+  }
+  GST_DEBUG ("lastpcr:%" GST_TIME_FORMAT " lastoffset:%" G_GUINT64_FORMAT
+      " refoffset:%" G_GUINT64_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (lastpcr)), lastoffset,
+      packetizer->refoffset);
+
+  /* Convert byte difference into time difference (and transformed from 27MHz to 1GHz) */
+  res =
+      PCRTIME_TO_GSTTIME (gst_util_uint64_scale (offset - packetizer->refoffset,
+          lastpcr, lastoffset));
+
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+
+  GST_DEBUG ("Returning timestamp %" GST_TIME_FORMAT " for offset %"
+      G_GUINT64_FORMAT, GST_TIME_ARGS (res), offset);
+
+  return res;
+}
+
+/* Input  : local PTS (in GHz units)
+ * Return : Stream time (in GHz units) */
+GstClockTime
+wfd_ts_packetizer_pts_to_ts (WFDTSPacketizer * packetizer,
+    GstClockTime pts, guint16 pcr_pid)
+{
+  GstClockTime res = GST_CLOCK_TIME_NONE;
+  WFDTSPCR *pcrtable;
+
+  PACKETIZER_GROUP_LOCK (packetizer);
+  pcrtable = get_pcr_table (packetizer, pcr_pid);
+  if(G_UNLIKELY(pcrtable == NULL)) {
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+    GST_ERROR ("The pcr table is null");
+    return res;
+  }
+
+  /* Use clock skew if present */
+  if (packetizer->calculate_skew
+      && GST_CLOCK_TIME_IS_VALID (pcrtable->base_time)) {
+    GST_DEBUG ("pts %" GST_TIME_FORMAT " base_pcrtime:%" GST_TIME_FORMAT
+        " base_time:%" GST_TIME_FORMAT " pcroffset:%" GST_TIME_FORMAT,
+        GST_TIME_ARGS (pts),
+        GST_TIME_ARGS (pcrtable->base_pcrtime),
+        GST_TIME_ARGS (pcrtable->base_time),
+        GST_TIME_ARGS (pcrtable->pcroffset));
+    res = pts + pcrtable->pcroffset;
+
+    /* Don't return anything if we differ too much against last seen PCR */
+    /* FIXME : Ideally we want to figure out whether we have a wraparound or
+     * a reset so we can provide actual values.
+     * That being said, this will only happen for the small interval of time
+     * where PTS/DTS are wrapping just before we see the first reset/wrap PCR
+     */
+    if (G_UNLIKELY (ABSDIFF (res, pcrtable->last_pcrtime) > 15 * GST_SECOND))
+      res = GST_CLOCK_TIME_NONE;
+    else {
+      GstClockTime tmp = pcrtable->base_time + pcrtable->skew;
+      if (tmp + res > pcrtable->base_pcrtime)
+        res += tmp - pcrtable->base_pcrtime;
+      else
+        res = GST_CLOCK_TIME_NONE;
+    }
+  } else if (packetizer->calculate_offset && pcrtable->groups) {
+    gint64 refpcr = G_MAXINT64, refpcroffset;
+    PCROffsetGroup *group = pcrtable->current->group;
+
+    /* Generic calculation:
+     * Stream Time = PTS - first group PCR + group PCR_offset
+     *
+     * In case of wrapover:
+     * Stream Time = PTS + MAX_PCR - first group PCR + group PCR_offset
+     * (which we actually do by using first group PCR -= MAX_PCR in order
+     *  to end up with the same calculation as for non-wrapover) */
+
+    if (group) {
+      /* If we have a current group the value is pretty much guaranteed */
+      GST_DEBUG ("Using current First PCR:%" GST_TIME_FORMAT " offset:%"
+          G_GUINT64_FORMAT " PCR_offset:%" GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->first_pcr)),
+          group->first_offset,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->pcr_offset)));
+      refpcr = group->first_pcr;
+      refpcroffset = group->pcr_offset;
+      if (pts < PCRTIME_TO_GSTTIME (refpcr)) {
+        /* Only apply wrapover if we're certain it is, and avoid
+         * returning bogus values if it's a PTS/DTS which is *just*
+         * before the start of the current group
+         */
+        if (PCRTIME_TO_GSTTIME (refpcr) - pts > GST_SECOND) {
+          pts += PCR_GST_MAX_VALUE;
+        } else
+          refpcr = G_MAXINT64;
+      }
+    } else {
+      GList *tmp;
+      /* Otherwise, find a suitable group */
+
+      GST_DEBUG ("Find group for current offset %" G_GUINT64_FORMAT,
+          packetizer->offset);
+
+      for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
+        PCROffsetGroup *tgroup = tmp->data;
+        GST_DEBUG ("Trying First PCR:%" GST_TIME_FORMAT " offset:%"
+            G_GUINT64_FORMAT " PCR_offset:%" GST_TIME_FORMAT,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (tgroup->first_pcr)),
+            tgroup->first_offset,
+            GST_TIME_ARGS (PCRTIME_TO_GSTTIME (tgroup->pcr_offset)));
+        /* Gone too far ? */
+        if (tgroup->first_offset > packetizer->offset) {
+          /* If there isn't a pending reset, use that value */
+          if (group) {
+            GST_DEBUG ("PTS is %" GST_TIME_FORMAT " into group",
+                GST_TIME_ARGS (pts - PCRTIME_TO_GSTTIME (group->first_pcr)));
+          }
+          break;
+        }
+        group = tgroup;
+        /* In that group ? */
+        if (group->first_offset + group->values[group->last_value].offset >
+            packetizer->offset) {
+          GST_DEBUG ("PTS is %" GST_TIME_FORMAT " into group",
+              GST_TIME_ARGS (pts - PCRTIME_TO_GSTTIME (group->first_pcr)));
+          break;
+        }
+      }
+      if (group && !(group->flags & PCR_GROUP_FLAG_RESET)) {
+        GST_DEBUG ("Using group !");
+        refpcr = group->first_pcr;
+        refpcroffset = group->pcr_offset;
+        if (pts < refpcr)
+          refpcr -= PCR_MAX_VALUE;
+      }
+    }
+    if (refpcr != G_MAXINT64)
+      res =
+          pts - PCRTIME_TO_GSTTIME (refpcr) + PCRTIME_TO_GSTTIME (refpcroffset);
+    else
+      GST_WARNING ("No groups, can't calculate timestamp");
+  } else
+    GST_WARNING ("Not enough information to calculate proper timestamp");
+
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+
+  GST_DEBUG ("Returning timestamp %" GST_TIME_FORMAT " for pts %"
+      GST_TIME_FORMAT " pcr_pid:0x%04x", GST_TIME_ARGS (res),
+      GST_TIME_ARGS (pts), pcr_pid);
+  return res;
+}
+
+/* Stream time to offset */
+guint64
+wfd_ts_packetizer_ts_to_offset (WFDTSPacketizer * packetizer,
+    GstClockTime ts, guint16 pcr_pid)
+{
+  WFDTSPCR *pcrtable;
+  guint64 res;
+  PCROffsetGroup *nextgroup = NULL, *prevgroup = NULL;
+  guint64 querypcr, firstpcr, lastpcr, firstoffset, lastoffset;
+  PCROffsetCurrent *current;
+  GList *tmp;
+
+  if (!packetizer->calculate_offset)
+    return -1;
+
+  PACKETIZER_GROUP_LOCK (packetizer);
+  pcrtable = get_pcr_table (packetizer, pcr_pid);
+
+  if (pcrtable == NULL || pcrtable->groups == NULL) {
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+    return -1;
+  }
+
+  querypcr = GSTTIME_TO_PCRTIME (ts);
+
+  GST_DEBUG ("Searching offset for ts %" GST_TIME_FORMAT, GST_TIME_ARGS (ts));
+
+  /* First check if we're within the current pending group */
+  current = pcrtable->current;
+  if (current && current->group && (querypcr >= current->group->pcr_offset) &&
+      querypcr - current->group->pcr_offset <=
+      current->pending[current->last].pcr) {
+    GST_DEBUG ("pcr is in current group");
+    nextgroup = current->group;
+    goto calculate_points;
+  }
+
+  /* Find the neighbouring groups */
+  for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
+    nextgroup = (PCROffsetGroup *) tmp->data;
+
+    GST_DEBUG ("Trying group PCR %" GST_TIME_FORMAT " (offset %"
+        G_GUINT64_FORMAT " pcr_offset %" GST_TIME_FORMAT,
+        GST_TIME_ARGS (PCRTIME_TO_GSTTIME (nextgroup->first_pcr)),
+        nextgroup->first_offset,
+        GST_TIME_ARGS (PCRTIME_TO_GSTTIME (nextgroup->pcr_offset)));
+
+    /* Check if we've gone too far */
+    if (nextgroup->pcr_offset > querypcr) {
+      GST_DEBUG ("pcr is before that group");
+      break;
+    }
+
+    if (tmp->next == NULL) {
+      GST_DEBUG ("pcr is beyond last group");
+      break;
+    }
+
+    prevgroup = nextgroup;
+
+    /* Maybe it's in this group */
+    if (nextgroup->values[nextgroup->last_value].pcr +
+        nextgroup->pcr_offset >= querypcr) {
+      GST_DEBUG ("pcr is in that group");
+      break;
+    }
+  }
+
+calculate_points:
+
+  GST_DEBUG ("nextgroup:%p, prevgroup:%p", nextgroup, prevgroup);
+
+  if (nextgroup == prevgroup || prevgroup == NULL) {
+    /* We use the current group to calculate position:
+     * * if the PCR is within this group
+     * * if there is only one group to use for calculation
+     */
+    GST_DEBUG ("In group or after last one");
+    lastoffset = firstoffset = nextgroup->first_offset;
+    lastpcr = firstpcr = nextgroup->pcr_offset;
+    if (current && nextgroup == current->group) {
+      lastoffset += current->pending[current->last].offset;
+      lastpcr += current->pending[current->last].pcr;
+    } else {
+      lastoffset += nextgroup->values[nextgroup->last_value].offset;
+      lastpcr += nextgroup->values[nextgroup->last_value].pcr;
+    }
+  } else {
+    GST_DEBUG ("Between group");
+    lastoffset = nextgroup->first_offset;
+    lastpcr = nextgroup->pcr_offset;
+    firstoffset =
+        prevgroup->values[prevgroup->last_value].offset +
+        prevgroup->first_offset;
+    firstpcr =
+        prevgroup->values[prevgroup->last_value].pcr + prevgroup->pcr_offset;
+  }
+
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+
+  GST_DEBUG ("Using prev PCR %" G_GUINT64_FORMAT " offset %" G_GUINT64_FORMAT,
+      firstpcr, firstoffset);
+  GST_DEBUG ("Using last PCR %" G_GUINT64_FORMAT " offset %" G_GUINT64_FORMAT,
+      lastpcr, lastoffset);
+
+  res = firstoffset;
+  if (lastpcr != firstpcr)
+    res += gst_util_uint64_scale (querypcr - firstpcr,
+        lastoffset - firstoffset, lastpcr - firstpcr);
+
+  GST_DEBUG ("Returning offset %" G_GUINT64_FORMAT " for ts %"
+      GST_TIME_FORMAT, res, GST_TIME_ARGS (ts));
+
+  return res;
+}
+
+void
+wfd_ts_packetizer_set_reference_offset (WFDTSPacketizer * packetizer,
+    guint64 refoffset)
+{
+  GST_DEBUG ("Setting reference offset to %" G_GUINT64_FORMAT, refoffset);
+
+  PACKETIZER_GROUP_LOCK (packetizer);
+  packetizer->refoffset = refoffset;
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+}
+
+void
+wfd_ts_packetizer_set_current_pcr_offset (WFDTSPacketizer * packetizer,
+    GstClockTime offset, guint16 pcr_pid)
+{
+  guint64 pcr_offset;
+  gint64 delta;
+  WFDTSPCR *pcrtable;
+  PCROffsetGroup *group;
+  GList *tmp;
+  gboolean apply = FALSE;
+
+  /* fast path */
+  PACKETIZER_GROUP_LOCK (packetizer);
+  pcrtable = get_pcr_table (packetizer, pcr_pid);
+
+  if (pcrtable == NULL || pcrtable->current->group == NULL) {
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+    return;
+  }
+
+  pcr_offset = GSTTIME_TO_PCRTIME (offset);
+
+  /* Pick delta from *first* group */
+  if (pcrtable->groups)
+    group = pcrtable->groups->data;
+  else
+    group = pcrtable->current->group;
+  GST_DEBUG ("Current group PCR %" GST_TIME_FORMAT " (offset %"
+      G_GUINT64_FORMAT " pcr_offset %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->first_pcr)),
+      group->first_offset,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (group->pcr_offset)));
+
+  /* Remember the difference between previous initial pcr_offset and
+   * new initial pcr_offset */
+  delta = pcr_offset - group->pcr_offset;
+  if (delta == 0) {
+    GST_DEBUG ("No shift to apply");
+    PACKETIZER_GROUP_UNLOCK (packetizer);
+    return;
+  }
+  GST_DEBUG ("Shifting groups by %" GST_TIME_FORMAT
+      " for new initial pcr_offset %" GST_TIME_FORMAT,
+      GST_TIME_ARGS (PCRTIME_TO_GSTTIME (delta)), GST_TIME_ARGS (offset));
+
+  for (tmp = pcrtable->groups; tmp; tmp = tmp->next) {
+    PCROffsetGroup *tgroup = (tmp->data);
+    if (tgroup == group)
+      apply = TRUE;
+    if (apply) {
+      tgroup->pcr_offset += delta;
+      GST_DEBUG ("Update group PCR %" GST_TIME_FORMAT " (offset %"
+          G_GUINT64_FORMAT " pcr_offset %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (tgroup->first_pcr)),
+          tgroup->first_offset,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (tgroup->pcr_offset)));
+    } else
+      GST_DEBUG ("Not modifying group PCR %" GST_TIME_FORMAT " (offset %"
+          G_GUINT64_FORMAT " pcr_offset %" GST_TIME_FORMAT,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (tgroup->first_pcr)),
+          tgroup->first_offset,
+          GST_TIME_ARGS (PCRTIME_TO_GSTTIME (tgroup->pcr_offset)));
+  }
+  PACKETIZER_GROUP_UNLOCK (packetizer);
+}
diff --git a/wfdtsdemux/wfdtspacketizer.h b/wfdtsdemux/wfdtspacketizer.h
new file mode 100755 (executable)
index 0000000..b90c71c
--- /dev/null
@@ -0,0 +1,377 @@
+/*
+ * wfdtspacketizer.h -
+ * Copyright (C) 2007 Alessandro Decina
+ *
+ * Authors:
+ *   Alessandro Decina <alessandro@nnva.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef GST_WFD_TS_PACKETIZER_H
+#define GST_WFD_TS_PACKETIZER_H
+
+#include <gst/gst.h>
+#include <gst/base/gstadapter.h>
+#include <glib.h>
+
+#include "gstwfdtsdescriptor.h"
+#include "gstwfdtssection.h"
+#include "gstwfdtsdefs.h"
+
+#define WFD_TS_NORMAL_PACKETSIZE  188
+#define WFD_TS_M2TS_PACKETSIZE    192
+#define WFD_TS_DVB_ASI_PACKETSIZE 204
+#define WFD_TS_ATSC_PACKETSIZE    208
+
+#define WFD_TS_MIN_PACKETSIZE WFD_TS_NORMAL_PACKETSIZE
+#define WFD_TS_MAX_PACKETSIZE WFD_TS_ATSC_PACKETSIZE
+
+#define MPEGTS_AFC_DISCONTINUITY_FLAG           0x80
+#define MPEGTS_AFC_RANDOM_ACCES_FLAGS           0x40
+#define MPEGTS_AFC_ELEMENTARY_STREAM_PRIORITY   0x20
+#define MPEGTS_AFC_PCR_FLAG                     0x10
+#define MPEGTS_AFC_OPCR_FLAG                    0x08
+#define MPEGTS_AFC_SPLICING_POINT_FLAG          0x04
+#define MPEGTS_AFC_TRANSPORT_PRIVATE_DATA_FLAG  0x02
+#define MPEGTS_AFC_EXTENSION_FLAG               0x01
+
+#define MAX_WINDOW 512
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_WFD_TS_PACKETIZER \
+  (wfd_ts_packetizer_get_type())
+#define GST_WFD_TS_PACKETIZER(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_WFD_TS_PACKETIZER,WFDTSPacketizer))
+#define GST_WFD_TS_PACKETIZER_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_WFD_TS_PACKETIZER,WFDTSPacketizerClass))
+#define GST_IS_WFD_TS_PACKETIZER(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_TS_PACKETIZER))
+#define GST_IS_WFD_TS_PACKETIZER_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_TS_PACKETIZER))
+
+typedef struct _WFDTSPacketizer WFDTSPacketizer;
+typedef struct _WFDTSPacketizerClass WFDTSPacketizerClass;
+
+typedef struct
+{
+  guint16 pid;
+  guint   continuity_counter;
+
+  /* Section data (always newly allocated) */
+  guint8 *section_data;
+  /* Current offset in section_data */
+  guint16 section_offset;
+
+  /* Values for pending section */
+  /* table_id of the pending section_data */
+  guint8  table_id;
+  guint   section_length;
+  guint8  version_number;
+  guint16 subtable_extension;
+  guint8  section_number;
+  guint8  last_section_number;
+
+  GSList *subtables;
+
+  /* Upstream offset of the data contained in the section */
+  guint64 offset;
+} WFDTSPacketizerStream;
+
+/* Maximum number of MpegTSPcr
+ * 256 should be sufficient for most multiplexes */
+#define MAX_PCR_OBS_CHANNELS 256
+
+/* PCR/offset structure */
+typedef struct _PCROffset
+{
+  /* PCR value (units: 1/27MHz) */
+  guint64 pcr;
+
+  /* The offset (units: bytes) */
+  guint64 offset;
+} PCROffset;
+
+/* Flags used on groups */
+enum
+{
+  /* Closed groups: There is a contiguous next group */
+  PCR_GROUP_FLAG_CLOSED = 1 << 0,
+  /* estimated: the pcr_offset has been estimated and is not
+   * guaranteed to be 100% accurate */
+  PCR_GROUP_FLAG_ESTIMATED = 1 << 1,
+  /* reset: there is a pcr reset between the end of this
+   * group and the next one.
+   * This flag is exclusive with CLOSED. */
+  PCR_GROUP_FLAG_RESET = 1 << 2,
+  /* reset: there is a pcr wrapover between the end of this
+   * group and the next one.
+   * This flag is exclusive with CLOSED. */
+  PCR_GROUP_FLAG_WRAPOVER = 1 << 3
+};
+
+
+
+/* PCROffsetGroup: A group of PCR observations.
+ * All values in a group have got the same reference pcr and
+ * byte offset (first_pcr/first_offset).
+ */
+#define DEFAULT_ALLOCATED_OFFSET 16
+typedef struct _PCROffsetGroup
+{
+  /* Flags (see PCR_GROUP_FLAG_* above) */
+  guint flags;
+
+  /* First raw PCR of this group. Units: 1/27MHz.
+   * All values[].pcr are differences against first_pcr */
+  guint64 first_pcr;
+  /* Offset of this group in bytes.
+   * All values[].offset are differences against first_offset */
+  guint64 first_offset;
+
+  /* Dynamically allocated table of PCROffset */
+  PCROffset *values;
+  /* number of PCROffset allocated in values */
+  guint nb_allocated;
+  /* number of *actual* PCROffset contained in values */
+  guint last_value;
+
+  /* Offset since the very first PCR value observed in the whole
+   * stream. Units: 1/27MHz.
+   * This will take into account gaps/wraparounds/resets/... and is
+   * used to determine running times.
+   * The value is only guaranteed to be 100% accurate if the group
+   * does not have the ESTIMATED flag.
+   * If the value is estimated, the pcr_offset shall be recalculated
+   * (based on previous groups) whenever it is accessed.
+   */
+  guint64 pcr_offset;
+
+  /* FIXME : Cache group bitrate ? */
+} PCROffsetGroup;
+
+/* Number of PCRs needed before bitrate estimation can start */
+/* Note: the reason we use 10 is because PCR should normally be
+ * received at least every 100ms so this gives us close to
+ * a 1s moving window to calculate bitrate */
+#define PCR_BITRATE_NEEDED 10
+
+/* PCROffsetCurrent: The PCR/Offset window iterator
+ * This is used to estimate/observe incoming PCR/offset values
+ * Points to a group (which it is filling) */
+typedef struct _PCROffsetCurrent
+{
+  /* The PCROffsetGroup we are filling.
+   * If NULL, a group needs to be identified */
+  PCROffsetGroup *group;
+
+  /* Table of pending values we are iterating over */
+  PCROffset pending[PCR_BITRATE_NEEDED];
+
+  /* base offset/pcr from the group */
+  guint64 first_pcr;
+  guint64 first_offset;
+
+  /* The previous reference PCROffset
+   * This corresponds to the last entry of the group we are filling
+   * and is used to calculate prev_bitrate */
+  PCROffset prev;
+
+  /* The last PCROffset in pending[] */
+  PCROffset last_value;
+
+  /* Location of first pending PCR/offset observation in pending */
+  guint first;
+  /* Location of last pending PCR/offset observation in pending */
+  guint last;
+  /* Location of next write in pending */
+  guint write;
+
+  /* bitrate is always in bytes per second */
+
+  /* cur_bitrate is the bitrate of the pending values: d(last-first) */
+  guint64 cur_bitrate;
+
+  /* prev_bitrate is the bitrate between reference PCROffset
+   * and the first pending value. Used to detect changes
+   * in bitrate */
+  guint64 prev_bitrate;
+} PCROffsetCurrent;
+
+typedef struct _WFDTSPCR
+{
+  guint16 pid;
+
+  /* Following variables are only active/used when
+   * calculate_skew is TRUE */
+  GstClockTime base_time;
+  GstClockTime base_pcrtime;
+  GstClockTime prev_out_time;
+  GstClockTime prev_in_time;
+  GstClockTime last_pcrtime;
+  gint64 window[MAX_WINDOW];
+  guint window_pos;
+  guint window_size;
+  gboolean window_filling;
+  gint64 window_min;
+  gint64 skew;
+  gint64 prev_send_diff;
+
+  /* Offset to apply to PCR to handle wraparounds */
+  guint64 pcroffset;
+
+  /* Used for bitrate calculation */
+  /* List of PCR/offset observations */
+  GList *groups;
+
+  /* Current PCR/offset observations (used to update pcroffsets) */
+  PCROffsetCurrent *current;
+} WFDTSPCR;
+
+struct _WFDTSPacketizer {
+  GObject     parent;
+
+  GMutex group_lock;
+
+  GstAdapter *adapter;
+  /* streams hashed by pid */
+  /* FIXME : be more memory efficient (see how it's done in mpegtsbase) */
+  WFDTSPacketizerStream **streams;
+  gboolean    disposed;
+  guint16     packet_size;
+
+  /* current offset of the tip of the adapter */
+  guint64  offset;
+  gboolean empty;
+
+  /* clock skew calculation */
+  gboolean       calculate_skew;
+
+  /* offset/bitrate calculator */
+  gboolean       calculate_offset;
+
+  /* Shortcuts for adapter usage */
+  guint8 *map_data;
+  gsize map_offset;
+  gsize map_size;
+  gboolean need_sync;
+
+  /* Reference offset */
+  guint64 refoffset;
+
+  /* Number of seen pcr/offset observations (FIXME : kill later) */
+  guint nb_seen_offsets;
+
+  /* Last inputted timestamp */
+  GstClockTime last_in_time;
+
+  /* offset to observations table */
+  guint8 pcrtablelut[0x2000];
+  WFDTSPCR *observations[MAX_PCR_OBS_CHANNELS];
+  guint8 lastobsid;
+};
+
+struct _WFDTSPacketizerClass {
+  GObjectClass object_class;
+};
+
+#define FLAGS_SCRAMBLED(f) (f & 0xc0)
+#define FLAGS_HAS_AFC(f) (f & 0x20)
+#define FLAGS_HAS_PAYLOAD(f) (f & 0x10)
+#define FLAGS_CONTINUITY_COUNTER(f) (f & 0x0f)
+
+typedef struct
+{
+  gint16  pid;
+  guint8  payload_unit_start_indicator;
+  guint8  scram_afc_cc;
+  guint8 *payload;
+
+  guint8 *data_start;
+  guint8 *data_end;
+  guint8 *data;
+
+  guint8  afc_flags;
+  guint64 pcr;
+  guint64 offset;
+} WFDTSPacketizerPacket;
+
+typedef struct
+{
+  guint8 table_id;
+  /* the spec says sub_table_extension is the fourth and fifth byte of a 
+   * section when the section_syntax_indicator is set to a value of "1". If 
+   * section_syntax_indicator is 0, sub_table_extension will be set to 0 */
+  guint16  subtable_extension;
+  guint8   version_number;
+  guint8   last_section_number;
+  /* table of bits, whether the section was seen or not.
+   * Use WFD_TS_BIT_* macros to check */
+  /* Size is 32, because there's a maximum of 256 (32*8) section_number */
+  guint8   seen_section[32];
+} WFDTSPacketizerStreamSubtable;
+
+#define WFD_TS_BIT_SET(field, offs)    ((field)[(offs) >> 3] |=  (1 << ((offs) & 0x7)))
+#define WFD_TS_BIT_UNSET(field, offs)  ((field)[(offs) >> 3] &= ~(1 << ((offs) & 0x7)))
+#define WFD_TS_BIT_IS_SET(field, offs) ((field)[(offs) >> 3] &   (1 << ((offs) & 0x7)))
+
+typedef enum {
+  PACKET_BAD       = FALSE,
+  PACKET_OK        = TRUE,
+  PACKET_NEED_MORE
+} WFDTSPacketizerPacketReturn;
+
+G_GNUC_INTERNAL GType wfd_ts_packetizer_get_type(void);
+
+G_GNUC_INTERNAL WFDTSPacketizer *wfd_ts_packetizer_new (void);
+G_GNUC_INTERNAL void wfd_ts_packetizer_clear (WFDTSPacketizer *packetizer);
+G_GNUC_INTERNAL void wfd_ts_packetizer_flush (WFDTSPacketizer *packetizer, gboolean hard);
+G_GNUC_INTERNAL void wfd_ts_packetizer_push (WFDTSPacketizer *packetizer, GstBuffer *buffer);
+G_GNUC_INTERNAL gboolean wfd_ts_packetizer_has_packets (WFDTSPacketizer *packetizer);
+G_GNUC_INTERNAL WFDTSPacketizerPacketReturn wfd_ts_packetizer_next_packet (WFDTSPacketizer *packetizer,
+  WFDTSPacketizerPacket *packet);
+G_GNUC_INTERNAL WFDTSPacketizerPacketReturn
+wfd_ts_packetizer_process_next_packet(WFDTSPacketizer * packetizer);
+G_GNUC_INTERNAL void wfd_ts_packetizer_clear_packet (WFDTSPacketizer *packetizer,
+                                    WFDTSPacketizerPacket *packet);
+G_GNUC_INTERNAL void wfd_ts_packetizer_remove_stream(WFDTSPacketizer *packetizer,
+  gint16 pid);
+
+G_GNUC_INTERNAL GstWFDTSSection *wfd_ts_packetizer_push_section (WFDTSPacketizer *packetzer,
+                                                                 WFDTSPacketizerPacket *packet, GList **remaining);
+
+/* Only valid if calculate_offset is TRUE */
+G_GNUC_INTERNAL guint wfd_ts_packetizer_get_seen_pcr (WFDTSPacketizer *packetizer);
+
+G_GNUC_INTERNAL GstClockTime
+wfd_ts_packetizer_offset_to_ts (WFDTSPacketizer * packetizer,
+                               guint64 offset, guint16 pcr_pid);
+G_GNUC_INTERNAL guint64
+wfd_ts_packetizer_ts_to_offset (WFDTSPacketizer * packetizer,
+                               GstClockTime ts, guint16 pcr_pid);
+G_GNUC_INTERNAL GstClockTime
+wfd_ts_packetizer_pts_to_ts (WFDTSPacketizer * packetizer,
+                            GstClockTime pts, guint16 pcr_pid);
+G_GNUC_INTERNAL void
+wfd_ts_packetizer_set_current_pcr_offset (WFDTSPacketizer * packetizer,
+                         GstClockTime offset, guint16 pcr_pid);
+G_GNUC_INTERNAL void
+wfd_ts_packetizer_set_reference_offset (WFDTSPacketizer * packetizer,
+                                       guint64 refoffset);
+G_END_DECLS
+
+#endif /* GST_WFD_TS_PACKETIZER_H */
diff --git a/wfdtsdemux/wfdtsparse.c b/wfdtsdemux/wfdtsparse.c
new file mode 100755 (executable)
index 0000000..fdbc7cd
--- /dev/null
@@ -0,0 +1,691 @@
+/*
+ * wfdtsparse.c -
+ * Copyright (C) 2007 Alessandro Decina
+ *
+ * Authors:
+ *   Alessandro Decina <alessandro@nnva.org>
+ *   Zaheer Abbas Merali <zaheerabbas at merali dot org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "wfdtsbase.h"
+#include "wfdtsparse.h"
+#include "gstwfdtsdesc.h"
+
+/* latency in mseconds */
+#define TS_LATENCY 700
+
+#define TABLE_ID_UNSET 0xFF
+#define RUNNING_STATUS_RUNNING 4
+
+GST_DEBUG_CATEGORY_STATIC (wfd_ts_parse_debug);
+#define GST_CAT_DEFAULT wfd_ts_parse_debug
+
+typedef struct _WFDTSParsePad WFDTSParsePad;
+
+typedef struct
+{
+  WFDTSBaseProgram program;
+  WFDTSParsePad *tspad;
+} WFDTSParseProgram;
+
+struct _WFDTSParsePad
+{
+  GstPad *pad;
+
+  /* the program number that the peer wants on this pad */
+  gint program_number;
+  WFDTSParseProgram *program;
+
+  /* set to FALSE before a push and TRUE after */
+  gboolean pushed;
+
+  /* the return of the latest push */
+  GstFlowReturn flow_return;
+};
+
+static GstStaticPadTemplate src_template =
+GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS ("video/mpegts, " "systemstream = (boolean) true ")
+    );
+
+static GstStaticPadTemplate program_template =
+GST_STATIC_PAD_TEMPLATE ("program_%u", GST_PAD_SRC,
+    GST_PAD_REQUEST,
+    GST_STATIC_CAPS ("video/mpegts, " "systemstream = (boolean) true ")
+    );
+
+enum
+{
+  ARG_0,
+  /* FILL ME */
+};
+
+static void
+wfd_ts_parse_program_started (WFDTSBase * base, WFDTSBaseProgram * program);
+static void
+wfd_ts_parse_program_stopped (WFDTSBase * base, WFDTSBaseProgram * program);
+
+static GstFlowReturn
+wfd_ts_parse_push (WFDTSBase * base, WFDTSPacketizerPacket * packet,
+    GstWFDTSSection * section);
+
+static WFDTSParsePad *wfd_ts_parse_create_tspad (WFDTSParse * parse,
+    const gchar * name);
+static void wfd_ts_parse_destroy_tspad (WFDTSParse * parse,
+    WFDTSParsePad * tspad);
+
+static void wfd_ts_parse_pad_removed (GstElement * element, GstPad * pad);
+static GstPad *wfd_ts_parse_request_new_pad (GstElement * element,
+    GstPadTemplate * templ, const gchar * name, const GstCaps * caps);
+static void wfd_ts_parse_release_pad (GstElement * element, GstPad * pad);
+static gboolean wfd_ts_parse_src_pad_query (GstPad * pad, GstObject * parent,
+    GstQuery * query);
+static gboolean push_event (WFDTSBase * base, GstEvent * event);
+
+#define wfd_ts_parse_parent_class parent_class
+G_DEFINE_TYPE (WFDTSParse, wfd_ts_parse, GST_TYPE_WFD_TS_BASE);
+static void wfd_ts_parse_reset (WFDTSBase * base);
+static GstFlowReturn wfd_ts_parse_input_done (WFDTSBase * base,
+    GstBuffer * buffer);
+
+static void
+wfd_ts_parse_class_init (WFDTSParseClass * klass)
+{
+  GstElementClass *element_class;
+  WFDTSBaseClass *ts_class;
+
+  element_class = GST_ELEMENT_CLASS (klass);
+  element_class->pad_removed = wfd_ts_parse_pad_removed;
+  element_class->request_new_pad = wfd_ts_parse_request_new_pad;
+  element_class->release_pad = wfd_ts_parse_release_pad;
+
+  gst_element_class_add_pad_template (element_class,
+      gst_static_pad_template_get (&src_template));
+  gst_element_class_add_pad_template (element_class,
+      gst_static_pad_template_get (&program_template));
+
+  gst_element_class_set_static_metadata (element_class,
+      "MPEG transport stream parser", "Codec/Parser",
+      "Parses MPEG2 transport streams",
+      "Alessandro Decina <alessandro@nnva.org>, "
+      "Zaheer Abbas Merali <zaheerabbas at merali dot org>");
+
+  ts_class = GST_WFD_TS_BASE_CLASS (klass);
+  ts_class->push = GST_DEBUG_FUNCPTR (wfd_ts_parse_push);
+  ts_class->push_event = GST_DEBUG_FUNCPTR (push_event);
+  ts_class->program_started = GST_DEBUG_FUNCPTR (wfd_ts_parse_program_started);
+  ts_class->program_stopped = GST_DEBUG_FUNCPTR (wfd_ts_parse_program_stopped);
+  ts_class->reset = GST_DEBUG_FUNCPTR (wfd_ts_parse_reset);
+  ts_class->input_done = GST_DEBUG_FUNCPTR (wfd_ts_parse_input_done);
+}
+
+static void
+wfd_ts_parse_init (WFDTSParse * parse)
+{
+  WFDTSBase *base = (WFDTSBase *) parse;
+
+  base->program_size = sizeof (WFDTSParseProgram);
+  /* We will only need to handle data/section if we have request pads */
+  base->push_data = FALSE;
+  base->push_section = FALSE;
+
+  parse->srcpad = gst_pad_new_from_static_template (&src_template, "src");
+  parse->first = TRUE;
+  gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
+
+  parse->have_group_id = FALSE;
+  parse->group_id = G_MAXUINT;
+}
+
+static void
+wfd_ts_parse_reset (WFDTSBase * base)
+{
+  /* Set the various know PIDs we are interested in */
+
+  /* CAT */
+  WFD_TS_BIT_SET (base->known_psi, 1);
+  /* NIT, ST */
+  WFD_TS_BIT_SET (base->known_psi, 0x10);
+  /* SDT, BAT, ST */
+  WFD_TS_BIT_SET (base->known_psi, 0x11);
+  /* EIT, ST, CIT (TS 102 323) */
+  WFD_TS_BIT_SET (base->known_psi, 0x12);
+  /* RST, ST */
+  WFD_TS_BIT_SET (base->known_psi, 0x13);
+  /* RNT (TS 102 323) */
+  WFD_TS_BIT_SET (base->known_psi, 0x16);
+  /* inband signalling */
+  WFD_TS_BIT_SET (base->known_psi, 0x1c);
+  /* measurement */
+  WFD_TS_BIT_SET (base->known_psi, 0x1d);
+  /* DIT */
+  WFD_TS_BIT_SET (base->known_psi, 0x1e);
+  /* SIT */
+  WFD_TS_BIT_SET (base->known_psi, 0x1f);
+
+  GST_WFD_TS_PARSE (base)->first = TRUE;
+  GST_WFD_TS_PARSE (base)->have_group_id = FALSE;
+  GST_WFD_TS_PARSE (base)->group_id = G_MAXUINT;
+
+  g_list_free_full (GST_WFD_TS_PARSE (base)->pending_buffers,
+      (GDestroyNotify) gst_buffer_unref);
+  GST_WFD_TS_PARSE (base)->pending_buffers = NULL;;
+}
+
+static void
+wfd_prepare_src_pad (WFDTSBase * base, WFDTSParse * parse)
+{
+  if (base->packetizer->packet_size) {
+    GstEvent *event;
+    gchar *stream_id;
+    GstCaps *caps;
+
+    stream_id =
+        gst_pad_create_stream_id (parse->srcpad, GST_ELEMENT_CAST (base),
+        "multi-program");
+
+    event =
+        gst_pad_get_sticky_event (parse->parent.sinkpad, GST_EVENT_STREAM_START,
+        0);
+    if (event) {
+      if (gst_event_parse_group_id (event, &parse->group_id))
+        parse->have_group_id = TRUE;
+      else
+        parse->have_group_id = FALSE;
+      gst_event_unref (event);
+    } else if (!parse->have_group_id) {
+      parse->have_group_id = TRUE;
+      parse->group_id = gst_util_group_id_next ();
+    }
+    event = gst_event_new_stream_start (stream_id);
+    if (parse->have_group_id)
+      gst_event_set_group_id (event, parse->group_id);
+
+    gst_pad_push_event (parse->srcpad, event);
+    g_free (stream_id);
+
+    caps = gst_caps_new_simple ("video/mpegts",
+        "systemstream", G_TYPE_BOOLEAN, TRUE,
+        "packetsize", G_TYPE_INT, base->packetizer->packet_size, NULL);
+
+    gst_pad_set_caps (parse->srcpad, caps);
+    gst_caps_unref (caps);
+
+    gst_pad_push_event (parse->srcpad, gst_event_new_segment (&base->segment));
+
+    parse->first = FALSE;
+  }
+}
+
+static gboolean
+push_event (WFDTSBase * base, GstEvent * event)
+{
+  WFDTSParse *parse = (WFDTSParse *) base;
+  GList *tmp;
+
+  if (G_UNLIKELY (parse->first)) {
+    /* We will send the segment when really starting  */
+    if (G_UNLIKELY (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT)) {
+      gst_event_unref (event);
+      return TRUE;
+    }
+    wfd_prepare_src_pad (base, parse);
+  }
+
+  for (tmp = parse->srcpads; tmp; tmp = tmp->next) {
+    GstPad *pad = (GstPad *) tmp->data;
+    if (pad) {
+      gst_event_ref (event);
+      gst_pad_push_event (pad, event);
+    }
+  }
+
+  gst_pad_push_event (parse->srcpad, event);
+
+  return TRUE;
+}
+
+static WFDTSParsePad *
+wfd_ts_parse_create_tspad (WFDTSParse * parse, const gchar * pad_name)
+{
+  GstPad *pad;
+  WFDTSParsePad *tspad;
+
+  pad = gst_pad_new_from_static_template (&program_template, pad_name);
+  if(pad == NULL) {
+    GST_ERROR("gst_pad_new_from_static_template fail");
+    return NULL;
+  }
+  gst_pad_set_query_function (pad,
+      GST_DEBUG_FUNCPTR (wfd_ts_parse_src_pad_query));
+
+  /* create our wrapper */
+  tspad = g_new0 (WFDTSParsePad, 1);
+  tspad->pad = pad;
+  tspad->program_number = -1;
+  tspad->program = NULL;
+  tspad->pushed = FALSE;
+  tspad->flow_return = GST_FLOW_NOT_LINKED;
+  gst_pad_set_element_private (pad, tspad);
+
+  return tspad;
+}
+
+static void
+wfd_ts_parse_destroy_tspad (WFDTSParse * parse, WFDTSParsePad * tspad)
+{
+  /* free the wrapper */
+  g_free (tspad);
+}
+
+static void
+wfd_ts_parse_pad_removed (GstElement * element, GstPad * pad)
+{
+  WFDTSParsePad *tspad;
+  WFDTSBase *base = (WFDTSBase *) element;
+  WFDTSParse *parse = GST_WFD_TS_PARSE (element);
+
+  if (gst_pad_get_direction (pad) == GST_PAD_SINK)
+    return;
+
+  tspad = (WFDTSParsePad *) gst_pad_get_element_private (pad);
+  if (tspad) {
+    wfd_ts_parse_destroy_tspad (parse, tspad);
+
+    parse->srcpads = g_list_remove_all (parse->srcpads, pad);
+  }
+  if (parse->srcpads == NULL) {
+    base->push_data = FALSE;
+    base->push_section = FALSE;
+  }
+
+  if (GST_ELEMENT_CLASS (parent_class)->pad_removed)
+    GST_ELEMENT_CLASS (parent_class)->pad_removed (element, pad);
+}
+
+static GstPad *
+wfd_ts_parse_request_new_pad (GstElement * element, GstPadTemplate * template,
+    const gchar * padname, const GstCaps * caps)
+{
+  WFDTSBase *base = (WFDTSBase *) element;
+  WFDTSParse *parse;
+  WFDTSParsePad *tspad;
+  WFDTSParseProgram *parseprogram;
+  GstPad *pad;
+  gint program_num = -1;
+  GstEvent *event;
+  gchar *stream_id;
+
+  g_return_val_if_fail (template != NULL, NULL);
+  g_return_val_if_fail (GST_IS_WFD_TS_PARSE (element), NULL);
+  g_return_val_if_fail (padname != NULL, NULL);
+
+  sscanf (padname + 8, "%d", &program_num);
+
+  GST_DEBUG_OBJECT (element, "padname:%s, program:%d", padname, program_num);
+
+  parse = GST_WFD_TS_PARSE (element);
+
+  tspad = wfd_ts_parse_create_tspad (parse, padname);
+  if(tspad == NULL) {
+    GST_ERROR("wfd_ts_parse_create_tspad fail");
+    return NULL;
+  }
+  tspad->program_number = program_num;
+
+  /* Find if the program is already active */
+  parseprogram =
+      (WFDTSParseProgram *) wfd_ts_base_get_program (GST_WFD_TS_BASE (parse),
+      program_num);
+  if (parseprogram) {
+    tspad->program = parseprogram;
+    parseprogram->tspad = tspad;
+  }
+
+  pad = tspad->pad;
+  parse->srcpads = g_list_append (parse->srcpads, pad);
+  base->push_data = TRUE;
+  base->push_section = TRUE;
+
+  gst_pad_set_active (pad, TRUE);
+
+  stream_id = gst_pad_create_stream_id (pad, element, padname + 8);
+
+  event =
+      gst_pad_get_sticky_event (parse->parent.sinkpad, GST_EVENT_STREAM_START,
+      0);
+  if (event) {
+    if (gst_event_parse_group_id (event, &parse->group_id))
+      parse->have_group_id = TRUE;
+    else
+      parse->have_group_id = FALSE;
+    gst_event_unref (event);
+  } else if (!parse->have_group_id) {
+    parse->have_group_id = TRUE;
+    parse->group_id = gst_util_group_id_next ();
+  }
+  event = gst_event_new_stream_start (stream_id);
+  if (parse->have_group_id)
+    gst_event_set_group_id (event, parse->group_id);
+
+  gst_pad_push_event (pad, event);
+  g_free (stream_id);
+
+  gst_element_add_pad (element, pad);
+
+  return pad;
+}
+
+static void
+wfd_ts_parse_release_pad (GstElement * element, GstPad * pad)
+{
+  gst_pad_set_active (pad, FALSE);
+  /* we do the cleanup in GstElement::pad-removed */
+  gst_element_remove_pad (element, pad);
+}
+
+static GstFlowReturn
+wfd_ts_parse_tspad_push_section (WFDTSParse * parse, WFDTSParsePad * tspad,
+    GstWFDTSSection * section, WFDTSPacketizerPacket * packet)
+{
+  GstFlowReturn ret = GST_FLOW_OK;
+  gboolean to_push = TRUE;
+
+  if (tspad->program_number != -1) {
+    if (tspad->program) {
+      /* we push all sections to all pads except PMTs which we
+       * only push to pads meant to receive that program number */
+      if (section->table_id == 0x02) {
+        /* PMT */
+        if (section->subtable_extension != tspad->program_number)
+          to_push = FALSE;
+      }
+    } else {
+      /* there's a program filter on the pad but the PMT for the program has not
+       * been parsed yet, ignore the pad until we get a PMT */
+      to_push = FALSE;
+    }
+  }
+
+  GST_DEBUG_OBJECT (parse,
+      "pushing section: %d program number: %d table_id: %d", to_push,
+      tspad->program_number, section->table_id);
+
+  if (to_push) {
+    GstBuffer *buf =
+        gst_buffer_new_and_alloc (packet->data_end - packet->data_start);
+    gst_buffer_fill (buf, 0, packet->data_start,
+        packet->data_end - packet->data_start);
+    ret = gst_pad_push (tspad->pad, buf);
+  }
+
+  return ret;
+}
+
+static GstFlowReturn
+wfd_ts_parse_tspad_push (WFDTSParse * parse, WFDTSParsePad * tspad,
+    WFDTSPacketizerPacket * packet)
+{
+  GstFlowReturn ret = GST_FLOW_OK;
+  WFDTSBaseStream **pad_pids = NULL;
+
+  if (tspad->program_number != -1) {
+    if (tspad->program) {
+      WFDTSBaseProgram *bp = (WFDTSBaseProgram *) tspad->program;
+      pad_pids = bp->streams;
+    } else {
+      /* there's a program filter on the pad but the PMT for the program has not
+       * been parsed yet, ignore the pad until we get a PMT */
+      goto out;
+    }
+  }
+
+  if (pad_pids == NULL || pad_pids[packet->pid]) {
+    GstBuffer *buf =
+        gst_buffer_new_and_alloc (packet->data_end - packet->data_start);
+    gst_buffer_fill (buf, 0, packet->data_start,
+        packet->data_end - packet->data_start);
+    /* push if there's no filter or if the pid is in the filter */
+    ret = gst_pad_push (tspad->pad, buf);
+  }
+
+out:
+  return ret;
+}
+
+static void
+pad_clear_for_push (GstPad * pad, WFDTSParse * parse)
+{
+  WFDTSParsePad *tspad = (WFDTSParsePad *) gst_pad_get_element_private (pad);
+
+  tspad->flow_return = GST_FLOW_NOT_LINKED;
+  tspad->pushed = FALSE;
+}
+
+static GstFlowReturn
+wfd_ts_parse_push (WFDTSBase * base, WFDTSPacketizerPacket * packet,
+    GstWFDTSSection * section)
+{
+  WFDTSParse *parse = (WFDTSParse *) base;
+  guint32 pads_cookie;
+  gboolean done = FALSE;
+  GstPad *pad = NULL;
+  WFDTSParsePad *tspad;
+  GstFlowReturn ret;
+  GList *srcpads;
+
+  GST_OBJECT_LOCK (parse);
+  srcpads = parse->srcpads;
+
+  /* clear tspad->pushed on pads */
+  g_list_foreach (srcpads, (GFunc) pad_clear_for_push, parse);
+  if (srcpads)
+    ret = GST_FLOW_NOT_LINKED;
+  else
+    ret = GST_FLOW_OK;
+
+  /* Get cookie and source pads list */
+  pads_cookie = GST_ELEMENT_CAST (parse)->pads_cookie;
+  if (G_LIKELY (srcpads)) {
+    pad = GST_PAD_CAST (srcpads->data);
+    g_object_ref (pad);
+  }
+  GST_OBJECT_UNLOCK (parse);
+
+  while (pad && !done) {
+    tspad = gst_pad_get_element_private (pad);
+
+    if (G_LIKELY (!tspad->pushed)) {
+      if (section) {
+        tspad->flow_return =
+            wfd_ts_parse_tspad_push_section (parse, tspad, section, packet);
+      } else {
+        tspad->flow_return = wfd_ts_parse_tspad_push (parse, tspad, packet);
+      }
+      tspad->pushed = TRUE;
+
+      if (G_UNLIKELY (tspad->flow_return != GST_FLOW_OK
+              && tspad->flow_return != GST_FLOW_NOT_LINKED)) {
+        /* return the error upstream */
+        ret = tspad->flow_return;
+        done = TRUE;
+      }
+
+    }
+
+    if (ret == GST_FLOW_NOT_LINKED)
+      ret = tspad->flow_return;
+
+    g_object_unref (pad);
+
+    if (G_UNLIKELY (!done)) {
+      GST_OBJECT_LOCK (parse);
+      if (G_UNLIKELY (pads_cookie != GST_ELEMENT_CAST (parse)->pads_cookie)) {
+        /* resync */
+        GST_DEBUG ("resync");
+        pads_cookie = GST_ELEMENT_CAST (parse)->pads_cookie;
+        srcpads = parse->srcpads;
+      } else {
+        GST_DEBUG ("getting next pad");
+        /* Get next pad */
+        srcpads = g_list_next (srcpads);
+      }
+
+      if (srcpads) {
+        pad = GST_PAD_CAST (srcpads->data);
+        g_object_ref (pad);
+      } else
+        done = TRUE;
+      GST_OBJECT_UNLOCK (parse);
+    }
+  }
+
+  return ret;
+}
+
+static GstFlowReturn
+wfd_ts_parse_input_done (WFDTSBase * base, GstBuffer * buffer)
+{
+  WFDTSParse *parse = GST_WFD_TS_PARSE (base);
+  GstFlowReturn ret = GST_FLOW_OK;
+
+  if (G_UNLIKELY (parse->first))
+    wfd_prepare_src_pad (base, parse);
+
+  if (G_UNLIKELY (parse->first)) {
+    parse->pending_buffers = g_list_append (parse->pending_buffers, buffer);
+    return GST_FLOW_OK;
+  }
+
+  if (G_UNLIKELY (parse->pending_buffers)) {
+    GList *l;
+
+    for (l = parse->pending_buffers; l; l = l->next) {
+      if (ret == GST_FLOW_OK)
+        ret = gst_pad_push (parse->srcpad, l->data);
+      else
+        gst_buffer_unref (l->data);
+    }
+    g_list_free (parse->pending_buffers);
+    parse->pending_buffers = NULL;
+
+    if (ret != GST_FLOW_OK) {
+      gst_buffer_unref (buffer);
+      return ret;
+    }
+  }
+
+  return gst_pad_push (parse->srcpad, buffer);
+}
+
+static WFDTSParsePad *
+wfd_find_pad_for_program (WFDTSParse * parse, guint program_number)
+{
+  GList *tmp;
+
+  for (tmp = parse->srcpads; tmp; tmp = tmp->next) {
+    WFDTSParsePad *tspad = gst_pad_get_element_private ((GstPad *) tmp->data);
+
+    if (tspad->program_number == program_number)
+      return tspad;
+  }
+
+  return NULL;
+}
+
+static void
+wfd_ts_parse_program_started (WFDTSBase * base, WFDTSBaseProgram * program)
+{
+  WFDTSParse *parse = GST_WFD_TS_PARSE (base);
+  WFDTSParseProgram *parseprogram = (WFDTSParseProgram *) program;
+  WFDTSParsePad *tspad;
+
+  /* If we have a request pad for that program, activate it */
+  tspad = wfd_find_pad_for_program (parse, program->program_number);
+
+  if (tspad) {
+    tspad->program = parseprogram;
+    parseprogram->tspad = tspad;
+  }
+}
+
+static void
+wfd_ts_parse_program_stopped (WFDTSBase * base, WFDTSBaseProgram * program)
+{
+  WFDTSParse *parse = GST_WFD_TS_PARSE (base);
+  WFDTSParseProgram *parseprogram = (WFDTSParseProgram *) program;
+  WFDTSParsePad *tspad;
+
+  /* If we have a request pad for that program, activate it */
+  tspad = wfd_find_pad_for_program (parse, program->program_number);
+
+  if (tspad) {
+    tspad->program = NULL;
+    parseprogram->tspad = NULL;
+  }
+}
+
+static gboolean
+wfd_ts_parse_src_pad_query (GstPad * pad, GstObject * parent, GstQuery * query)
+{
+  WFDTSParse *parse = GST_WFD_TS_PARSE (parent);
+  gboolean res;
+
+  switch (GST_QUERY_TYPE (query)) {
+    case GST_QUERY_LATENCY:
+    {
+      if ((res = gst_pad_peer_query (((WFDTSBase *) parse)->sinkpad, query))) {
+        gboolean is_live;
+        GstClockTime min_latency, max_latency;
+
+        gst_query_parse_latency (query, &is_live, &min_latency, &max_latency);
+        if (is_live) {
+          min_latency += TS_LATENCY * GST_MSECOND;
+          if (max_latency != GST_CLOCK_TIME_NONE)
+            max_latency += TS_LATENCY * GST_MSECOND;
+        }
+
+        gst_query_set_latency (query, is_live, min_latency, max_latency);
+      }
+
+      break;
+    }
+    default:
+      res = gst_pad_query_default (pad, parent, query);
+  }
+  return res;
+}
+
+gboolean
+gst_wfdtsparse_plugin_init (GstPlugin * plugin)
+{
+  GST_DEBUG_CATEGORY_INIT (wfd_ts_parse_debug, "wfdtsparse", 0,
+      "Wi-Fi Display transport stream parser");
+
+  return gst_element_register (plugin, "wfdtsparse",
+      GST_RANK_NONE, GST_TYPE_WFD_TS_PARSE);
+}
diff --git a/wfdtsdemux/wfdtsparse.h b/wfdtsdemux/wfdtsparse.h
new file mode 100755 (executable)
index 0000000..bcc9050
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * wfdtsparse.h - GStreamer MPEG transport stream parser
+ * Copyright (C) 2007 Alessandro Decina
+ *
+ * Authors:
+ *   Alessandro Decina <alessandro@nnva.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+
+#ifndef GST_WFD_TS_PARSE_H
+#define GST_WFD_TS_PARSE_H
+
+#include <gst/gst.h>
+#include "wfdtsbase.h"
+#include "wfdtspacketizer.h"
+
+G_BEGIN_DECLS
+
+#define GST_TYPE_WFD_TS_PARSE \
+  (wfd_ts_parse_get_type())
+#define GST_WFD_TS_PARSE(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_WFD_TS_PARSE,WFDTSParse))
+#define GST_WFD_TS_PARSE_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_WFD_TS_PARSE,WFDTSParseClass))
+#define GST_IS_WFD_TS_PARSE(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_WFD_TS_PARSE))
+#define GST_IS_WFD_TS_PARSE_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_WFD_TS_PARSE))
+
+typedef struct _WFDTSParse WFDTSParse;
+typedef struct _WFDTSParseClass WFDTSParseClass;
+
+struct _WFDTSParse {
+  WFDTSBase parent;
+
+  gboolean have_group_id;
+  guint group_id;
+
+  /* Always present source pad */
+  GstPad *srcpad;
+
+  GList *srcpads;
+
+  /* state */
+  gboolean first;
+  GList *pending_buffers;
+};
+
+struct _WFDTSParseClass {
+  WFDTSBaseClass parent_class;
+};
+
+G_GNUC_INTERNAL GType wfd_ts_parse_get_type(void);
+
+G_GNUC_INTERNAL gboolean gst_wfdtsparse_plugin_init (GstPlugin * plugin);
+
+G_END_DECLS
+
+#endif /* GST_WFD_TS_PARSE_H */
diff --git a/xvimagesrc/Makefile.am b/xvimagesrc/Makefile.am
new file mode 100644 (file)
index 0000000..af437a6
--- /dev/null
@@ -0,0 +1 @@
+SUBDIRS = src
diff --git a/xvimagesrc/src/Makefile.am b/xvimagesrc/src/Makefile.am
new file mode 100644 (file)
index 0000000..fa8c2e6
--- /dev/null
@@ -0,0 +1,26 @@
+# plugindir is set in configure
+
+##############################################################################
+# change libgstplugin.la to something more suitable, e.g. libmysomething.la  #
+##############################################################################
+plugin_LTLIBRARIES = libgstxvimagesrc.la
+
+##############################################################################
+# for the next set of variables, rename the prefix if you renamed the .la,   #
+#  e.g. libgstplugin_la_SOURCES => libmysomething_la_SOURCES                 #
+#       libgstplugin_la_CFLAGS  => libmysomething_la_CFLAGS                  #
+#       libgstplugin_la_LIBADD  => libmysomething_la_LIBADD                  #
+#       libgstplugin_la_LDFLAGS => libmysomething_la_LDFLAGS                 #
+##############################################################################
+
+# sources used to compile this plug-in
+libgstxvimagesrc_la_SOURCES = gstxvimagesrc.c
+
+# flags used to compile this plugin
+# add other _CFLAGS and _LIBS as needed
+libgstxvimagesrc_la_CFLAGS = $(GST_CFLAGS)  $(GST_PLUGINS_BASE_CFLAGS) $(GST_BASE_CFLAGS) $(TBM_CFLAGS) $(DRI2_CFLAGS) $(X11_CFLAGS) $(XEXT_CFLAGS) $(XV_CFLAGS) $(XDAMAGE_CFLAGS) $(DRM_DEVEL_CFLAGS) $(DRM_CFLAGS) $(MMCOMMON_CFLAGS)
+libgstxvimagesrc_la_LIBADD = $(GST_LIBS) $(GST_PLUGINS_BASE_LIBS) $(GST_BASE_LIBS) $(TBM_LIBS)$(DRI2_LIBS) $(X11_LIBS) $(XEXT_LIBS) $(XV_LIBS) $(XDAMAGE_LIBS) $(DRM_LIBS) $(DRM_DEVEL_LIBS)
+libgstxvimagesrc_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gstxvimagesrc.h
diff --git a/xvimagesrc/src/gstxvimagesrc.c b/xvimagesrc/src/gstxvimagesrc.c
new file mode 100644 (file)
index 0000000..b2ce9b0
--- /dev/null
@@ -0,0 +1,1934 @@
+/*
+ * xvimagesrc
+ *
+ * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Hyunjun Ko <zzoon.ko@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+/**
+* SECTION:element-xvimagesrc
+*
+* xvimagesrc captures frame buffer which includes the application data along with video layer data
+* from the XServer and pushes the data to the downstream element.
+*
+*
+* <refsect2>
+* <title>Example launch line</title>
+* |[
+* gst-launch xvimagesrc ! "video/x-raw, width=720, height=1280, framerate=(fraction)30/1, format=(string)ST12" ! fakesink
+* ]| captures the frame buffer from the XServer and send the buffers to a fakesink.
+* </refsect2>
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "gstxvimagesrc.h"
+
+/* headers for drm */
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <X11/Xmd.h>
+#include <X11/Xlibint.h>
+#include <dri2.h>
+#include <drm.h>
+#include <sys/time.h>
+#include <sys/times.h>
+#include <xf86drm.h>
+#include <sys/mman.h>
+#include <exynos_drm.h>
+#include <mm_types.h>
+
+GST_DEBUG_CATEGORY_STATIC (xvimagesrc_debug);
+#define GST_CAT_DEFAULT xvimagesrc_debug
+
+#define GST_XV_IMAGE_SRC_CAPS                    \
+  "video/x-raw, "                                \
+  "format = (string) RGBx, "                     \
+  "width  = (int)  [ 16, 4096 ], "               \
+  "height = (int)  [ 16, 4096 ], "               \
+  "framerate = (fraction) [0/1, 2147483647/1];"  \
+  "video/x-raw,"                                 \
+  "format = (string) { SN12, ST12 }, "           \
+  "width = (int) [ 1, 4096 ], "                  \
+  "height = (int) [ 1, 4096 ], "                 \
+  "framerate = (fraction) [0/1, 2147483647/1];"
+
+static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
+    GST_PAD_SRC,
+    GST_PAD_ALWAYS,
+    GST_STATIC_CAPS (GST_XV_IMAGE_SRC_CAPS)
+    );
+
+enum
+{
+  PROP_0
+};
+
+enum
+{
+  VIDEO_TYPE_VIDEO_WITH_UI,
+  VIDEO_TYPE_VIDEO_ONLY,
+};
+
+enum
+{
+  SIGNAL_VIDEO_WITH_UI = 0,
+  SIGNAL_VIDEO_ONLY,
+  SIGNAL_SELECTION_NOTIFY,
+  SIGNAL_LAST
+};
+
+#define GEM_NAME_MAX                10
+
+#define SCMN_CS_YUV420              1   /* Y:U:V 4:2:0 */
+#define SCMN_CS_I420                SCMN_CS_YUV420      /* Y:U:V */
+#define SCMN_CS_NV12                6
+#define SCMN_CS_NV12_T64X32         11  /* 64x32 Tiled NV12 type */
+#define SCMN_CS_UYVY                100
+#define SCMN_CS_YUYV                101
+#define SCMN_CS_YUY2                SCMN_CS_YUYV
+
+typedef struct
+{
+  void *address[GEM_NAME_MAX];
+  int buffer_size[GEM_NAME_MAX];
+  int name[GEM_NAME_MAX];
+  gint32 fd[GEM_NAME_MAX];
+  gint32 handle[GEM_NAME_MAX];
+} GEM_MMAP;
+
+typedef enum
+{
+  BUF_SHARE_METHOD_PADDR = 0,
+  BUF_SHARE_METHOD_FD,
+  BUF_SHARE_METHOD_TIZEN_BUFFER
+} buf_share_method_t;
+
+typedef struct GstXvImageOutBuffer GstXvImageOutBuffer;
+
+struct GstXvImageOutBuffer
+{
+  GstBuffer *buffer;
+  int fd_name;
+  unsigned int YBuf;
+  tbm_bo bo[2];
+  GstXVImageSrc *xvimagesrc;
+};
+
+static guint gst_xv_image_src_signals[SIGNAL_LAST] = { 0 };
+
+static const char fake_edid_info[] = {
+    0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x4c, 0x2d, 0x05, 0x05,
+    0x00, 0x00, 0x00, 0x00, 0x30, 0x12, 0x01, 0x03, 0x80, 0x10, 0x09, 0x78,
+    0x0a, 0xee, 0x91, 0xa3, 0x54, 0x4c, 0x99, 0x26, 0x0f, 0x50, 0x54, 0xbd,
+    0xee, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x66, 0x21, 0x50, 0xb0, 0x51, 0x00,
+    0x1b, 0x30, 0x40, 0x70, 0x36, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x1e,
+    0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00,
+    0xa0, 0x5a, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x18,
+    0x4b, 0x1a, 0x44, 0x17, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+    0x00, 0x00, 0x00, 0xfc, 0x00, 0x53, 0x41, 0x4d, 0x53, 0x55, 0x4e, 0x47,
+    0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0xbc, 0x02, 0x03, 0x1e, 0xf1,
+    0x46, 0x84, 0x05, 0x03, 0x10, 0x20, 0x22, 0x23, 0x09, 0x07, 0x07, 0x83,
+    0x01, 0x00, 0x00, 0xe2, 0x00, 0x0f, 0x67, 0x03, 0x0c, 0x00, 0x10, 0x00,
+    0xb8, 0x2d, 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c,
+    0x25, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x9e, 0x8c, 0x0a, 0xd0, 0x8a,
+    0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0xa0, 0x5a, 0x00, 0x00,
+    0x00, 0x18, 0x02, 0x3a, 0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c,
+    0x45, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x06
+};
+
+//#define _MAKE_DUMP
+#ifdef _MAKE_DUMP
+#define YUV_FRAME_SIZE 3110400
+#define YUV_720_FRAME_SIZE 1382400
+#define YUV_VGA_FRAME_SIZE 460800
+
+static int g_prev_frame[YUV_FRAME_SIZE] = { 0, };
+
+static unsigned char g_dump_frame[100][921600];
+static unsigned char g_dump_frame1[100][462848];
+//static int g_dump_frame[100][YUV_720_FRAME_SIZE];
+//static int g_dump_frame[200][YUV_VGA_FRAME_SIZE];
+static int f_idx = 0;
+static int f_done = 0;
+#endif
+
+//#define COUNT_FRAMES
+#define BASE_TIME 33000
+#define LIMIT_TIME -33000
+
+#ifdef COUNT_FRAMES
+gchar old_time[10] = { 0, };
+#endif
+
+static gboolean error_caught = FALSE;
+
+#define BUFFER_COND_WAIT_TIMEOUT            (1 * G_TIME_SPAN_SECOND)
+//#define GST_TYPE_GST_XV_IMAGE_OUT_BUFFER               (gst_xv_image_out_buffer_get_type())
+//#define GST_IS_GST_XV_IMAGE_OUT_BUFFER(obj)            (G_TYPE_CHECK_INSTANCE_TYPE((obj), GST_TYPE_GST_XV_IMAGE_OUT_BUFFER))
+//static void gst_xv_image_out_buffer_finalize (GstXvImageOutBuffer * buffer);
+static GstXvImageOutBuffer *gst_xv_image_out_buffer_new (GstXVImageSrc * src);
+
+static void gst_xv_image_src_finalize (GObject * gobject);
+
+static void gst_xv_image_src_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec);
+static void gst_xv_image_src_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec);
+static GstFlowReturn gst_xv_image_src_create (GstPushSrc * psrc,
+    GstBuffer ** outbuf);
+static GstStateChangeReturn gst_xv_image_src_change_state (GstElement * element,
+    GstStateChange transition);
+static gboolean gst_xv_image_src_start (GstBaseSrc * bsrc);
+static gboolean gst_xv_image_src_stop (GstBaseSrc * bsrc);
+static gboolean gst_xv_image_src_get_size (GstBaseSrc * bsrc, guint64 * size);
+static gboolean gst_xv_image_src_is_seekable (GstBaseSrc * bsrc);
+static gboolean gst_xv_image_src_query (GstBaseSrc * bsrc, GstQuery * query);
+static gboolean gst_xv_image_src_unlock (GstBaseSrc * bsrc);
+static gboolean gst_xv_image_src_unlock_stop (GstBaseSrc * bsrc);
+static gboolean gst_xv_image_src_setcaps (GstBaseSrc * bsrc, GstCaps * caps);
+
+static tbm_bufmgr bufmgr_get (Display * dpy, Pixmap pixmap);
+static int port_get (GstXVImageSrc * src, unsigned int id);
+static void pixmap_update (GstXVImageSrc * src, Display * dpy,
+    tbm_bufmgr bufmgr, Pixmap pixmap, int x, int y, int width, int height);
+static Pixmap pixmap_create (GstXVImageSrc * src, Display * dpy, int width,
+    int height);
+
+static void *gst_xv_image_src_update_thread (void *asrc);
+static gboolean xvimagesrc_thread_start (GstXVImageSrc * src);
+static void drm_init (GstXVImageSrc * src);
+static void drm_finalize (GstXVImageSrc * src);
+static tbm_bo drm_convert_gem_to_bo (tbm_bufmgr bufmgr, unsigned int gem_name);
+static gint32 drm_convert_gem_to_fd (int *gemname_cnt, int drm_fd,
+    unsigned int name, void *data, void **virtual_address, guint * buf_size);
+static void gst_xv_get_image_sleep (void *asrc, long duration);
+
+static void
+_do_init (GType type)
+{
+  GST_DEBUG_CATEGORY_INIT (xvimagesrc_debug, "xvimagesrc", 0, "Xv image src");
+}
+
+#define gst_xv_image_src_parent_class parent_class
+G_DEFINE_TYPE_WITH_CODE (GstXVImageSrc, gst_xv_image_src, GST_TYPE_PUSH_SRC,
+    _do_init (G_TYPE_INVALID));
+
+//G_DEFINE_BOXED_TYPE (GstXvImageOutBuffer, gst_xv_image_out_buffer, NULL,
+//    gst_xv_image_out_buffer_finalize);
+
+#ifdef DEBUG_BUFFER
+int value[5] = { 0 };
+
+static int value_count = 0;
+#endif
+
+
+static GstXvImageOutBuffer *
+gst_xv_image_out_buffer_new (GstXVImageSrc * src)
+{
+  GstXvImageOutBuffer *newbuf = NULL;
+  GST_LOG ("gst_xv_image_out_buffer_new");
+
+  newbuf = (GstXvImageOutBuffer *) malloc (sizeof (GstXvImageOutBuffer));
+  if (!newbuf) {
+    GST_ERROR ("gst_xv_image_out_buffer_new out of memory");
+    return NULL;
+  }
+  GST_LOG ("creating buffer : %p", newbuf);
+  newbuf->buffer = gst_buffer_new ();
+  newbuf->xvimagesrc = gst_object_ref (GST_OBJECT (src));
+  newbuf->fd_name = 0;
+  newbuf->YBuf = 0;
+  newbuf->bo[0] = NULL;
+  newbuf->bo[1] = NULL;
+  return newbuf;
+}
+
+static void
+gst_xv_image_src_class_init (GstXVImageSrcClass * klass)
+{
+  GObjectClass *gobject_class;
+  GstElementClass *gstelement_class;
+  GstBaseSrcClass *gstbasesrc_class;
+  GstPushSrcClass *gstpushsrc_class;
+  gobject_class = G_OBJECT_CLASS (klass);
+  gstelement_class = GST_ELEMENT_CLASS (klass);
+  gstbasesrc_class = (GstBaseSrcClass *) klass;
+  gstpushsrc_class = (GstPushSrcClass *) klass;
+  gobject_class->set_property = gst_xv_image_src_set_property;
+  gobject_class->get_property = gst_xv_image_src_get_property;
+  gobject_class->finalize = gst_xv_image_src_finalize;
+
+  gst_element_class_add_pad_template (gstelement_class,
+      gst_static_pad_template_get (&srctemplate));
+  gst_element_class_set_details_simple (gstelement_class,
+      "XServer Display FB video source", "Source/video",
+      "Receive frame buffer data from XServer and passes to next element",
+      "Hyunjun Ko <zzoon.ko@samsung.com>");
+
+  gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_xv_image_src_start);
+  gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_xv_image_src_stop);
+  gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_xv_image_src_unlock);
+  gstbasesrc_class->unlock_stop =
+      GST_DEBUG_FUNCPTR (gst_xv_image_src_unlock_stop);
+  gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_xv_image_src_get_size);
+  gstbasesrc_class->is_seekable =
+      GST_DEBUG_FUNCPTR (gst_xv_image_src_is_seekable);
+  gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_xv_image_src_query);
+  gstbasesrc_class->set_caps = GST_DEBUG_FUNCPTR (gst_xv_image_src_setcaps);
+  gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_xv_image_src_create);
+  gstelement_class->change_state =
+      GST_DEBUG_FUNCPTR (gst_xv_image_src_change_state);
+
+  gst_xv_image_src_signals[SIGNAL_VIDEO_WITH_UI] =
+      g_signal_new ("video-with-ui", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstXVImageSrcClass, video_with_ui),
+      NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  gst_xv_image_src_signals[SIGNAL_VIDEO_ONLY] =
+      g_signal_new ("video-only", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
+      G_STRUCT_OFFSET (GstXVImageSrcClass, video_only), NULL, NULL,
+      g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+
+  gst_xv_image_src_signals[SIGNAL_SELECTION_NOTIFY] =
+      g_signal_new ("selection-notify", G_TYPE_FROM_CLASS (klass),
+      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstXVImageSrcClass, selection_notify),
+      NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
+}
+
+static GstStateChangeReturn
+gst_xv_image_src_change_state (GstElement * element, GstStateChange transition)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (element);
+
+  GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
+
+  switch (transition) {
+    case GST_STATE_CHANGE_NULL_TO_READY:
+      GST_WARNING_OBJECT (src, "GST_STATE_CHANGE_NULL_TO_READY");
+      break;
+    case GST_STATE_CHANGE_READY_TO_PAUSED:
+      GST_WARNING_OBJECT (src, "GST_STATE_CHANGE_READY_TO_PAUSED");
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
+      GST_WARNING_OBJECT (src, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
+      src->pause_cond_var = FALSE;
+      g_cond_signal(&src->pause_cond);
+      break;
+    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
+      GST_WARNING_OBJECT (src, "GST_STATE_CHANGE_PLAYING_TO_PAUSED: START");
+      src->pause_cond_var = TRUE;
+      GST_WARNING_OBJECT (src, "GST_STATE_CHANGE_PLAYING_TO_PAUSED: End");
+      break;
+    case GST_STATE_CHANGE_PAUSED_TO_READY:
+      GST_WARNING_OBJECT (src, "GST_STATE_CHANGE_PAUSED_TO_READY");
+      src->thread_return = TRUE;
+      g_cond_signal(&src->pause_cond);
+      break;
+    case GST_STATE_CHANGE_READY_TO_NULL:
+      break;
+    default:
+      break;
+  }
+
+  result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
+
+  return result;
+}
+
+static gboolean
+gst_xv_image_src_get_frame_size (int fourcc, int width, int height,
+    unsigned int *outsize)
+{
+  switch (fourcc) {
+/* case GST_MAKE_FOURCC('I','4','2','0'):      // V4L2_PIX_FMT_YUV420
+    *outsize = GST_ROUND_UP_4 (width) * GST_ROUND_UP_2 (height);
+    *outsize += 2 * ((GST_ROUND_UP_8 (width) / 2) * (GST_ROUND_UP_2 (height) / 2));
+    break;*/
+    case GST_MAKE_FOURCC ('S', 'N', '1', '2'): // V4L2_PIX_FMT_NV12 non-linear
+    case GST_MAKE_FOURCC ('S', 'T', '1', '2'): // V4L2_PIX_FMT_NV12 tiled non-linear
+      GST_INFO ("SN12 or ST12");
+      *outsize = GST_ROUND_UP_4 (width) * GST_ROUND_UP_2 (height);
+      *outsize += (GST_ROUND_UP_4 (width) * height) / 2;
+      break;
+    case GST_MAKE_FOURCC ('R', 'G', 'B', '4'):
+      /* jpeg size can't be calculated here. */
+      *outsize = width * height * 4;
+      break;
+    default:
+      /* unkown format!! */
+      *outsize = 0;
+      return FALSE;
+  }
+  return TRUE;
+}
+
+static gboolean
+gst_xv_image_src_parse_caps (const GstCaps * caps, guint32 * fourcc,
+    gint * width, gint * height, gint * rate_numerator, gint * rate_denominator,
+    unsigned int *framesize)
+{
+  const GstStructure *structure;
+  GstPadLinkReturn ret = TRUE;
+  const GValue *framerate;
+  const char *media_type = NULL;
+
+  if (gst_caps_get_size (caps) < 1)
+    return FALSE;
+
+  GST_INFO ("xvimagesrc src caps:%" GST_PTR_FORMAT, caps);
+
+  structure = gst_caps_get_structure (caps, 0);
+  ret = gst_structure_get_int (structure, "width", width);
+  if (!ret) {
+    GST_ERROR ("xvimagesrc width not specified in caps");
+    goto error;
+  }
+
+  ret = gst_structure_get_int (structure, "height", height);
+  if (!ret) {
+    GST_ERROR ("xvimagesrc height not specified in caps");
+    goto error;
+  }
+
+  media_type = gst_structure_get_name (structure);
+  if (media_type == NULL) {
+    GST_ERROR ("xvimagesrc media type not specified in caps");
+    goto error;
+  }
+
+  framerate = gst_structure_get_value (structure, "framerate");
+  if (framerate) {
+    *rate_numerator = gst_value_get_fraction_numerator (framerate);
+    *rate_denominator = gst_value_get_fraction_denominator (framerate);
+  } else {
+    GST_ERROR ("xvimagesrc frametype not specified in caps");
+    goto error;
+  }
+
+  if (g_strcmp0 (media_type, "video/x-raw") == 0) {
+    GST_INFO ("media_type is video/x-raw");
+    guint32 format = FOURCC_SN12;
+
+#if 0
+    ret = gst_structure_get_uint (structure, "format", &format);
+    if (!ret)
+      GST_DEBUG
+          ("xvimagesrc format not specified in caps, SN12 selected as default");
+#endif
+    const gchar * sformat = NULL;
+
+    sformat = gst_structure_get_string(structure, "format");
+    if (!sformat) {
+      GST_WARNING ("xvimagesrc format not specified in caps");
+    } else {
+      format = FOURCC(sformat[0],sformat[1],sformat[2],sformat[3]);
+    }
+
+    ret = gst_xv_image_src_get_frame_size (format, *width, *height, framesize);
+    if (!ret) {
+      GST_ERROR ("xvimagesrc unsupported format type specified in caps");
+      goto error;
+    }
+
+    *fourcc = format;
+  }
+  return TRUE;
+/* ERRORS */
+error:
+  return FALSE;
+}
+
+static gboolean
+gst_xv_image_src_setcaps (GstBaseSrc * bsrc, GstCaps * caps)
+{
+  gboolean res = TRUE;
+  gint width, height, rate_denominator, rate_numerator;
+  GstXVImageSrc *src;
+
+  src = GST_XV_IMAGE_SRC (bsrc);
+
+  res = gst_xv_image_src_parse_caps (caps, &src->format_id, &width, &height,
+      &rate_numerator, &rate_denominator, &src->framesize);
+  if (res) {
+    /* looks ok here */
+    src->width = width;
+    src->height = height;
+    src->rate_numerator = rate_numerator;
+    src->rate_denominator = rate_denominator;
+    GST_DEBUG_OBJECT (src, "size %dx%d, %d/%d fps, framesize : %d",
+        src->width, src->height,
+        src->rate_numerator, src->rate_denominator, src->framesize);
+
+    if (src->rate_numerator) {
+      src->sleep_base_time =
+          (long) (((int) (1000 / src->rate_numerator)) * 1000);
+      src->sleep_limit_time = (long) (-1 * src->sleep_base_time);
+    }
+  }
+
+  xvimagesrc_thread_start (src);
+  return res;
+}
+
+static void
+gst_xv_image_src_init (GstXVImageSrc * src)
+{
+  src->format_id = 0;
+  src->running_time = GST_CLOCK_TIME_NONE;
+  src->frame_duration = GST_CLOCK_TIME_NONE;
+  src->virtual = NULL;
+  src->pixmap = 0;
+  src->gc = NULL;
+  src->bo = NULL;
+  src->dri2_buffers = NULL;
+  src->buf_share_method = BUF_SHARE_METHOD_TIZEN_BUFFER;
+  g_mutex_init (&src->queue_lock);
+  src->queue = g_queue_new ();
+  g_cond_init (&src->queue_cond);
+  g_mutex_init (&src->cond_lock);
+
+  g_cond_init (&src->buffer_cond);
+  g_mutex_init (&src->buffer_cond_lock);
+  g_mutex_init (&src->dpy_lock);
+
+  src->pause_cond_var = FALSE;
+  g_cond_init (&src->pause_cond);
+  g_mutex_init (&src->pause_lock);
+
+  src->drm_fd = -1;
+  src->current_data_type = VIDEO_TYPE_VIDEO_WITH_UI;
+  src->new_data_type = VIDEO_TYPE_VIDEO_WITH_UI;
+  src->get_image_overtime = 0;
+  src->get_image_overtime_cnt = 0;
+  src->gemname_cnt = 0;
+  src->tz_enable = 0;
+  src->sleep_base_time = 0;
+  src->sleep_limit_time = 0;
+
+  drm_init (src);
+  gst_base_src_set_live (GST_BASE_SRC (src), TRUE);
+}
+
+static void
+gst_xv_image_src_finalize (GObject * gobject)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (gobject);
+  GST_DEBUG_OBJECT (src, "finalize");
+  g_mutex_clear (&src->queue_lock);
+  g_mutex_clear (&src->pause_lock);
+  g_mutex_clear (&src->dpy_lock);
+  g_mutex_clear (&src->cond_lock);
+  g_mutex_clear (&src->buffer_cond_lock);
+  drm_finalize (src);
+  G_OBJECT_CLASS (parent_class)->finalize (gobject);
+}
+
+static void
+drm_init (GstXVImageSrc * src)
+{
+  Display *dpy;
+  int eventBase, errorBase;
+  int dri2Major, dri2Minor;
+  char *driverName, *deviceName;
+  struct drm_auth auth_arg = { 0 };
+
+  src->drm_fd = -1;
+  dpy = XOpenDisplay (0);
+
+  /* DRI2 */
+  if (!DRI2QueryExtension (dpy, &eventBase, &errorBase)) {
+    GST_ERROR ("DRI2QueryExtension !!");
+    return;
+  }
+  if (!DRI2QueryVersion (dpy, &dri2Major, &dri2Minor)) {
+    GST_ERROR ("DRI2QueryVersion !!");
+    return;
+  }
+  if (!DRI2Connect (dpy, RootWindow (dpy, DefaultScreen (dpy)), &driverName,
+          &deviceName)) {
+    GST_ERROR ("DRI2Connect !!");
+    return;
+  }
+  GST_INFO ("Open drm device : %s", deviceName);
+
+  /* get the drm_fd though opening the deviceName */
+  src->drm_fd = open (deviceName, O_RDWR);
+  if (src->drm_fd < 0) {
+    GST_ERROR ("cannot open drm device (%s)", deviceName);
+    return;
+  }
+
+  /* get magic from drm to authentication */
+  if (ioctl (src->drm_fd, DRM_IOCTL_GET_MAGIC, &auth_arg)) {
+    GST_ERROR ("cannot get drm auth magic");
+    close (src->drm_fd);
+    src->drm_fd = -1;
+    return;
+  }
+  if (!DRI2Authenticate (dpy, RootWindow (dpy, DefaultScreen (dpy)),
+          auth_arg.magic)) {
+    GST_ERROR ("cannot get drm authentication from X");
+    close (src->drm_fd);
+    src->drm_fd = -1;
+    return;
+  }
+}
+
+static void
+drm_finalize (GstXVImageSrc * src)
+{
+  if (src->drm_fd >= 0) {
+    close (src->drm_fd);
+    src->drm_fd = -1;
+  }
+}
+
+static tbm_bo
+drm_convert_gem_to_bo (tbm_bufmgr bufmgr, unsigned int gem_name)
+{
+  tbm_bo ret = NULL;
+
+  ret = tbm_bo_import (bufmgr, gem_name);
+  if (ret == NULL) {
+    GST_ERROR ("[Error] : cannot import bo (key:%d)", gem_name);
+  }
+
+  return ret;
+}
+
+static gint32
+drm_convert_gem_to_fd (int *gemname_cnt, int drm_fd, unsigned int name,
+    void *data, void **virtual_address, guint * buf_size)
+{
+  g_return_val_if_fail ((data != NULL), 0);
+  int count = 0;
+  gint32 fd = 0;
+  count = *gemname_cnt;
+  GST_DEBUG ("gamname_cnt = %d", count);
+  GST_DEBUG ("name = %u", name);
+
+
+  GEM_MMAP *xv_gem_mmap = NULL;
+  xv_gem_mmap = (GEM_MMAP *) data;
+
+  if (count < GEM_NAME_MAX) {
+    int i = 0;
+
+    for (i = 0; i < GEM_NAME_MAX; i++) {
+      if (name == xv_gem_mmap->name[i])
+        goto PASS;
+    }
+
+    struct drm_prime_handle prime;
+    struct drm_gem_open gem_open;
+    struct drm_exynos_gem_mmap gem_mmap;        //for virtual address
+
+    memset (&gem_open, 0, sizeof (struct drm_gem_open));
+    gem_open.name = name;
+    if (ioctl (drm_fd, DRM_IOCTL_GEM_OPEN, &gem_open)) {
+      GST_ERROR ("Gem Open failed");
+      return 0;
+    }
+
+    memset (&prime, 0, sizeof (struct drm_prime_handle));
+    prime.handle = gem_open.handle;
+    prime.flags = DRM_CLOEXEC;
+
+    /*get gem_open handle */
+    xv_gem_mmap->handle[count] = gem_open.handle;
+    GST_DEBUG ("gem_open.handle =%d, xv_gem_mmap->handle[count]=%d",
+        gem_open.handle, xv_gem_mmap->handle[count]);
+
+    /*get virtual address */
+    /*set name */
+    xv_gem_mmap->name[count] = name;
+    memset (&gem_mmap, 0, sizeof (struct drm_exynos_gem_mmap));
+    gem_mmap.handle = prime.handle;
+    gem_mmap.size = gem_open.size;
+
+    /*set size */
+    xv_gem_mmap->buffer_size[count] = gem_mmap.size;
+    if (drmIoctl (drm_fd, DRM_IOCTL_EXYNOS_GEM_MMAP, &gem_mmap) != 0) {
+      GST_ERROR ("Gem mmap failed [handle %d, size %lld]", gem_mmap.handle,
+          gem_mmap.size);
+      return 0;
+    }
+
+    /*set virtual address */
+    xv_gem_mmap->address[count] = (void *) (gem_mmap.mapped);
+    GST_DEBUG ("%u - Virtual address[%d] = %p size=%d ", name, count,
+        xv_gem_mmap->address[count], xv_gem_mmap->buffer_size[count]);
+
+    /*get fd */
+    if (ioctl (drm_fd, DRM_IOCTL_PRIME_HANDLE_TO_FD, &prime) < 0) {
+      GST_ERROR ("Gem Handle to Fd failed");
+      return 0;
+    }
+
+    xv_gem_mmap->fd[count] = prime.fd;
+    GST_DEBUG ("fd = %d", xv_gem_mmap->fd[count]);
+  }
+
+  if (count < GEM_NAME_MAX) {
+    count++;
+    *gemname_cnt = count;
+  }
+
+PASS:
+  if (name == xv_gem_mmap->name[0]) {
+    *virtual_address = xv_gem_mmap->address[0];
+    fd = xv_gem_mmap->fd[0];
+    *buf_size = xv_gem_mmap->buffer_size[0];
+  } else if (name == xv_gem_mmap->name[1]) {
+    *virtual_address = xv_gem_mmap->address[1];
+    fd = xv_gem_mmap->fd[1];
+    *buf_size = xv_gem_mmap->buffer_size[1];
+  } else if (name == xv_gem_mmap->name[2]) {
+    *virtual_address = xv_gem_mmap->address[2];
+    fd = xv_gem_mmap->fd[2];
+    *buf_size = xv_gem_mmap->buffer_size[2];
+  } else if (name == xv_gem_mmap->name[3]) {
+    *virtual_address = xv_gem_mmap->address[3];
+    fd = xv_gem_mmap->fd[3];
+    *buf_size = xv_gem_mmap->buffer_size[3];
+  } else if (name == xv_gem_mmap->name[4]) {
+    *virtual_address = xv_gem_mmap->address[4];
+    fd = xv_gem_mmap->fd[4];
+    *buf_size = xv_gem_mmap->buffer_size[4];
+  } else if (name == xv_gem_mmap->name[5]) {
+    *virtual_address = xv_gem_mmap->address[5];
+    fd = xv_gem_mmap->fd[5];
+    *buf_size = xv_gem_mmap->buffer_size[5];
+  } else if (name == xv_gem_mmap->name[6]) {
+    *virtual_address = xv_gem_mmap->address[6];
+    fd = xv_gem_mmap->fd[6];
+    *buf_size = xv_gem_mmap->buffer_size[6];
+  } else if (name == xv_gem_mmap->name[7]) {
+    *virtual_address = xv_gem_mmap->address[7];
+    fd = xv_gem_mmap->fd[7];
+    *buf_size = xv_gem_mmap->buffer_size[7];
+  } else if (name == xv_gem_mmap->name[8]) {
+    *virtual_address = xv_gem_mmap->address[8];
+    fd = xv_gem_mmap->fd[8];
+    *buf_size = xv_gem_mmap->buffer_size[8];
+  } else if (name == xv_gem_mmap->name[9]) {
+    *virtual_address = xv_gem_mmap->address[9];
+    fd = xv_gem_mmap->fd[9];
+    *buf_size = xv_gem_mmap->buffer_size[9];
+  }
+
+  GST_DEBUG ("virtual_address = %p (size: %d) fd = %d",
+      *virtual_address, *buf_size, fd);
+  return fd;
+}
+
+static void
+gst_xv_image_src_set_property (GObject * object, guint prop_id,
+    const GValue * value, GParamSpec * pspec)
+{
+  //GstXVImageSrc *src = GST_XV_IMAGE_SRC (object);
+
+  switch (prop_id) {
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+
+  return;
+}
+
+static void
+gst_xv_image_src_get_property (GObject * object, guint prop_id,
+    GValue * value, GParamSpec * pspec)
+{
+  //GstXVImageSrc *src = GST_XV_IMAGE_SRC (object);
+
+  switch (prop_id) {
+    default:
+      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+      break;
+  }
+
+  return;
+}
+
+static gboolean
+gst_xv_image_src_get_timeinfo (GstXVImageSrc *src, GstClockTime *time, GstClockTime *dur)
+{
+  int fps_nu = 0;
+  int fps_de = 0;
+  GstClockTime timestamp = GST_CLOCK_TIME_NONE;
+  GstClockTime duration = GST_CLOCK_TIME_NONE;
+  static GstClockTime prev_timestamp = 0;
+
+  GstClock *clock;
+  if (!src) {
+    GST_WARNING("Invalid pointer [handle:%p]", src);
+    return FALSE;
+  }
+  clock = gst_element_get_clock (GST_ELEMENT (src));
+  if (clock) {
+    timestamp = gst_clock_get_time (clock);
+    if(!gst_element_get_base_time (GST_ELEMENT(src)))
+      timestamp = GST_CLOCK_TIME_NONE;
+    else timestamp -= gst_element_get_base_time (GST_ELEMENT (src));
+    gst_object_unref (clock);
+  } else {
+    /* not an error not to have a clock */
+    timestamp = GST_CLOCK_TIME_NONE;
+  }
+
+  if ((timestamp - prev_timestamp <= 30000000) || (timestamp-prev_timestamp >=36000000)) {
+    /*GST_ERROR("Gap is below 30ms or over 36ms!!");*/
+  }
+
+  /* if we have a framerate adjust timestamp for frame latency */
+  if ((int)((float)src->rate_numerator / (float)src->rate_denominator) <= 0) {
+    /*if fps is zero, auto fps mode*/
+    fps_nu = 0;
+    fps_de = 1;
+  } else {
+    fps_nu = 1;
+    fps_de = (int)((float)src->rate_numerator / (float)src->rate_denominator);
+  }
+  if (fps_nu > 0 && fps_de > 0) {
+    GstClockTime latency;
+    latency = gst_util_uint64_scale_int(GST_SECOND, fps_nu, fps_de);
+    duration = latency;
+  }
+  //timestamp+=src->initial_audio_latency;
+  *time = timestamp;
+  *dur = duration;
+  prev_timestamp = timestamp;
+  return TRUE;
+}
+
+#ifdef COUNT_FRAMES
+static int fps = 0;
+
+static gchar *
+get_current_system_time ()
+{
+  gchar target[10] = { 0, };
+  time_t t;
+  struct tm tm;
+
+  t = time (NULL);
+  tzset ();
+  /*localtimer_r : available since libc 5.2.5 */
+  if (localtime_r (&t, &tm) == NULL) {
+    return NULL;
+  }
+  snprintf (target, sizeof (target), "%02i:%02i:%02i", tm.tm_hour, tm.tm_min,
+      tm.tm_sec);
+  return g_strdup (target);
+}
+#endif
+
+#define XVIMAGESRC_SLEEP(msec) \
+do { \
+  if(msec) { \
+    unsigned long sec_t = 0; \
+    unsigned long nsec_t = 0; \
+    unsigned long cal_time = msec * 1000000; \
+    sec_t = cal_time / 1000000000; \
+    nsec_t = cal_time % 1000000000; \
+    struct timespec reqtime; \
+    reqtime.tv_sec = sec_t; \
+    reqtime.tv_nsec = nsec_t; \
+    nanosleep(&reqtime, NULL); \
+  } \
+} while (0)
+
+static void
+gst_xv_get_image_sleep (void *asrc, long duration)
+{
+  GST_INFO ("end_time duration=%ld", duration);
+  if (duration < 0)
+    return;
+
+  GstXVImageSrc *src = (GstXVImageSrc *) asrc;
+  g_return_if_fail (src != NULL);
+
+  long sleep_time = 0;
+  sleep_time = src->sleep_base_time - duration;
+
+  if (sleep_time < 0) {
+    src->get_image_overtime_cnt++;
+    src->get_image_overtime += sleep_time;
+
+    if (src->get_image_overtime_cnt > 2)
+      src->get_image_overtime = 0;
+
+    if (src->get_image_overtime <= src->sleep_limit_time)
+      src->get_image_overtime = 0;
+  } else if (sleep_time > 0) {
+    src->get_image_overtime_cnt = 0;
+    sleep_time = sleep_time + src->get_image_overtime;
+    src->get_image_overtime = (sleep_time < 0) ? sleep_time : 0;
+
+    if (sleep_time > 0) {
+      GST_INFO ("end_time : sleep_time = %ld", sleep_time);
+      sleep_time = sleep_time / 1000;
+      XVIMAGESRC_SLEEP (sleep_time);
+    }
+  }
+}
+
+static GstFlowReturn
+gst_xv_image_src_create (GstPushSrc * psrc, GstBuffer ** buffer)
+{
+  GstXVImageSrc *src;
+  GstXvImageOutBuffer *outbuf = NULL;
+
+  src = GST_XV_IMAGE_SRC (psrc);
+  g_mutex_lock (&src->queue_lock);
+
+  if (g_queue_is_empty (src->queue)) {
+    g_mutex_unlock (&src->queue_lock);
+    g_mutex_lock (&src->cond_lock);
+    g_cond_wait (&src->queue_cond, &src->cond_lock);
+    g_mutex_unlock (&src->cond_lock);
+
+    g_mutex_lock (&src->queue_lock);
+    outbuf = (GstXvImageOutBuffer *) g_queue_pop_head (src->queue);
+    g_mutex_unlock (&src->queue_lock);
+  } else {
+    GstXvImageOutBuffer *tempbuf = NULL;
+    while ((tempbuf =
+            (GstXvImageOutBuffer *) g_queue_pop_head (src->queue)) != NULL) {
+      /* To reduce latency, skipping the old frames and submitting only latest frames */
+      outbuf = tempbuf;
+    }
+    g_mutex_unlock (&src->queue_lock);
+  }
+
+  if (outbuf == NULL)
+    return GST_FLOW_ERROR;
+
+  GST_INFO_OBJECT (src, "gem_name=%d, fd_name=%d, Time stamp of the buffer is %"
+      GST_TIME_FORMAT, outbuf->YBuf, outbuf->fd_name,
+      GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf->buffer)));
+
+  *buffer = outbuf->buffer;
+
+#ifdef COUNT_FRAMES
+  gchar *current_time = NULL;
+  current_time = get_current_system_time ();
+  if (strncmp (current_time, old_time, 10) == 0) {
+    fps++;
+    strncpy (old_time, current_time, 10);
+  } else {
+    g_printf ("xvimagesrc %s - fps : %d\n", old_time, fps);
+    fps = 1;
+    strncpy (old_time, current_time, 10);
+  }
+#endif
+
+  return GST_FLOW_OK;
+}
+
+static gboolean
+xvimagesrc_thread_start (GstXVImageSrc * src)
+{
+  GError *error;
+  if (!src->updates_thread) {
+    src->updates_thread =
+        g_thread_new ("xvimagecapture", (GThreadFunc) gst_xv_image_src_update_thread, src);
+#if 0
+        g_thread_create ((GThreadFunc) gst_xv_image_src_update_thread, src,
+        TRUE, &error);
+#endif
+
+    GST_WARNING_OBJECT (src, "image capture thread start");
+  } else {
+    GST_LOG_OBJECT (src, "The thread function already running");
+  }
+
+  return TRUE;
+}
+
+static gboolean
+gst_xv_image_src_start (GstBaseSrc * bsrc)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  if (src->format_id)
+    xvimagesrc_thread_start (src);
+  return TRUE;
+}
+
+gboolean
+signal_emit_func (void *asrc)
+{
+  GstXVImageSrc *src = (GstXVImageSrc *) asrc;
+  if (src->current_data_type == VIDEO_TYPE_VIDEO_ONLY) {
+    g_signal_emit (src, gst_xv_image_src_signals[SIGNAL_VIDEO_ONLY], 0, NULL);
+  } else if (src->current_data_type == VIDEO_TYPE_VIDEO_WITH_UI) {
+    g_signal_emit (src, gst_xv_image_src_signals[SIGNAL_VIDEO_WITH_UI], 0,
+        NULL);
+  }
+  return FALSE;
+}
+
+static gboolean
+signal_selection_emit_func (void *asrc)
+{
+  GstXVImageSrc *src = (GstXVImageSrc *) asrc;
+
+  g_signal_emit (src, gst_xv_image_src_signals[SIGNAL_SELECTION_NOTIFY], 0,
+      NULL);
+
+  return FALSE;
+}
+
+static int
+gst_xvimagesrc_handle_xerror (Display * display, XErrorEvent * xevent)
+{
+  char error_msg[1024];
+
+  XGetErrorText (display, xevent->error_code, error_msg, 1024);
+  GST_DEBUG ("XError. error: %s", error_msg);
+  error_caught = TRUE;
+  return 0;
+}
+
+static void
+gst_xv_image_out_buffer_unref (gpointer userdata)
+{
+  Atom atom_retbuf = 0;
+  //GstXVImageSrc *xvimagesrc = userdata;
+  GstXvImageOutBuffer *buffer = userdata;
+
+  //tbm_bo_unref (buffer->bo[0]);
+  //tbm_bo_unref (buffer->bo[1]);
+
+  g_mutex_lock (&buffer->xvimagesrc->dpy_lock);
+  atom_retbuf =
+      XInternAtom (buffer->xvimagesrc->dpy,
+      "_USER_WM_PORT_ATTRIBUTE_RETURN_BUFFER", False);
+
+  /* data->YBuf is gemname, refer to drm_convert_gem_to_fd */
+  XvSetPortAttribute (buffer->xvimagesrc->dpy, buffer->xvimagesrc->p,
+      atom_retbuf, buffer->YBuf);
+
+  g_mutex_unlock (&buffer->xvimagesrc->dpy_lock);
+  g_cond_signal (&buffer->xvimagesrc->buffer_cond);
+
+#ifdef DEBUG_BUFFER
+  int i = 0;
+  for (i = 0; i < 5; i++) {
+    if (value[i] == buffer->YBuf) {
+      value[i] = 0;
+      GST_ERROR ("value[%d]=%d", i, value[i]);
+    }
+  }
+#endif
+
+  return;
+}
+
+static void *
+gst_xv_image_src_update_thread (void *asrc)
+{
+  GstXVImageSrc *src = (GstXVImageSrc *) asrc;
+  Atom atom_data_type = 0;
+  Atom atom_display = 0;
+  Atom atom_secure = 0, atom_capture = 0;
+
+  g_return_val_if_fail ((src != NULL), NULL);
+
+  struct drm_gem_close gem_close;
+  int i = 0;
+  GEM_MMAP *xv_gem_mmap = NULL;
+  xv_gem_mmap = (GEM_MMAP *) malloc (sizeof (GEM_MMAP));
+  g_return_val_if_fail ((xv_gem_mmap != NULL), NULL);
+
+  memset (xv_gem_mmap, 0, sizeof (GEM_MMAP));
+
+  GST_LOG_OBJECT (src, "The thread function start");
+  int damage_err_base = 0;
+  Atom atom_format = 0;
+  src->dpy = XOpenDisplay (NULL);
+
+  src->p = port_get (src, src->format_id);
+  if (src->p < 0)
+    goto finish;
+
+  /*src->width and src->height is set by caps info */
+  GST_LOG_OBJECT (src, "width and height of caps : %dx%d ", src->width,
+      src->height);
+  if (src->width == 0 || src->height == 0) {
+    GST_ERROR_OBJECT (src, "width or height is 0");
+    goto finish;
+  }
+
+  src->pixmap = pixmap_create (src, src->dpy, src->width, src->height);
+  if (src->pixmap <= 0) {
+    GST_ERROR_OBJECT (src, "Failed to create pixmap");
+    goto finish;
+  }
+
+  src->gc = XCreateGC (src->dpy, src->pixmap, 0, 0);
+  if (src->gc == NULL) {
+    GST_ERROR_OBJECT (src, "Failed to create GC");
+    goto finish;
+  }
+
+  src->bufmgr = bufmgr_get (src->dpy, src->pixmap);
+  if (!src->bufmgr)
+    goto finish;
+
+  if (!XDamageQueryExtension (src->dpy, &src->damage_base, &damage_err_base)) {
+    GST_ERROR_OBJECT (src, "XDamageQueryExtension failed");
+    goto finish;
+  }
+
+  src->damage = XDamageCreate (src->dpy, src->pixmap, XDamageReportNonEmpty);
+  atom_format = XInternAtom (src->dpy, "_USER_WM_PORT_ATTRIBUTE_FORMAT", False);
+  atom_capture =
+      XInternAtom (src->dpy, "_USER_WM_PORT_ATTRIBUTE_CAPTURE", False);
+  atom_secure = XInternAtom (src->dpy, "_USER_WM_PORT_ATTRIBUTE_SECURE", False);
+  atom_display =
+      XInternAtom (src->dpy, "_USER_WM_PORT_ATTRIBUTE_DISPLAY", False);
+
+  XvSetPortAttribute (src->dpy, src->p, atom_format, src->format_id);
+  XvSetPortAttribute (src->dpy, src->p, atom_capture, 2);
+  XvSetPortAttribute (src->dpy, src->p, atom_display, 1);
+
+  /*get data type */
+  atom_data_type =
+      XInternAtom (src->dpy, "_USER_WM_PORT_ATTRIBUTE_DATA_TYPE", False);
+  XvSelectPortNotify (src->dpy, src->p, 1);
+  XvGetPortAttribute (src->dpy, src->p, atom_data_type, &(src->new_data_type));
+#if 0
+  /*set Xorg write-back hz */
+  atom_fps = XInternAtom (src->dpy, "_USER_WM_PORT_ATTRIBUTE_FPS", False);
+  GST_DEBUG ("frame rate of caps %d", src->rate_numerator);
+  XvSetPortAttribute (src->dpy, src->p, atom_fps, src->rate_numerator);
+  GST_DEBUG ("gst_xv_image_src_update_thread XvSetPortAttribute !!");
+#endif
+
+  struct timeval start_time, end_time;
+  long duration;
+  long starttime, endtime;
+  //GTimeVal timeout;
+  guint64 timeout;
+  XEvent ev;
+  void *virtual_address = NULL;
+  guint buf_size_Y = 0;
+  guint buf_size_Cb = 0;
+  int (*handler) (Display *, XErrorEvent *);
+  GstXvImageOutBuffer *outbuf = NULL;
+
+  gboolean pause_trigger = FALSE;
+  gboolean got_display_select_req = FALSE;
+
+  GstClockTime ts_putstill = 0;
+  GstClockTime dur_putstill = 0;
+
+  while (!src->thread_return) {
+    duration = 0;
+    starttime = 0;
+    endtime = 0;
+    start_time.tv_sec = 0;
+    start_time.tv_usec = 0;
+    end_time.tv_sec = 0;
+    end_time.tv_usec = 0;
+    gettimeofday (&start_time, NULL);
+
+    virtual_address = NULL;
+    duration = 0;
+    outbuf = NULL;
+
+    if (pause_trigger) {
+      g_cond_signal (&src->queue_cond);
+
+      GST_WARNING_OBJECT (src, "PAUSED in capture thread");
+      g_mutex_lock (&src->pause_lock);
+      g_cond_wait (&src->pause_cond, &src->pause_lock);
+      g_mutex_unlock (&src->pause_lock);
+      pause_trigger = FALSE;
+      continue;
+    }
+
+    if (src->pause_cond_var) {
+      pause_trigger = TRUE;
+    }
+
+    g_mutex_lock (&src->dpy_lock);
+    XSync (src->dpy, 0);
+    g_mutex_unlock (&src->dpy_lock);
+    error_caught = FALSE;
+    handler = XSetErrorHandler (gst_xvimagesrc_handle_xerror);
+
+    g_mutex_lock (&src->dpy_lock);
+    XvPutStill (src->dpy, src->p, src->pixmap, src->gc, 0, 0, src->width,
+        src->height, 0, 0, src->width, src->height);
+    XSync (src->dpy, 0);
+    g_mutex_unlock (&src->dpy_lock);
+
+    gst_xv_image_src_get_timeinfo (src, &ts_putstill, &dur_putstill);
+
+    if (error_caught) {
+      GST_ERROR
+          ("gst_xv_image_src_update_thread error_caught is TRUE, X is out of buffers");
+      error_caught = FALSE;
+      XSetErrorHandler (handler);
+
+      timeout = g_get_monotonic_time () + BUFFER_COND_WAIT_TIMEOUT;
+
+      g_mutex_lock (&src->buffer_cond_lock);
+      if (!g_cond_wait_until (&src->buffer_cond, &src->buffer_cond_lock, timeout)) {
+        GST_ERROR ("skip wating");
+      } else {
+        GST_ERROR ("Signal received");
+      }
+      g_mutex_unlock (&src->buffer_cond_lock);
+      continue;
+    }
+
+    /*reset error handler */
+    error_caught = FALSE;
+    XSetErrorHandler (handler);
+
+  next_event:
+    g_mutex_lock (&src->dpy_lock);
+    XNextEvent (src->dpy, &ev); /* wating for x event */
+    g_mutex_unlock (&src->dpy_lock);
+
+    if (ev.type == (src->damage_base + XDamageNotify)) {
+      XDamageNotifyEvent *damage_ev = (XDamageNotifyEvent *) & ev;
+      GST_INFO ("gst_xv_image_src_update_thread XDamageNotifyEvent");
+
+      g_mutex_lock (&src->dpy_lock);
+      if (damage_ev->drawable == src->pixmap) {
+        pixmap_update (src, src->dpy, src->bufmgr, src->pixmap,
+            damage_ev->area.x,
+            damage_ev->area.y, damage_ev->area.width, damage_ev->area.height);
+        GST_INFO ("gst_xv_image_src_update_thread pixmap_update");
+      }
+
+      XDamageSubtract (src->dpy, src->damage, None, None);
+      g_mutex_unlock (&src->dpy_lock);
+    } else if (ev.type == SelectionClear) {
+      /* Added to handle display selection notify */
+      //XSelectionEvent *selection_ev = (XSelectionEvent *) & ev;
+
+      GST_ERROR ("ev.type : %d SelectionClear", ev.type);
+      //g_timeout_add(1, signal_selection_emit_func, src);
+    } else if (ev.type == SelectionRequest) {
+      XSelectionRequestEvent *selection_ev = (XSelectionRequestEvent *) & ev;
+
+      GST_ERROR ("ev.type : %d SelectionRequest", ev.type);
+      src->requestor = selection_ev->requestor;
+      src->selection = selection_ev->selection;
+      src->target = selection_ev->target;
+      src->property = selection_ev->property;
+
+      got_display_select_req = TRUE;
+      g_timeout_add (1, signal_selection_emit_func, src);
+    } else if (ev.type == SelectionNotify) {
+      //XSelectionEvent *selection_ev = (XSelectionEvent *) & ev;
+
+      GST_ERROR ("ev.type : %d SelectionNotify", ev.type);
+      //g_timeout_add(1, signal_selection_emit_func, src);
+    } else if (ev.type == (src->evt_base + XvPortNotify)) {
+      XvPortNotifyEvent *notify_ev = (XvPortNotifyEvent *) & ev;
+
+      if (notify_ev->attribute == atom_secure) {
+        GST_WARNING ("secure attr changed : %s \n",
+            ((int) notify_ev->value) ? "Secure" : "Normal");
+        src->tz_enable = (int) notify_ev->value;
+        GST_WARNING ("src->tz_enable = %d", src->tz_enable);
+      } else if (notify_ev->attribute == atom_data_type) {
+        /* got a port notify, data_type */
+        src->new_data_type = (int) notify_ev->value;
+        if (src->current_data_type != src->new_data_type) {
+          src->current_data_type = src->new_data_type;
+          GST_WARNING ("current_data_type : %s \n",
+              (src->current_data_type) ? "Video" : "UI+Video");
+          g_timeout_add (1, signal_emit_func, src);
+        }
+      }
+      goto next_event;
+    }
+
+    if (!src->virtual)
+      continue;
+    if (src->format_id == FOURCC_RGB32) {
+      outbuf = (GstXvImageOutBuffer *) malloc (sizeof (GstXvImageOutBuffer));
+      outbuf->buffer = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
+          src->virtual, src->framesize, 0, src->framesize, NULL, NULL);
+#if 0
+        void *tmp_data = NULL;
+        tmp_data = (void *)malloc(buf_size_Y+buf_size_Cb);
+        memset (tmp_data, 0x00, buf_size_Y+buf_size_Cb);
+
+        memcpy (tmp_data, mm_video_buf->data[0], buf_size_Y);
+        memcpy (tmp_data+buf_size_Y, mm_video_buf->data[1], buf_size_Cb);
+
+        outbuf->buffer = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
+            tmp_data, buf_size_Y+buf_size_Cb, 0, buf_size_Y+buf_size_Cb, (gpointer) outbuf,
+            gst_xv_image_out_buffer_unref);
+
+        free (tmp_data);
+/*
+        GstBuffer *new_buf = NULL;
+        new_buf = gst_buffer_new_and_alloc (buf_size_Y+buf_size_Cb);
+        gst_buffer_set_size (new_buf, buf_size_Y+buf_size_Cb);
+
+        GstMapInfo map;
+        gst_buffer_map (new_buf, &map, GST_MAP_READ);
+        memcpy (map.data, mm_video_buf->data[0], buf_size_Y);
+        memcpy (map.data+buf_size_Y, mm_video_buf->data[1], buf_size_Cb);
+
+        outbuf->buffer = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
+            map.data, buf_size_Y+buf_size_Cb, 0, buf_size_Y+buf_size_Cb, (gpointer) outbuf,
+            gst_xv_image_out_buffer_unref);
+
+        gst_buffer_unmap (new_buf, &map);
+        gst_buffer_unref (new_buf);
+*/
+
+#endif
+    } else if (src->format_id == FOURCC_SN12) {
+      XV_DATA_PTR data = (XV_DATA_PTR) src->virtual;
+      int error = XV_VALIDATE_DATA (data);
+
+      if (error == XV_HEADER_ERROR)
+        GST_ERROR ("XV_HEADER_ERROR\n");
+      else if (error == XV_VERSION_MISMATCH)
+        GST_ERROR ("XV_VERSION_MISMATCH\n");
+      else {
+        MMVideoBuffer *mm_video_buf = NULL;
+        mm_video_buf = (MMVideoBuffer *) malloc (sizeof (MMVideoBuffer));
+        if (mm_video_buf == NULL) {
+          GST_ERROR_OBJECT (src, "failed to alloc MMVideoBuffer");
+          continue;
+        }
+
+        outbuf = gst_xv_image_out_buffer_new (src);
+        if (!outbuf) {
+          GST_ERROR ("Out of memory");
+          g_free (mm_video_buf);
+          continue;
+        }
+
+        memset (mm_video_buf, 0x00, sizeof (MMVideoBuffer));
+
+        if (data->BufType == XV_BUF_TYPE_LEGACY) {
+          GST_DEBUG ("XV_BUF_TYPE_LEGACY");
+          mm_video_buf->handle.paddr[0] = (void *) data->YBuf;
+          mm_video_buf->handle.paddr[1] = (void *) data->CbBuf;
+          mm_video_buf->type = MM_VIDEO_BUFFER_TYPE_PHYSICAL_ADDRESS;
+          mm_video_buf->data[0] = NULL;
+          mm_video_buf->data[1] = NULL;
+        } else if (data->BufType == XV_BUF_TYPE_DMABUF) {
+          if (src->buf_share_method == BUF_SHARE_METHOD_FD) {
+            mm_video_buf->handle.dmabuf_fd[0] =
+                drm_convert_gem_to_fd (&src->gemname_cnt, src->drm_fd, data->YBuf,
+                xv_gem_mmap, &virtual_address, &buf_size_Y);
+            mm_video_buf->data[0] = virtual_address;
+            GST_WARNING_OBJECT (src,
+                "YBuf gem to dmabuf_fd[0]:%d virtual_address : %p size : %d",
+                mm_video_buf->handle.dmabuf_fd[0], mm_video_buf->data[0], buf_size_Y);
+
+            mm_video_buf->handle.dmabuf_fd[1] =
+                drm_convert_gem_to_fd (&src->gemname_cnt, src->drm_fd,
+                data->CbBuf, xv_gem_mmap, &virtual_address, &buf_size_Cb);
+            mm_video_buf->data[1] = virtual_address;
+            GST_WARNING_OBJECT (src,
+                "CbBuf gem to dmabuf_fd[1]:%d  virtual_address : %p size: %d",
+                mm_video_buf->handle.dmabuf_fd[1], mm_video_buf->data[1], buf_size_Cb);
+            mm_video_buf->type = MM_VIDEO_BUFFER_TYPE_DMABUF_FD;
+          } else if (src->buf_share_method == BUF_SHARE_METHOD_TIZEN_BUFFER) {
+            mm_video_buf->type = MM_VIDEO_BUFFER_TYPE_TBM_BO;
+            mm_video_buf->handle.bo[0] = drm_convert_gem_to_bo (src->bufmgr, data->YBuf);
+            mm_video_buf->handle.bo[1] = drm_convert_gem_to_bo (src->bufmgr, data->CbBuf);
+            GST_WARNING_OBJECT (src, "BO : %p %p", mm_video_buf->handle.bo[0], mm_video_buf->handle.bo[1]);
+
+            outbuf->bo[0] = mm_video_buf->handle.bo[0];
+            outbuf->bo[1] = mm_video_buf->handle.bo[1];
+          }
+        }
+
+        mm_video_buf->width[0] = src->width;
+        mm_video_buf->height[0] = src->height;
+        mm_video_buf->format = MM_PIXEL_FORMAT_NV12;
+        mm_video_buf->width[1] = src->width;
+        mm_video_buf->height[1] = src->height >> 1;
+
+        mm_video_buf->stride_width[0] = GST_ROUND_UP_16 (mm_video_buf->width[0]);
+        mm_video_buf->stride_height[0] = GST_ROUND_UP_16 (mm_video_buf->height[0]);
+        mm_video_buf->stride_width[1] = GST_ROUND_UP_16 (mm_video_buf->width[1]);
+        mm_video_buf->stride_height[1] = GST_ROUND_UP_16 (mm_video_buf->height[1]);
+
+        mm_video_buf->is_secured = 0;
+
+        outbuf->buffer = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
+            src->virtual, src->framesize, 0, src->framesize, (gpointer) outbuf,
+            gst_xv_image_out_buffer_unref);
+        gst_buffer_append_memory (outbuf->buffer,
+            gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, mm_video_buf,
+                sizeof (*mm_video_buf), 0, sizeof (*mm_video_buf), mm_video_buf, g_free));
+
+        outbuf->YBuf = data->YBuf;
+        outbuf->fd_name = mm_video_buf->handle.dmabuf_fd[0];
+
+#ifdef DEBUG_BUFFER
+        for (i = 0; i < 5; i++) {
+          if (value[value_count] == outbuf->YBuf) {
+            GST_ERROR ("ERROR: value[%d](%d)==YBUf(%d)", value_count,
+                value[value_count], outbuf->YBuf);
+          }
+        }
+        value[value_count] = outbuf->YBuf;
+        GST_ERROR ("value[%d]=%d", value_count, value[value_count]);
+        if (value_count < 4) {
+          value_count++;
+        } else {
+          value_count = 0;
+        }
+#endif
+
+#ifdef _MAKE_DUMP
+        if (f_idx < 100) {
+          if (src->running_time > 14000000000
+              && src->running_time < 20000000000) {
+            GST_ERROR ("Mem copy");
+            if (virtual_address == NULL) {
+              GST_ERROR ("Mem virtual is NULL[%d]", f_idx);
+            } else {
+              //memcpy(g_dump_frame[f_idx++], mm_video_buf->data[0], YUV_720_FRAME_SIZE);
+              //memcpy(g_dump_frame[f_idx++], virtual_address, YUV_VGA_FRAME_SIZE);
+              memcpy (g_dump_frame[f_idx], mm_video_buf->data[0], 921600);
+              memcpy (g_dump_frame1[f_idx], mm_video_buf->data[1], 462848);
+              f_idx++;
+              GST_ERROR ("Mem copy done[%d]", f_idx);
+            }
+          }
+        } else {
+          if (f_done == 0) {
+            GST_ERROR ("File DUMP!!");
+            FILE *fp = NULL;
+            fp = fopen ("/root/frame.yuv", "a");
+            int i = 0;
+            for (i = 0; i < 100; i++) {
+              fwrite (g_dump_frame[i], 921600, 1, fp);
+              fwrite (g_dump_frame1[i], 462848, 1, fp);
+              //fwrite(g_dump_frame[i], 1384448, 1, fp);
+              //fwrite(g_dump_frame[i], YUV_720_FRAME_SIZE, 1, fp);
+              //fwrite(g_dump_frame[i], YUV_VGA_FRAME_SIZE, 1, fp);
+            }
+            fclose (fp);
+            f_done = 1;
+            GST_ERROR ("File DUMP done!!");
+          }
+        }
+#endif
+      }
+    }
+
+    if (!outbuf)
+      continue;
+
+    GST_BUFFER_TIMESTAMP (outbuf->buffer) = ts_putstill;
+    GST_BUFFER_DURATION (outbuf->buffer) = dur_putstill;
+    src->running_time = GST_BUFFER_TIMESTAMP (outbuf->buffer);
+    src->frame_duration = GST_BUFFER_DURATION (outbuf->buffer);
+    g_mutex_lock (&src->queue_lock);
+    g_queue_push_tail (src->queue, outbuf);
+    GST_INFO ("g_queue_push_tail");
+    g_mutex_unlock (&src->queue_lock);
+    g_cond_signal (&src->queue_cond);
+    GST_INFO ("g_cond_signal");
+
+    if (src->virtual)
+      tbm_bo_unmap (src->bo);
+    src->virtual = NULL;
+
+    if (src->bo)
+      tbm_bo_unref (src->bo);
+    src->bo = NULL;
+
+    if (src->dri2_buffers)
+      free (src->dri2_buffers);
+
+    src->dri2_buffers = NULL;
+
+    gettimeofday (&end_time, NULL);
+    starttime = start_time.tv_usec;
+    endtime = end_time.tv_usec;
+    GST_INFO ("star_time: %ld, end_time:%ld", starttime, endtime);
+
+    if (endtime > starttime) {
+      GST_INFO ("end_time > start_time");
+      duration = endtime - starttime;
+    } else {
+      GST_INFO ("end_time.tv_usec < start_time.tv_usec");
+      endtime = endtime + 1000000;
+      GST_INFO ("end_time =%ld", endtime);
+      duration = endtime - starttime;
+    }
+    GST_INFO ("end_time duration = %ld", duration);
+
+    if (src->sleep_base_time > duration)
+      gst_xv_get_image_sleep (src, duration);
+  }
+
+  for (i = 0; i < GEM_NAME_MAX; i++) {
+    /*gem munmap */
+    if (xv_gem_mmap->address[i]) {
+      if (-1 == munmap (xv_gem_mmap->address[i], xv_gem_mmap->buffer_size[i])) {
+        GST_ERROR ("munmap failed");
+        return NULL;
+      }
+    }
+    /*fd close */
+    if (xv_gem_mmap->handle[i]) {
+      gem_close.handle = xv_gem_mmap->handle[i];
+      if (ioctl (src->drm_fd, DRM_IOCTL_GEM_CLOSE, &gem_close)) {
+        GST_ERROR ("Gem Close failed");
+      }
+    }
+
+    if (xv_gem_mmap->fd[i]) {
+      close (xv_gem_mmap->fd[i]);
+    }
+  }
+
+  if (xv_gem_mmap) {
+    free (xv_gem_mmap);
+    xv_gem_mmap = NULL;
+  }
+
+
+  GST_LOG_OBJECT (src, "The thread function cleanup");
+
+  XvStopVideo (src->dpy, src->p, src->pixmap);
+
+  if (src->bufmgr) {
+    tbm_bufmgr_deinit (src->bufmgr);
+    src->bufmgr = NULL;
+  }
+
+  if (src->p > 0) {
+    XvUngrabPort (src->dpy, src->p, 0);
+    src->p = 0;
+  }
+
+  if (got_display_select_req) {
+    /* Notify miracast-destroyed to X  */
+    GST_WARNING_OBJECT (src, "There is display selection request");
+    XEvent xev;
+    XSelectionEvent xnotify;
+
+    xnotify.type = SelectionNotify;
+    xnotify.display = src->dpy;
+    xnotify.requestor = src->requestor;
+    xnotify.selection = src->selection;
+    xnotify.target = src->target;
+    xnotify.property = src->property;
+    xnotify.time = 0;
+    xnotify.send_event = True;
+    xnotify.serial = 0;
+    xev.xselection = xnotify;
+    if (XSendEvent (src->dpy, src->requestor, False, 0, &xev) < 0) {
+      GST_ERROR ("XSendEvent failed!");
+    } else {
+      GST_INFO ("XSendEvent success!");
+    }
+  }
+
+  if (src->gc) {
+    XFreeGC (src->dpy, src->gc);
+    src->gc = NULL;
+  }
+
+  if (src->pixmap > 0) {
+    XFreePixmap (src->dpy, src->pixmap);
+    src->pixmap = 0;
+  }
+
+  if (src->dpy) {
+    XCloseDisplay (src->dpy);
+    src->dpy = NULL;
+  }
+
+  GST_LOG_OBJECT (src, "The thread function stop");
+  return NULL;
+finish:
+  GST_LOG_OBJECT (src, "The thread function Error cleanup");
+
+  XvStopVideo (src->dpy, src->p, src->pixmap);
+
+  if (src->bufmgr)
+    tbm_bufmgr_deinit (src->bufmgr);
+  src->bufmgr = NULL;
+  if (src->p > 0)
+    XvUngrabPort (src->dpy, src->p, 0);
+  src->p = 0;
+  if (src->gc)
+    XFreeGC (src->dpy, src->gc);
+  src->gc = NULL;
+  if (src->pixmap > 0)
+    XFreePixmap (src->dpy, src->pixmap);
+  src->pixmap = 0;
+  if (src->dpy)
+    XCloseDisplay (src->dpy);
+  src->dpy = NULL;
+
+  GST_LOG_OBJECT (src, "The thread function Error stop");
+  return NULL;
+}
+
+static tbm_bufmgr
+bufmgr_get (Display * dpy, Pixmap pixmap)
+{
+  int screen;
+  int drm_fd;
+  tbm_bufmgr bufmgr;
+  int eventBase, errorBase;
+  int dri2Major, dri2Minor;
+  char *driverName, *deviceName;
+  drm_magic_t magic;
+
+  screen = DefaultScreen (dpy);
+  if (!DRI2QueryExtension (dpy, &eventBase, &errorBase)) {
+    GST_ERROR ("!!Error : DRI2QueryExtension !!");
+    return NULL;
+  }
+
+  if (!DRI2QueryVersion (dpy, &dri2Major, &dri2Minor)) {
+    GST_ERROR ("!!Error : DRI2QueryVersion !!");
+    return NULL;
+  }
+
+  if (!DRI2Connect (dpy, RootWindow (dpy, screen), &driverName, &deviceName)) {
+    GST_ERROR ("!!Error : DRI2Connect !!");
+    if (driverName)
+      Xfree (driverName);
+    if (deviceName)
+      Xfree (deviceName);
+    return NULL;
+  }
+
+  if (driverName)
+    Xfree (driverName);
+
+  if (!deviceName) return NULL;
+
+  GST_DEBUG ("Open drm device : %s", deviceName);
+
+  // get the drm_fd though opening the deviceName
+  drm_fd = open (deviceName, O_RDWR);
+  if (drm_fd < 0) {
+    GST_ERROR ("!!Error : cannot open drm device (%s)", deviceName);
+    if (deviceName)
+      Xfree (deviceName);
+    return NULL;
+  }
+
+  if (deviceName)
+    Xfree (deviceName);
+
+  struct drm_exynos_vidi_connection vidi;
+
+  vidi.connection = 1;
+  vidi.extensions = 1;
+  vidi.edid = (uint64_t *)fake_edid_info;
+
+  ioctl (drm_fd, DRM_IOCTL_EXYNOS_VIDI_CONNECTION, &vidi);
+
+  /* get the drm magic */
+  drmGetMagic (drm_fd, &magic);
+  fprintf (stderr, ">>> drm magic=%d \n", magic);
+  if (!DRI2Authenticate (dpy, RootWindow (dpy, screen), magic)) {
+    fprintf (stderr, "!!Error : DRI2Authenticate !!\n");
+    close (drm_fd);
+    return NULL;
+  }
+
+  // drm slp buffer manager init
+  bufmgr = tbm_bufmgr_init (drm_fd);
+  if (!bufmgr) {
+    GST_ERROR ("Error : fail to init buffer manager ");
+    close (drm_fd);
+    return NULL;
+  }
+
+  DRI2CreateDrawable (dpy, pixmap);
+  return bufmgr;
+}
+
+static int
+port_get (GstXVImageSrc * src, unsigned int id)
+{
+  unsigned int ver, rev, req_base, err_base;
+  unsigned int adaptors;
+  XvAdaptorInfo *ai = NULL;
+  XvAttribute *at = NULL;
+  XvImageFormatValues *fo = NULL;
+  int attributes, formats;
+  int i, j, p;
+
+  if (XvQueryExtension (src->dpy, &ver, &rev, &req_base, &src->evt_base,
+          &err_base) != Success)
+    return -1;
+
+  if (XvQueryAdaptors (src->dpy, DefaultRootWindow (src->dpy), &adaptors,
+          &ai) != Success)
+    return -1;
+
+  if (!ai)
+    return -1;
+
+  for (i = 0; i < adaptors; i++) {
+    int support_format = False;
+    if (!(ai[i].type & XvInputMask) || !(ai[i].type & XvStillMask))
+      continue;
+
+    GST_LOG ("===========================================");
+    GST_LOG (" name:        %s"
+        " first port:  %ld"
+        " ports:       %ld", ai[i].name, ai[i].base_id, ai[i].num_ports);
+    p = ai[i].base_id;
+    GST_LOG (" attribute list:");
+    at = XvQueryPortAttributes (src->dpy, p, &attributes);
+    for (j = 0; j < attributes; j++)
+      GST_LOG ("\t-  name: %s\n"
+          "\t\t  flags:     %s%s\n"
+          "\t\t  min_value:  %i\n"
+          "\t\t  max_value:  %i\n",
+          at[j].name,
+          (at[j].flags & XvGettable) ? " get" : "",
+          (at[j].flags & XvSettable) ? " set" : "",
+          at[j].min_value, at[j].max_value);
+
+    if (at)
+      XFree (at);
+
+    GST_LOG (" image format list:");
+    fo = XvListImageFormats (src->dpy, p, &formats);
+    for (j = 0; j < formats; j++) {
+      GST_LOG ("\t-  0x%x (%4.4s) %s", fo[j].id, (char *) &fo[j].id,
+          (fo[j].format == XvPacked) ? "packed" : "planar");
+      if (fo[j].id == (int) id)
+        support_format = True;
+    }
+
+    if (fo)
+      XFree (fo);
+    if (!support_format)
+      continue;
+
+    for (; p < ai[i].base_id + ai[i].num_ports; p++) {
+      if (XvGrabPort (src->dpy, p, 0) == Success) {
+        GST_LOG ("========================================");
+        GST_DEBUG ("XvGrabPort success : %d", p);
+        GST_LOG ("========================================");
+        XvFreeAdaptorInfo (ai);
+        return p;
+      }
+    }
+  }
+
+  GST_ERROR_OBJECT (src, "XvGrabPort failed");
+  XvFreeAdaptorInfo (ai);
+  return -1;
+}
+
+static void
+pixmap_update (GstXVImageSrc * src, Display * dpy, tbm_bufmgr bufmgr,
+    Pixmap pixmap, int x, int y, int width, int height)
+{
+  unsigned int attachments[1];
+  int dri2_count, dri2_out_count;
+  int dri2_width, dri2_height, dri2_stride;
+  int opt;
+  tbm_bo_handle temp_virtual;
+
+  attachments[0] = DRI2BufferFrontLeft;
+  dri2_count = 1;
+  src->dri2_buffers =
+      DRI2GetBuffers (dpy, pixmap, &dri2_width, &dri2_height, attachments,
+      dri2_count, &dri2_out_count);
+
+  if (!src->dri2_buffers) {
+    GST_ERROR ("[Error] : fail to get buffers");
+    goto update_done;
+  }
+
+  if (!src->dri2_buffers[0].name) {
+    GST_ERROR ("[Error] : a handle of the dri2 buffer is null  ");
+    goto update_done;
+  }
+
+  src->bo = tbm_bo_import (bufmgr, src->dri2_buffers[0].name);
+  if (!src->bo) {
+    GST_ERROR ("[Error] : cannot import bo (key:%d)",
+        src->dri2_buffers[0].name);
+    goto update_done;
+  }
+
+  dri2_stride = src->dri2_buffers[0].pitch;
+  opt = TBM_OPTION_READ | TBM_OPTION_WRITE;
+
+  temp_virtual = tbm_bo_map (src->bo, TBM_DEVICE_CPU, opt);
+  src->virtual = temp_virtual.ptr;
+  if (!src->virtual) {
+    GST_ERROR ("[Error] : fail to map ");
+    goto update_done;
+  }
+
+  return;
+update_done:
+  if (src->virtual)
+    tbm_bo_unmap (src->bo);
+  src->virtual = NULL;
+
+  if (src->bo)
+    tbm_bo_unref (src->bo);
+  src->bo = NULL;
+
+  if (src->dri2_buffers)
+    free (src->dri2_buffers);
+  src->dri2_buffers = NULL;
+
+  return;
+}
+
+static Pixmap
+pixmap_create (GstXVImageSrc * src, Display * dpy, int width, int height)
+{
+  Pixmap pixmap = 0;
+
+  pixmap = XCreatePixmap (dpy, DefaultRootWindow (dpy), width, height,
+      DefaultDepth (dpy, DefaultScreen (dpy)));
+  if (pixmap <= 0) {
+    GST_ERROR_OBJECT (src, "Failed to create pixmap");
+    return 0;
+  }
+
+  src->gc = XCreateGC (dpy, pixmap, 0, 0);
+  if (src->gc == NULL) {
+    GST_ERROR_OBJECT (src, "Failed to create GC");
+    XFreePixmap (dpy, pixmap);
+    return 0;
+  }
+
+  XSetForeground (dpy, src->gc, 0xFFFF0000);
+  XFillRectangle (dpy, pixmap, src->gc, 0, 0, width, height);
+  XSync (dpy, 0);
+  XFreeGC (dpy, src->gc);
+
+  return pixmap;
+}
+
+static gboolean
+gst_xv_image_src_stop (GstBaseSrc * bsrc)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  GST_DEBUG_OBJECT (src, "stop()");
+
+  if (src->updates_thread) {
+    src->thread_return = TRUE;
+    g_thread_join (src->updates_thread);
+    src->updates_thread = NULL;
+  }
+  GST_DEBUG_OBJECT (src, "stop end ");
+  return TRUE;
+}
+
+/* Interrupt a blocking request. */
+static gboolean
+gst_xv_image_src_unlock (GstBaseSrc * bsrc)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  GST_DEBUG_OBJECT (src, "unlock()");
+  return TRUE;
+}
+
+/* Interrupt interrupt. */
+static gboolean
+gst_xv_image_src_unlock_stop (GstBaseSrc * bsrc)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  GST_DEBUG_OBJECT (src, "unlock_stop()");
+  return TRUE;
+}
+
+static gboolean
+gst_xv_image_src_get_size (GstBaseSrc * bsrc, guint64 * size)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  GST_INFO ("Get size %p", src);
+  return FALSE;
+}
+
+static gboolean
+gst_xv_image_src_is_seekable (GstBaseSrc * bsrc)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  GST_INFO_OBJECT (src, "Is seekable");
+  return FALSE;
+}
+
+static gboolean
+gst_xv_image_src_query (GstBaseSrc * bsrc, GstQuery * query)
+{
+  GstXVImageSrc *src = GST_XV_IMAGE_SRC (bsrc);
+  gboolean ret;
+
+  switch (GST_QUERY_TYPE (query)) {
+    default:
+      GST_INFO_OBJECT (src, "Default");
+      break;
+  }
+
+  ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
+
+  return ret;
+}
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+  GST_DEBUG_CATEGORY_INIT (xvimagesrc_debug, "xvimagesrc", 0,
+      "XServer display FB video capture Source");
+  return gst_element_register (plugin, "xvimagesrc", GST_RANK_PRIMARY,
+      GST_TYPE_XV_IMAGE_SRC);
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+    GST_VERSION_MINOR,
+    xvimage,
+    "XServer display video src",
+    plugin_init, VERSION, "LGPL", "Samsung Electronics Co",
+    "http://www.samsung.com")
diff --git a/xvimagesrc/src/gstxvimagesrc.h b/xvimagesrc/src/gstxvimagesrc.h
new file mode 100644 (file)
index 0000000..c2e1340
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+ * xvimagesrc
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact: Hyunil Park <hyunil46.park@samsung.com>
+ *
+ * This library is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU Lesser General Public License as published by the
+ * Free Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software Foundation, Inc., 51
+ * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+#ifndef __GST_XV_IMAGE_SRC_H__
+#define __GST_XV_IMAGE_SRC_H__
+
+#include <gst/gst.h>
+#include <gst/base/gstpushsrc.h>
+#include <glib.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <signal.h>
+
+#include <sys/types.h>
+#include <sys/shm.h>
+
+#include <X11/X.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <X11/extensions/Xvlib.h>
+#include <X11/extensions/Xvproto.h>
+#include <X11/extensions/XShm.h>
+#include <X11/extensions/Xdamage.h>
+
+#include <dri2.h>               //libdri2-dev, libdrm-dev
+#include <tbm_bufmgr.h>
+
+#include "xv_types.h"
+
+#define C(b,m)              (((b) >> (m)) & 0xFF)
+#define B(c,s)              ((((unsigned int)(c)) & 0xff) << (s))
+#define FOURCC(a,b,c,d)     (B(d,24) | B(c,16) | B(b,8) | B(a,0))
+#define FOURCC_RGB32        FOURCC('R','G','B','4')
+#define FOURCC_I420         FOURCC('I','4','2','0')
+#define FOURCC_SN12         FOURCC('S','N','1','2')
+#define FOURCC_ST12         FOURCC('S','T','1','2')
+
+G_BEGIN_DECLS
+#define GST_TYPE_XV_IMAGE_SRC \
+  (gst_xv_image_src_get_type())
+#define GST_XV_IMAGE_SRC(obj) \
+  (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_XV_IMAGE_SRC,GstXVImageSrc))
+#define GST_XV_IMAGE_SRC_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_CAST((klass), \
+      GST_TYPE_XV_IMAGE_SRC,GstXVImageSrcClass))
+#define GST_IS_XV_IMAGE_SRC(obj) \
+  (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_XV_IMAGE_SRC))
+#define GST_IS_XV_IMAGE_SRC_CLASS(klass) \
+  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_XV_IMAGE_SRC))
+typedef struct _GstXVImageSrc GstXVImageSrc;
+typedef struct _GstXVImageSrcClass GstXVImageSrcClass;
+
+struct _GstXVImageSrc
+{
+  GstPushSrc element;
+  Display *dpy;
+  int p;
+  Pixmap pixmap;
+  GC gc;
+  unsigned int width;
+  unsigned int height;
+  unsigned int framesize;
+  guint32 format_id;
+  Damage damage;
+  int damage_base;
+  unsigned int evt_base;
+  tbm_bufmgr bufmgr;
+  void *virtual;
+  tbm_bo bo;
+  DRI2Buffer *dri2_buffers;
+  int buf_share_method;
+  guint64 running_time;
+  guint64 base_time;
+  guint64 frame_duration;
+  gint rate_numerator;
+  gint rate_denominator;
+  GThread *updates_thread;
+  gboolean thread_return;
+  GQueue *queue;
+  GMutex queue_lock;
+  GCond queue_cond;
+  GMutex cond_lock;
+  GCond buffer_cond;
+  GMutex buffer_cond_lock;
+  GMutex dpy_lock;
+
+  gboolean pause_cond_var;
+  GCond pause_cond;
+  GMutex pause_lock;
+
+  gint drm_fd;
+  int current_data_type;
+  int new_data_type;
+  double get_image_overtime;
+  int get_image_overtime_cnt;
+  int gemname_cnt;
+  int tz_enable;
+  long sleep_base_time;
+  long sleep_limit_time;
+
+  /* For display selection */
+  Window win;
+  Atom requestor;
+  Atom selection;
+  Atom target;
+  Atom property;
+};
+
+struct _GstXVImageSrcClass
+{
+  GstPushSrcClass parent_class;
+
+  /* signals */
+  void (*video_with_ui) (void *data);
+  void (*video_only) (void *data);
+  void (*selection_notify) (void *data);
+};
+
+GType gst_xv_image_src_get_type (void);
+
+G_END_DECLS
+#endif /* __GST_XV_IMAGE_SRC_H__ */
diff --git a/xvimagesrc/src/xv_types.h b/xvimagesrc/src/xv_types.h
new file mode 100644 (file)
index 0000000..10e17f2
--- /dev/null
@@ -0,0 +1,170 @@
+/**************************************************************************
+
+xserver-xorg-video-exynos
+
+Copyright 2010 - 2011 Samsung Electronics co., Ltd. All Rights Reserved.
+
+Contact: Boram Park <boram1288.park@samsung.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, sub license, 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 (including the
+next paragraph) 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 NON-INFRINGEMENT.
+IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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.
+
+**************************************************************************/
+
+/*                                                              */
+/* File name : xv_types.h                                       */
+/* Author : Boram Park (boram1288.park@samsung.com)             */
+/* Protocol Version : 1.0.1 (Dec 16th 2009)                       */
+/* This file is for describing Xv APIs' buffer encoding method. */
+/*                                                              */
+
+#ifndef __XV_TYPE_H__
+#define __XV_TYPE_H__
+
+#define XV_DATA_HEADER 0xDEADCD01
+#define XV_DATA_VERSION        0x00010001
+
+/* Return Values */
+#define XV_OK 0
+#define XV_HEADER_ERROR -1
+#define XV_VERSION_MISMATCH -2
+
+/* Video Mode */
+#define DISPLAY_MODE_DEFAULT                                      0
+#define DISPLAY_MODE_PRI_VIDEO_ON_AND_SEC_VIDEO_FULL_SCREEN       1
+#define DISPLAY_MODE_PRI_VIDEO_OFF_AND_SEC_VIDEO_FULL_SCREEN      2
+
+/* Color space range */
+#define CSC_RANGE_NARROW        0
+#define CSC_RANGE_WIDE          1
+
+/* Buffer Type */
+#define XV_BUF_TYPE_DMABUF  0
+#define XV_BUF_TYPE_LEGACY  1
+#define XV_BUF_PLANE_NUM    3
+
+/* Data structure for XvPutImage / XvShmPutImage */
+typedef struct
+{
+    unsigned int _header; /* for internal use only */
+    unsigned int _version; /* for internal use only */
+
+    unsigned int YBuf;
+    unsigned int CbBuf;
+    unsigned int CrBuf;
+    unsigned int BufType;
+    unsigned int dmabuf_fd[XV_BUF_PLANE_NUM];
+    unsigned int gem_handle[XV_BUF_PLANE_NUM];
+    void *bo[XV_BUF_PLANE_NUM];
+} XV_DATA, * XV_DATA_PTR;
+
+static void
+#ifdef __GNUC__
+__attribute__ ((unused))
+#endif
+XV_INIT_DATA (XV_DATA_PTR data)
+{
+    data->_header = XV_DATA_HEADER;
+    data->_version = XV_DATA_VERSION;
+}
+
+static int
+#ifdef __GNUC__
+__attribute__ ((unused))
+#endif
+XV_VALIDATE_DATA (XV_DATA_PTR data)
+{
+    if (data->_header != XV_DATA_HEADER)
+        return XV_HEADER_ERROR;
+    if (data->_version != XV_DATA_VERSION)
+        return XV_VERSION_MISMATCH;
+    return XV_OK;
+}
+
+#if 0
+/* max channel count *********************************************************/
+#define SCMN_IMGB_MAX_PLANE         (4)
+
+/* image buffer definition ***************************************************
+
+    +------------------------------------------+ ---
+    |                                          |  ^
+    |     a[], p[]                             |  |
+    |     +---------------------------+ ---    |  |
+    |     |                           |  ^     |  |
+    |     |<---------- w[] ---------->|  |     |  |
+    |     |                           |  |     |  |
+    |     |                           |        |
+    |     |                           |  h[]   |  e[]
+    |     |                           |        |
+    |     |                           |  |     |  |
+    |     |                           |  |     |  |
+    |     |                           |  v     |  |
+    |     +---------------------------+ ---    |  |
+    |                                          |  v
+    +------------------------------------------+ ---
+
+    |<----------------- s[] ------------------>|
+*/
+
+typedef struct
+{
+    /* width of each image plane */
+    int w[SCMN_IMGB_MAX_PLANE]; // int width
+    /* height of each image plane */
+    int h[SCMN_IMGB_MAX_PLANE]; // int height
+    /* stride of each image plane */
+    int s[SCMN_IMGB_MAX_PLANE]; // int stride_width
+    /* elevation of each image plane */
+    int e[SCMN_IMGB_MAX_PLANE]; // int stride_width
+    /* user space address of each image plane */
+    void *a[SCMN_IMGB_MAX_PLANE]; //  void *data
+    /* physical address of each image plane, if needs */
+    void *p[SCMN_IMGB_MAX_PLANE]; // union void *paddr
+    /* color space type of image */
+    int cs; // MMPixelFormatType format
+    /* left postion, if needs */
+    int x;
+    /* top position, if needs */
+    int y;
+    /* to align memory */
+    int __dummy2;
+    /* arbitrary data */
+    int data[16];
+    /* dma buf fd */
+    int dmabuf_fd[SCMN_IMGB_MAX_PLANE]; // union int dmabuf_fd
+    /* buffer share method */
+    int buf_share_method; // MMVideoBufferType type
+    /* Y plane size in case of ST12 */
+    int y_size;
+    /* UV plane size in case of ST12 */
+    int uv_size;
+    /* Tizen buffer object */
+    void *bo[SCMN_IMGB_MAX_PLANE]; // union void *bo
+    /* JPEG data */
+    void *jpeg_data;
+    /* JPEG size */
+    int jpeg_size;
+    /* TZ memory buffer */
+    int tz_enable; // is_secured
+} SCMN_IMGB;
+#endif
+#endif
+