shithub: opus-tools

Download patch

ref: c27db573523ba968921a845af1ece5076013d4cc
parent: 6e9360558a07b04ed73ebb681cbd95ebbcd7cd61
author: Gregory Maxwell <greg@xiph.org>
date: Sat May 26 14:49:35 EDT 2012

Add 'opusinfo' tool and misc cleanups.

opus_header.[ch] were changed to using the ogg types rather than
the opus ones in order to facilitate copying them into other
packages.

--- a/COPYING
+++ b/COPYING
@@ -1,3 +1,7 @@
+
+Opus-tools, with the exception of opusinfo.[ch] is available under
+the following two clause BSD-style license:
+
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
@@ -20,3 +24,348 @@
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+Opusinfo is a fork of ogginfo from the vorbis-tools package
+(http://www.xiph.org). It is available under the GPLv2:
+
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+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 Program or any portion
+of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+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 Program, 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 Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) 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; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, 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 executable.  However, as a
+special exception, the source code 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.
+
+If distribution of executable or 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 counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program 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.
+
+  5. 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 Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program 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 to
+this License.
+
+  7. 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 Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program 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 Program.
+
+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.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program 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.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies 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 Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, 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
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. 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 PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+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 program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 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
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year  name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
--- a/Makefile.am
+++ b/Makefile.am
@@ -4,9 +4,9 @@
 
 INCLUDES = -I$(top_srcdir)/src
 
-AM_CFLAGS = $(OGG_CFLAGS) $(Opus_CFLAGS) -D_FORTIFY_SOURCE=2 -DHAVE_GETOPT_H -DEXPORT= -DRANDOM_PREFIX=opustools -DOUTSIDE_SPEEX -DFLOATING_POINT
+AM_CFLAGS = $(OGG_CFLAGS) $(Opus_CFLAGS) -DOPUSTOOLS -D_FORTIFY_SOURCE=2 -DHAVE_GETOPT_H -DEXPORT= -DRANDOM_PREFIX=opustools -DOUTSIDE_SPEEX -DFLOATING_POINT
 
-bin_PROGRAMS = opusenc opusdec
+bin_PROGRAMS = opusenc opusdec opusinfo
 
 opusenc_SOURCES = src/opus_header.c src/opusenc.c src/resample.c src/audio-in.c src/diag_range.c
 opusenc_LDADD = $(OGG_LIBS) $(Opus_LIBS) -lm
@@ -13,5 +13,8 @@
 
 opusdec_SOURCES = src/opus_header.c src/wav_io.c src/wave_out.c src/opusdec.c src/resample.c src/diag_range.c
 opusdec_LDADD = $(OGG_LIBS) $(Opus_LIBS) $(OSS_LIBS) -lm
+
+opusinfo_SOURCES = src/opus_header.c src/opusinfo.c src/info_opus.c
+opusinfo_LDADD = $(OGG_LIBS)
 
 #TESTS = FIXME
--- a/Makefile.unix
+++ b/Makefile.unix
@@ -1,8 +1,8 @@
 #CC=gcc
-CFLAGS:=-DHAVE_SYS_SOUNDCARD_H -O2 -g -c -Wall -Wextra -DHAVE_GETOPT_H -DEXPORT= -DRANDOM_PREFIX=opustools -DOUTSIDE_SPEEX -DFLOATING_POINT $(CFLAGS)
+CFLAGS:=-DPACKAGE='"opus-tools"' -DVERSION='"0.1.0"' -DOPUSTOOLS -DHAVE_SYS_SOUNDCARD_H -O2 -g -c -Wall -Wextra -DHAVE_GETOPT_H -DEXPORT= -DRANDOM_PREFIX=opustools -DOUTSIDE_SPEEX -DFLOATING_POINT $(CFLAGS)
 INCLUDES=-I../opus/include
 
-all: opusenc opusdec
+all: opusenc opusdec opusinfo
 
 .c.o:
 	$(CC) $(CFLAGS) $(INCLUDES) $< -o $@
@@ -13,5 +13,8 @@
 opusdec: src/opus_header.o src/wav_io.o src/wave_out.o src/opusdec.o src/resample.o src/diag_range.o
 	$(CC) $(LDFLAGS) src/wave_out.o src/opus_header.o src/wav_io.o src/diag_range.o src/opusdec.o src/resample.o -o opusdec ../opus/.libs/libopus.a -lm -logg
 
+opusinfo: src/opus_header.o src/opusinfo.o src/info_opus.o
+	$(CC) $(LDFLAGS) src/opus_header.o src/opusinfo.o src/info_opus.o -o opusinfo -logg
+
 clean:
-	rm -f src/*.o opusenc opusdec
+	rm -f src/*.o opusenc opusdec opusinfo
--- a/configure.ac
+++ b/configure.ac
@@ -26,9 +26,6 @@
 VERSION=$OPUSTOOLS_VERSION
 PACKAGE=opus-tools
 
-# For our version string
-AC_SUBST(OPUSTOOLS_VERSION)
-
 AM_INIT_AUTOMAKE($PACKAGE, $VERSION, no-define)
 AM_MAINTAINER_MODE
 
@@ -93,7 +90,8 @@
 fi
 AC_SUBST([LIBM])
 
-AC_DEFINE_UNQUOTED(OPUSTOOLS_VERSION, "${OPUSTOOLS_VERSION}", [Complete version string])
+AC_DEFINE_UNQUOTED(PACKAGE, "${OPUSTOOLS_VERSION}", [Package name])
+AC_DEFINE_UNQUOTED(VERSION, "${OPUSTOOLS_VERSION}", [Package version])
 AC_DEFINE_UNQUOTED(OPUSTOOLS_MAJOR_VERSION, ${OPUSTOOLS_MAJOR_VERSION}, [Version major])
 AC_DEFINE_UNQUOTED(OPUSTOOLS_MINOR_VERSION, ${OPUSTOOLS_MINOR_VERSION}, [Version minor])
 AC_DEFINE_UNQUOTED(OPUSTOOLS_MICRO_VERSION, ${OPUSTOOLS_MICRO_VERSION}, [Version micro])
--- /dev/null
+++ b/src/info_opus.c
@@ -1,0 +1,310 @@
+/* Copyright (C)2012 Gregory Maxwell
+   File: info_opus.c
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions
+   are met:
+
+   - Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <ogg/ogg.h>
+
+#ifndef OPUSTOOLS
+# include "ogginfo2.h"
+#else
+# include "opusinfo.h"
+#endif
+#include "opus_header.h"
+#include "info_opus.h"
+
+/* From libopus, src/opus_decode.c */
+static int packet_get_samples_per_frame(const unsigned char *data, int32_t Fs)
+{
+   int audiosize;
+   if (data[0]&0x80)
+   {
+      audiosize = ((data[0]>>3)&0x3);
+      audiosize = (Fs<<audiosize)/400;
+   } else if ((data[0]&0x60) == 0x60)
+   {
+      audiosize = (data[0]&0x08) ? Fs/50 : Fs/100;
+   } else {
+      audiosize = ((data[0]>>3)&0x3);
+      if (audiosize == 3)
+         audiosize = Fs*60/1000;
+      else
+         audiosize = (Fs<<audiosize)/100;
+   }
+   return audiosize;
+}
+
+/* From libopus, src/opus_decode.c */
+static int packet_get_nb_frames(const unsigned char packet[], int32_t len)
+{
+   int count;
+   if (len<1)
+      return -1;
+   count = packet[0]&0x3;
+   if (count==0)
+      return 1;
+   else if (count!=3)
+      return 2;
+   else if (len<2)
+      return -4;
+   else
+      return packet[1]&0x3F;
+}
+
+#define readle32(buf, base) (((buf[base+3]<<24)&0xff000000)| \
+                             ((buf[base+2]<<16)&0xff0000)| \
+                             ((buf[base+1]<<8)&0xff00)| \
+                              (buf[base]&0xff))
+
+void info_opus_process(stream_processor *stream, ogg_page *page )
+{
+    ogg_packet packet;
+    ogg_int64_t page_samples=0;
+    misc_opus_info *inf = stream->data;
+    int header=0, packets=0;
+    int res;
+
+    ogg_stream_pagein(&stream->os, page);
+    if(inf->doneheaders < 2)
+        header = 1;
+
+    while(1) {
+        int32_t spp;
+        res = ogg_stream_packetout(&stream->os, &packet);
+        if(res < 0) {
+           oi_warn(_("WARNING: discontinuity in stream (%d)\n"), stream->num);
+           continue;
+        }
+        else if (res == 0)
+            break;
+
+        packets++;
+        if(inf->doneheaders < 2) {
+            if(inf->doneheaders==0 && opus_header_parse(packet.packet,packet.bytes,&inf->oh)!=1) {
+                oi_warn(_("WARNING: Could not decode Opus header "
+                       "packet %d - invalid Opus stream (%d)\n"),
+                        inf->doneheaders, stream->num);
+                continue;
+            } else if (inf->doneheaders==0){
+                if(inf->oh.preskip<120)oi_warn(_("WARNING: Implausibly low preskip in Opus stream (%d)\n"),stream->num);
+            }
+            if(inf->doneheaders==1 && (packet.bytes<8 || memcmp(packet.packet, "OpusTags",8)!=0)) {
+               oi_warn(_("WARNING: Could not decode OpusTags header "
+                       "packet %d - invalid Opus stream (%d)\n"),
+                        inf->doneheaders, stream->num);
+                continue;
+            } else if (inf->doneheaders==1) {
+                char *tmp;
+                char *c=(char *)packet.packet;
+                int length, len, i, nb_fields;
+
+                length=packet.bytes;
+                if (length<(8+4+4)) {
+                    oi_warn(_("Invalid/corrupted comments in stream %d\n"),stream->num);
+                    continue;
+                }
+                c += 8;
+                len=readle32(c, 0);
+                c+=4;
+                if (len < 0 || len>(length-16)) {
+                    oi_warn(_("Invalid/corrupted comments in stream %d\n"),stream->num);
+                    continue;
+                }
+                tmp=calloc(len+1,1);
+                memcpy(tmp,c,len);
+                oi_info(_("Encoded with %s\n"),tmp);
+                free(tmp);
+                c+=len;
+                /*The -16 check above makes sure we can read this.*/
+                nb_fields=readle32(c, 0);
+                c+=4;
+                length-=16+len;
+                if (nb_fields < 0 || nb_fields>(length>>2)) {
+                    oi_warn(_("Invalid/corrupted comments in stream %d\n"),stream->num);
+                    continue;
+                }
+                if(nb_fields)oi_info(_("User comments section follows...\n"));
+                for (i=0;i<nb_fields;i++) {
+                    char *comment;
+                    if (length<4) {
+                        oi_warn(_("Invalid/corrupted comments in stream %d\n"),stream->num);
+                        break;
+                    }
+                    len=readle32(c, 0);
+                    c+=4;
+                    length-=4;
+                    if (len < 0 || len>length) {
+                        oi_warn(_("Invalid/corrupted comments in stream %d\n"),stream->num);
+                        break;
+                    }
+                    /*check_xiph_comment expects a null terminated comment*/
+                    comment=malloc((len+1)*sizeof(char));
+                    memcpy(comment,c,len);
+                    comment[len]=0;
+                    check_xiph_comment(stream, i, comment, len);
+                    free(comment);
+                    c+=len;
+                    length-=len;
+                }
+            }
+
+            inf->doneheaders++;
+            continue;
+        }
+        if(packet.bytes>=2 && memcmp(packet.packet, "Op",2)==0) {
+            oi_warn(_("WARNING: Invalid packet or misplaced header in stream %d\n"),stream->num);
+            continue;
+        }
+        if(packet.bytes<1) {
+            oi_warn(_("WARNING: Invalid zero byte packet in stream %d\n"),stream->num);
+            continue;
+        }
+        spp = packet_get_nb_frames(packet.packet,packet.bytes);
+        if(spp<1 || spp>48) {
+            oi_warn(_("WARNING: Invalid packet TOC in stream %d\n"),stream->num);
+            continue;
+        }
+        spp *= packet_get_samples_per_frame(packet.packet,48000);
+        if(spp<120 || spp>5760 || (spp%120)!=0) {
+            oi_warn(_("WARNING: Invalid packet TOC in stream %d\n"),stream->num);
+            continue;
+        }
+        inf->total_samples += spp;
+        page_samples += spp;
+        inf->total_packets++;
+        if(inf->max_packet_duration<spp)inf->max_packet_duration=spp;
+        if(inf->min_packet_duration>spp)inf->min_packet_duration=spp;
+        if(inf->max_packet_bytes<packet.bytes)inf->max_packet_bytes=packet.bytes;
+        if(inf->min_packet_bytes>packet.bytes)inf->min_packet_bytes=packet.bytes;
+    }
+
+    if(!header) {
+        ogg_int64_t gp = ogg_page_granulepos(page);
+        if(gp > 0) {
+            if(gp < inf->lastgranulepos)
+                oi_warn(_("WARNING: granulepos in stream %d decreases from %"
+                        I64FORMAT " to %" I64FORMAT "\n" ),
+                        stream->num, inf->lastgranulepos, gp);
+            if(inf->lastgranulepos==0 && inf->firstgranule==-1) {
+                /*First timed page, now we can recover the start time.*/
+                inf->firstgranule = gp-inf->total_samples;
+                if(inf->firstgranule<0) {
+                  /*There shouldn't be any negative samples after counting the samples in the page backwards
+                    from the first GP, but if this is the last page of the stream there may need to be to trim.*/
+                  if(!ogg_page_eos(page))oi_warn(_("WARNING: Samples with negative granpos in stream %d\n"),stream->num);
+                  else inf->firstgranule=0;
+                }
+            }
+            if(inf->total_samples<gp-inf->firstgranule)oi_warn(_("WARNING: Sample count behind granule (%lld<%lld) in stream %d\n"),
+                (long long)inf->total_samples,(long long)(gp-inf->firstgranule),stream->num);
+            if(!ogg_page_eos(page) && (inf->total_samples>gp-inf->firstgranule))
+                oi_warn(_("WARNING: Sample count ahead of granule (%lld>%lld) in stream %d\n"),
+                (long long)inf->total_samples,(long long)(gp-inf->firstgranule),stream->num);
+            inf->lastgranulepos = gp;
+        }
+        else if(packets) {
+            /* Only do this if we saw at least one packet ending on this page.
+             * It's legal (though very unusual) to have no packets in a page at
+             * all - this is occasionally used to have an empty EOS page */
+            oi_warn(_("Negative or zero granulepos (%" I64FORMAT ") on Opus stream outside of headers. This file was created by a buggy encoder\n"), gp);
+        }
+        inf->overhead_bytes += page->header_len;
+        if(page_samples)inf->last_page_duration = page_samples;
+        if(inf->max_page_duration<page_samples)inf->max_page_duration=page_samples;
+        if(inf->min_page_duration>page_samples)inf->min_page_duration=page_samples;
+        inf->total_pages++;
+    } else {
+        /* Headers and metadata are pure overhead. */
+        inf->overhead_bytes += page->header_len + page->body_len;
+    }
+    inf->bytes += page->header_len + page->body_len;
+}
+
+void info_opus_end(stream_processor *stream)
+{
+    misc_opus_info *inf = stream->data;
+
+    oi_info(_("Opus stream %d:\n"),stream->num);
+
+    if(inf && inf->total_packets>0){
+        int i;
+        long minutes, seconds, milliseconds;
+        double time;
+        time = (inf->lastgranulepos-inf->firstgranule-inf->oh.preskip) / 48000.;
+        minutes = (long)(time) / 60;
+        seconds = (long)(time - minutes*60);
+        milliseconds = (long)((time - minutes*60 - seconds)*1000);
+        if(inf->lastgranulepos-inf->firstgranule<inf->oh.preskip)
+           oi_warn(_("\tERROR: stream %d has a negative duration\n"),stream->num);
+        if((inf->total_samples-inf->last_page_duration)>(inf->lastgranulepos-inf->firstgranule))
+           oi_warn(_("\tWARNING: stream %d has holes or excessive end trimming\n"),stream->num);
+        if(inf->max_page_duration>=240000)
+           oi_warn(_("\tWARNING: stream %d has high muxing delay\n"),stream->num);
+        oi_info(_("\tPre-skip: %d\n"),inf->oh.preskip);
+        oi_info(_("\tPlayback gain: %0.1gdB\n"),inf->oh.gain*256.);
+        oi_info(_("\tChannels: %d\n"),inf->oh.channels);
+        if(inf->oh.input_sample_rate)oi_info(_("\tOriginal sample rate: %dHz\n"),inf->oh.input_sample_rate);
+        if(inf->oh.nb_streams>1)oi_info(_("\tStreams: %d, Coupled: %d\n"),inf->oh.nb_streams,inf->oh.nb_coupled);
+        if(inf->oh.channel_mapping>0) {
+          oi_info(_("\tChannel Mapping family: %d Map:"),inf->oh.channel_mapping);
+          for(i=0;i<inf->oh.channels;i++)oi_info("%s%d%s",i==0?" [":", ",inf->oh.stream_map[i],i==inf->oh.channels-1?"]\n":"");
+        }
+        if(inf->total_packets)oi_info(_("\tPacket duration: %6.1fms (max), %6.1fms (avg), %6.1fms (min)\n"),
+            inf->max_packet_duration/48.,inf->total_samples/(double)inf->total_packets/48.,inf->min_packet_duration/48.);
+        if(inf->total_pages)oi_info(_("\tPage duration: %8.1fms (max), %6.1fms (avg), %6.1fms (min)\n"),
+            inf->max_page_duration/48.,inf->total_samples/(double)inf->total_pages/48.,inf->min_page_duration/48.);
+        oi_info(_("\tTotal data length: %" I64FORMAT " bytes (overhead: %0.3g%%)\n"),inf->bytes,(double)inf->overhead_bytes/inf->bytes*100.);
+        oi_info(_("\tPlayback length: %ldm:%02ld.%03lds\n"), minutes, seconds, milliseconds);
+        oi_info(_("\tAverage bitrate: %0.4g kb/s, w/o overhead: %.04g kb/s%s\n"),inf->bytes*8/time/1000.0,(inf->bytes-inf->overhead_bytes)*8/time/1000.0,
+            (inf->min_packet_duration==inf->max_packet_duration)&&(inf->min_packet_bytes==inf->max_packet_bytes)?" (hard-CBR)":"");
+    } else {
+      oi_warn(_("\tWARNING: stream %d is empty\n"),stream->num);
+    }
+    free(stream->data);
+}
+
+void info_opus_start(stream_processor *stream)
+{
+    misc_opus_info *oinfo;
+
+    stream->type = "opus";
+    stream->process_page = info_opus_process;
+    stream->process_end = info_opus_end;
+
+    stream->data = calloc(1, sizeof(misc_opus_info));
+
+    oinfo = stream->data;
+    oinfo->firstgranule=-1;
+    oinfo->min_packet_duration=5760;
+    oinfo->min_page_duration=5760*255;
+    oinfo->min_packet_bytes=2147483647;
+}
--- /dev/null
+++ b/src/info_opus.h
@@ -1,0 +1,48 @@
+/* Copyright (C)2012 Gregory Maxwell
+   File: info_opus.h
+
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions
+   are met:
+
+   - Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+   - Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
+   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+typedef struct {
+    OpusHeader  oh;
+    ogg_int64_t bytes;
+    ogg_int64_t overhead_bytes;
+    ogg_int64_t lastgranulepos;
+    ogg_int64_t firstgranule;
+    ogg_int64_t total_samples;
+    ogg_int64_t total_packets;
+    ogg_int64_t total_pages;
+    ogg_int32_t last_page_duration;
+    ogg_int32_t max_page_duration;
+    ogg_int32_t min_page_duration;
+    ogg_int32_t max_packet_duration;
+    ogg_int32_t min_packet_duration;
+    ogg_int32_t max_packet_bytes;
+    ogg_int32_t min_packet_bytes;
+
+    int doneheaders;
+} misc_opus_info;
+
+void info_opus_start(stream_processor *stream);
--- a/src/opus_header.c
+++ b/src/opus_header.c
@@ -42,7 +42,7 @@
    int pos;
 } ROPacket;
 
-static int write_uint32(Packet *p, opus_uint32 val)
+static int write_uint32(Packet *p, ogg_uint32_t val)
 {
    if (p->pos>p->maxlen-4)
       return 0;
@@ -54,7 +54,7 @@
    return 1;
 }
 
-static int write_uint16(Packet *p, opus_uint16 val)
+static int write_uint16(Packet *p, ogg_uint16_t val)
 {
    if (p->pos>p->maxlen-2)
       return 0;
@@ -74,24 +74,24 @@
    return 1;
 }
 
-static int read_uint32(ROPacket *p, opus_uint32 *val)
+static int read_uint32(ROPacket *p, ogg_uint32_t *val)
 {
    if (p->pos>p->maxlen-4)
       return 0;
-   *val =  (opus_uint32)p->data[p->pos  ];
-   *val |= (opus_uint32)p->data[p->pos+1]<< 8;
-   *val |= (opus_uint32)p->data[p->pos+2]<<16;
-   *val |= (opus_uint32)p->data[p->pos+3]<<24;
+   *val =  (ogg_uint32_t)p->data[p->pos  ];
+   *val |= (ogg_uint32_t)p->data[p->pos+1]<< 8;
+   *val |= (ogg_uint32_t)p->data[p->pos+2]<<16;
+   *val |= (ogg_uint32_t)p->data[p->pos+3]<<24;
    p->pos += 4;
    return 1;
 }
 
-static int read_uint16(ROPacket *p, opus_uint16 *val)
+static int read_uint16(ROPacket *p, ogg_uint16_t *val)
 {
    if (p->pos>p->maxlen-2)
       return 0;
-   *val =  (opus_uint16)p->data[p->pos  ];
-   *val |= (opus_uint16)p->data[p->pos+1]<<8;
+   *val =  (ogg_uint16_t)p->data[p->pos  ];
+   *val |= (ogg_uint16_t)p->data[p->pos+1]<<8;
    p->pos += 2;
    return 1;
 }
@@ -112,14 +112,15 @@
    char str[9];
    ROPacket p;
    unsigned char ch;
-   opus_uint16 shortval;
+   ogg_uint16_t shortval;
 
    p.data = packet;
    p.maxlen = len;
    p.pos = 0;
    str[8] = 0;
+   if (len<19)return 0;
    read_chars(&p, (unsigned char*)str, 8);
-   if (strcmp(str, "OpusHead")!=0)
+   if (memcmp(str, "OpusHead", 8)!=0)
       return 0;
 
    if (!read_chars(&p, &ch, 1))
@@ -187,6 +188,7 @@
    p.data = packet;
    p.maxlen = len;
    p.pos = 0;
+   if (len<19)return 0;
    if (!write_chars(&p, (const unsigned char*)"OpusHead", 8))
       return 0;
    /* Version is 1 */
--- a/src/opus_header.h
+++ b/src/opus_header.h
@@ -1,13 +1,13 @@
 #ifndef OPUS_HEADER_H
 #define OPUS_HEADER_H
 
-#include <opus_types.h>
+#include <ogg/ogg.h>
 
 typedef struct {
    int version;
    int channels; /* Number of channels: 1..255 */
    int preskip;
-   opus_uint32 input_sample_rate;
+   ogg_uint32_t input_sample_rate;
    int gain; /* in dB S7.8 should be zero whenever possible */
    int channel_mapping;
    /* The rest is only used if channel_mapping != 0 */
--- a/src/opusdec.c
+++ b/src/opusdec.c
@@ -91,10 +91,6 @@
 #include "diag_range.h"
 #include "speex_resampler.h"
 
-#ifndef OPUSTOOLS_VERSION
-#define OPUSTOOLS_VERSION "unknown"
-#endif
-
 #define MINI(_a,_b)      ((_a)<(_b)?(_a):(_b))
 #define MAXI(_a,_b)      ((_a)>(_b)?(_a):(_b))
 #define CLAMPI(_a,_b,_c) (MAXI(_a,MINI(_b,_c)))
@@ -391,13 +387,13 @@
 
 void version(void)
 {
-   printf("opusdec opus-tools %s (based on %s)\n",OPUSTOOLS_VERSION,opus_get_version_string());
+   printf("opusdec %s %s (based on %s)\n",PACKAGE,VERSION,opus_get_version_string());
    printf("Copyright (C) 2008-2012 Xiph.Org Foundation\n");
 }
 
 void version_short(void)
 {
-   printf("opusdec opus-tools %s (based on %s)\n",OPUSTOOLS_VERSION,opus_get_version_string());
+   printf("opusdec %s %s (based on %s)\n",PACKAGE,VERSION,opus_get_version_string());
    printf("Copyright (C) 2008-2012 Xiph.Org Foundation\n");
 }
 
--- a/src/opusenc.c
+++ b/src/opusenc.c
@@ -68,10 +68,6 @@
 #define VG_CHECK(x,y)
 #endif
 
-#ifndef OPUSTOOLS_VERSION
-#define OPUSTOOLS_VERSION "unknown"
-#endif
-
 static void comment_init(char **comments, int* length, char *vendor_string);
 static void comment_add(char **comments, int* length, char *tag, char *val);
 
@@ -88,15 +84,15 @@
 #define IMIN(a,b) ((a) < (b) ? (a) : (b))   /**< Minimum int value.   */
 #define IMAX(a,b) ((a) > (b) ? (a) : (b))   /**< Maximum int value.   */
 
-void opustoolsversion(const char *version)
+void opustoolsversion(const char *opusversion)
 {
-  printf("opusenc opus-tools %s (using %s)\n",OPUSTOOLS_VERSION,version);
+  printf("opusenc %s %s (using %s)\n",PACKAGE,VERSION,opusversion);
   printf("Copyright (C) 2008-2012 Xiph.Org Foundation\n");
 }
 
-void opustoolsversion_short(const char *version)
+void opustoolsversion_short(const char *opusversion)
 {
-  printf("opusenc opus-tools %s (using %s)\n",OPUSTOOLS_VERSION,version);
+  printf("opusenc %s %s (using %s)\n",PACKAGE,VERSION,opusversion);
   printf("Copyright (C) 2008-2012 Xiph.Org Foundation\n");
 }
 
@@ -277,7 +273,7 @@
   for(i=0;i<256;i++)mapping[i]=i;
 
   opus_version=opus_get_version_string();
-  snprintf(vendor_string, sizeof(vendor_string), "opus-tools %s (using %s)\n",OPUSTOOLS_VERSION,opus_version);
+  snprintf(vendor_string, sizeof(vendor_string), "%s %s (using %s)\n",PACKAGE,VERSION,opus_version);
   comment_init(&comments, &comments_length, vendor_string);
 
 
--- /dev/null
+++ b/src/opusinfo.c
@@ -1,0 +1,638 @@
+/* Opusinfo
+ *
+ * A tool to describe opus file contents and metadata.
+ *
+ * This is a fork of ogginfo from the vorbis-tools package
+ * which has been cut down to only have opus support.
+ *
+ * Ogginfo is
+ * Copyright 2002-2005 Michael Smith <msmith@xiph.org>
+ * Licensed under the GNU GPL, distributed with this program.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <stdarg.h>
+#include <getopt.h>
+#include <math.h>
+
+#include <ogg/ogg.h>
+
+/*No NLS support for now*/
+#define _(X) (X)
+
+#include "opusinfo.h"
+#include "opus_header.h"
+#include "info_opus.h"
+
+#define CHUNK 4500
+
+static int printlots = 0;
+static int printinfo = 1;
+static int printwarn = 1;
+static int verbose = 1;
+
+static int flawed;
+
+#define CONSTRAINT_PAGE_AFTER_EOS   1
+#define CONSTRAINT_MUXING_VIOLATED  2
+
+static stream_set *create_stream_set(void) {
+    stream_set *set = calloc(1, sizeof(stream_set));
+
+    set->streams = calloc(5, sizeof(stream_processor));
+    set->allocated = 5;
+    set->used = 0;
+
+    return set;
+}
+
+void oi_info(char *format, ...)
+{
+    va_list ap;
+
+    if(!printinfo)
+        return;
+
+    va_start(ap, format);
+    vfprintf(stdout, format, ap);
+    va_end(ap);
+}
+
+void oi_warn(char *format, ...)
+{
+    va_list ap;
+
+    flawed = 1;
+    if(!printwarn)
+        return;
+
+    va_start(ap, format);
+    vfprintf(stdout, format, ap);
+    va_end(ap);
+}
+
+void oi_error(char *format, ...)
+{
+    va_list ap;
+
+    flawed = 1;
+
+    va_start(ap, format);
+    vfprintf(stdout, format, ap);
+    va_end(ap);
+}
+
+void check_xiph_comment(stream_processor *stream, int i, const char *comment,
+    int comment_length)
+{
+    char *sep = strchr(comment, '=');
+    int j;
+    int broken = 0;
+    unsigned char *val;
+    int bytes;
+    int remaining;
+
+    if(sep == NULL) {
+        oi_warn(_("WARNING: Comment %d in stream %d has invalid "
+              "format, does not contain '=': \"%s\"\n"),
+              i, stream->num, comment);
+             return;
+    }
+
+    for(j=0; j < sep-comment; j++) {
+        if(comment[j] < 0x20 || comment[j] > 0x7D) {
+            oi_warn(_("WARNING: Invalid comment fieldname in "
+                   "comment %d (stream %d): \"%s\"\n"),
+                   i, stream->num, comment);
+            broken = 1;
+            break;
+        }
+    }
+
+    if(broken)
+	return;
+
+    val = (unsigned char *)comment;
+
+    j = sep-comment+1;
+    while(j < comment_length)
+    {
+        remaining = comment_length - j;
+        if((val[j] & 0x80) == 0)
+            bytes = 1;
+        else if((val[j] & 0x40) == 0x40) {
+            if((val[j] & 0x20) == 0)
+                bytes = 2;
+            else if((val[j] & 0x10) == 0)
+                bytes = 3;
+            else if((val[j] & 0x08) == 0)
+                bytes = 4;
+            else if((val[j] & 0x04) == 0)
+                bytes = 5;
+            else if((val[j] & 0x02) == 0)
+                bytes = 6;
+            else {
+                oi_warn(_("WARNING: Illegal UTF-8 sequence in "
+                    "comment %d (stream %d): length marker wrong\n"),
+                    i, stream->num);
+                broken = 1;
+                break;
+            }
+        }
+        else {
+            oi_warn(_("WARNING: Illegal UTF-8 sequence in comment "
+                "%d (stream %d): length marker wrong\n"), i, stream->num);
+            broken = 1;
+            break;
+        }
+
+        if(bytes > remaining) {
+            oi_warn(_("WARNING: Illegal UTF-8 sequence in comment "
+                "%d (stream %d): too few bytes\n"), i, stream->num);
+            broken = 1;
+            break;
+        }
+
+        switch(bytes) {
+            case 1:
+                /* No more checks needed */
+                break;
+            case 2:
+                if((val[j+1] & 0xC0) != 0x80)
+                    broken = 1;
+                if((val[j] & 0xFE) == 0xC0)
+                    broken = 1;
+                break;
+            case 3:
+                if(!((val[j] == 0xE0 && val[j+1] >= 0xA0 && val[j+1] <= 0xBF &&
+                         (val[j+2] & 0xC0) == 0x80) ||
+                     (val[j] >= 0xE1 && val[j] <= 0xEC &&
+                         (val[j+1] & 0xC0) == 0x80 &&
+                         (val[j+2] & 0xC0) == 0x80) ||
+                     (val[j] == 0xED && val[j+1] >= 0x80 &&
+                         val[j+1] <= 0x9F &&
+                         (val[j+2] & 0xC0) == 0x80) ||
+                     (val[j] >= 0xEE && val[j] <= 0xEF &&
+                         (val[j+1] & 0xC0) == 0x80 &&
+                         (val[j+2] & 0xC0) == 0x80)))
+                     broken = 1;
+                 if(val[j] == 0xE0 && (val[j+1] & 0xE0) == 0x80)
+                     broken = 1;
+                 break;
+            case 4:
+                 if(!((val[j] == 0xF0 && val[j+1] >= 0x90 &&
+                         val[j+1] <= 0xBF &&
+                         (val[j+2] & 0xC0) == 0x80 &&
+                         (val[j+3] & 0xC0) == 0x80) ||
+                     (val[j] >= 0xF1 && val[j] <= 0xF3 &&
+                         (val[j+1] & 0xC0) == 0x80 &&
+                         (val[j+2] & 0xC0) == 0x80 &&
+                         (val[j+3] & 0xC0) == 0x80) ||
+                     (val[j] == 0xF4 && val[j+1] >= 0x80 &&
+                         val[j+1] <= 0x8F &&
+                         (val[j+2] & 0xC0) == 0x80 &&
+                         (val[j+3] & 0xC0) == 0x80)))
+                     broken = 1;
+                 if(val[j] == 0xF0 && (val[j+1] & 0xF0) == 0x80)
+                     broken = 1;
+                 break;
+             /* 5 and 6 aren't actually allowed at this point */
+             case 5:
+                 broken = 1;
+                 break;
+             case 6:
+                 broken = 1;
+                 break;
+         }
+
+         if(broken) {
+             char *simple = malloc (comment_length + 1);
+             char *seq = malloc (comment_length * 3 + 1);
+             static char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',
+                                  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+             int k, c1 = 0, c2 = 0;
+             for (k = 0; k < comment_length; k++) {
+               seq[c1++] = hex[((unsigned char)comment[k]) >> 4];
+               seq[c1++] = hex[((unsigned char)comment[k]) & 0xf];
+               seq[c1++] = ' ';
+
+               if(comment[k] < 0x20 || comment[k] > 0x7D)
+                 simple[c2++] = '?';
+               else
+                 simple[c2++] = comment[k];
+             }
+             seq[c1] = 0;
+             simple[c2] = 0;
+             oi_warn(_("WARNING: Illegal UTF-8 sequence in comment "
+                   "%d (stream %d): invalid sequence \"%s\": %s\n"), i,
+                   stream->num, simple, seq);
+             broken = 1;
+             free (simple);
+             free (seq);
+             break;
+         }
+
+         j += bytes;
+     }
+
+     if(!broken) {
+         oi_info("\t%s\n", comment);
+     }
+}
+
+static void process_null(stream_processor *stream, ogg_page *page)
+{
+    /* This is for invalid streams. */
+    (void)stream;
+    (void)page;
+}
+
+static void process_other(stream_processor *stream, ogg_page *page )
+{
+    ogg_packet packet;
+
+    ogg_stream_pagein(&stream->os, page);
+
+    while(ogg_stream_packetout(&stream->os, &packet) > 0) {
+        /* Should we do anything here? Currently, we don't */
+    }
+}
+
+
+static void free_stream_set(stream_set *set)
+{
+    int i;
+    for(i=0; i < set->used; i++) {
+        if(!set->streams[i].end) {
+            oi_warn(_("WARNING: EOS not set on stream %d\n"),
+                    set->streams[i].num);
+            if(set->streams[i].process_end)
+                set->streams[i].process_end(&set->streams[i]);
+        }
+        ogg_stream_clear(&set->streams[i].os);
+    }
+
+    free(set->streams);
+    free(set);
+}
+
+static int streams_open(stream_set *set)
+{
+    int i;
+    int res=0;
+    for(i=0; i < set->used; i++) {
+        if(!set->streams[i].end)
+            res++;
+    }
+
+    return res;
+}
+
+static void null_start(stream_processor *stream)
+{
+    stream->process_end = NULL;
+    stream->type = "invalid";
+    stream->process_page = process_null;
+}
+
+static void other_start(stream_processor *stream, char *type)
+{
+    if(type)
+        stream->type = type;
+    else
+        stream->type = "unknown";
+    stream->process_page = process_other;
+    stream->process_end = NULL;
+}
+
+static stream_processor *find_stream_processor(stream_set *set, ogg_page *page)
+{
+    ogg_uint32_t serial = ogg_page_serialno(page);
+    int i;
+    int invalid = 0;
+    int constraint = 0;
+    stream_processor *stream;
+
+    for(i=0; i < set->used; i++) {
+        if(serial == set->streams[i].serial) {
+            /* We have a match! */
+            stream = &(set->streams[i]);
+
+            set->in_headers = 0;
+            /* if we have detected EOS, then this can't occur here. */
+            if(stream->end) {
+                stream->isillegal = 1;
+                stream->constraint_violated = CONSTRAINT_PAGE_AFTER_EOS;
+                return stream;
+            }
+
+            stream->isnew = 0;
+            stream->start = ogg_page_bos(page);
+            stream->end = ogg_page_eos(page);
+            stream->serial = serial;
+            return stream;
+        }
+    }
+
+    /* If there are streams open, and we've reached the end of the
+     * headers, then we can't be starting a new stream.
+     * XXX: might this sometimes catch ok streams if EOS flag is missing,
+     * but the stream is otherwise ok?
+     */
+    if(streams_open(set) && !set->in_headers) {
+        constraint = CONSTRAINT_MUXING_VIOLATED;
+        invalid = 1;
+    }
+
+    set->in_headers = 1;
+
+    if(set->allocated < set->used)
+        stream = &set->streams[set->used];
+    else {
+        set->allocated += 5;
+        set->streams = realloc(set->streams, sizeof(stream_processor)*
+                set->allocated);
+        stream = &set->streams[set->used];
+    }
+    set->used++;
+    stream->num = set->used; /* We count from 1 */
+
+    stream->isnew = 1;
+    stream->isillegal = invalid;
+    stream->constraint_violated = constraint;
+
+    {
+        int res;
+        int has_oi_supported=0;
+        ogg_packet packet;
+
+        /* We end up processing the header page twice, but that's ok. */
+        ogg_stream_init(&stream->os, serial);
+        ogg_stream_pagein(&stream->os, page);
+        res = ogg_stream_packetout(&stream->os, &packet);
+        if(res <= 0) {
+            oi_warn(_("WARNING: Invalid header page, no packet found\n"));
+            null_start(stream);
+        }
+        else if(packet.bytes >= 19 && memcmp(packet.packet, "OpusHead", 8)==0)
+            info_opus_start(stream);
+        else if(packet.bytes >= 7 && memcmp(packet.packet, "\x01vorbis", 7)==0) {
+            other_start(stream, "Vorbis");
+            has_oi_supported=1;
+        } else if(packet.bytes >= 7 && memcmp(packet.packet, "\x80theora", 7)==0) {
+            other_start(stream, "Theora");
+            has_oi_supported=1;
+        } else if(packet.bytes >= 8 && memcmp(packet.packet, "OggMIDI\0", 8)==0)
+            other_start(stream, "MIDI");
+        else if(packet.bytes >= 5 && memcmp(packet.packet, "\177FLAC", 5)==0)
+            other_start(stream, "FLAC");
+        else if(packet.bytes == 4 && memcmp(packet.packet, "fLaC", 4)==0)
+            other_start(stream, "FLAC (legacy)");
+        else if(packet.bytes >= 8 && memcmp(packet.packet, "Speex   ", 8)==0)
+            other_start(stream, "speex");
+        else if(packet.bytes >= 8 && memcmp(packet.packet, "fishead\0", 8)==0)
+            other_start(stream, "skeleton");
+        else if(packet.bytes >= 5 && memcmp(packet.packet, "BBCD\0", 5)==0)
+            other_start(stream, "dirac");
+        else if(packet.bytes >= 8 && memcmp(packet.packet, "KW-DIRAC", 8)==0)
+            other_start(stream, "dirac (legacy)");
+        else if(packet.bytes >= 8 && memcmp(packet.packet, "\x80kate\0\0\0", 8)==0) {
+            other_start(stream, "Kate");
+            has_oi_supported=1;
+        } else
+            other_start(stream, NULL);
+
+        res = ogg_stream_packetout(&stream->os, &packet);
+        if(res > 0) {
+            oi_warn(_("WARNING: Invalid header page in stream %d, "
+                              "contains multiple packets\n"), stream->num);
+        }
+        if(has_oi_supported)oi_info(_("Use ogginfo for more information on this file.\n"));
+
+        /* re-init, ready for processing */
+        ogg_stream_clear(&stream->os);
+        ogg_stream_init(&stream->os, serial);
+   }
+
+   stream->start = ogg_page_bos(page);
+   stream->end = ogg_page_eos(page);
+   stream->serial = serial;
+   stream->shownillegal = 0;
+   stream->seqno = ogg_page_pageno(page);
+
+   if(stream->serial == 0 || stream->serial == 0xFFFFFFFFUL) {
+       oi_info(_("Note: Stream %d has serial number %d, which is legal but may "
+              "cause problems with some tools.\n"), stream->num,
+               stream->serial);
+   }
+
+   return stream;
+}
+
+static int get_next_page(FILE *f, ogg_sync_state *sync, ogg_page *page,
+        ogg_int64_t *written)
+{
+    int ret;
+    char *buffer;
+    int bytes;
+
+    while((ret = ogg_sync_pageseek(sync, page)) <= 0) {
+        if(ret < 0) {
+            /* unsynced, we jump over bytes to a possible capture - we don't need to read more just yet */
+            oi_warn(_("WARNING: Hole in data (%d bytes) found at approximate offset %" I64FORMAT " bytes. Corrupted Ogg.\n"), -ret, *written);
+            continue;
+        }
+
+        /* zero return, we didn't have enough data to find a whole page, read */
+        buffer = ogg_sync_buffer(sync, CHUNK);
+        bytes = fread(buffer, 1, CHUNK, f);
+        if(bytes <= 0) {
+            ogg_sync_wrote(sync, 0);
+            return 0;
+        }
+        ogg_sync_wrote(sync, bytes);
+        *written += bytes;
+    }
+
+    return 1;
+}
+
+static void process_file(char *filename) {
+    FILE *file = fopen(filename, "rb");
+    ogg_sync_state sync;
+    ogg_page page;
+    stream_set *processors = create_stream_set();
+    int gotpage = 0;
+    ogg_int64_t written = 0;
+
+    if(!file) {
+        oi_error(_("Error opening input file \"%s\": %s\n"), filename,
+                    strerror(errno));
+        return;
+    }
+
+    printf(_("Processing file \"%s\"...\n\n"), filename);
+
+    ogg_sync_init(&sync);
+
+    while(get_next_page(file, &sync, &page, &written)) {
+        stream_processor *p = find_stream_processor(processors, &page);
+        gotpage = 1;
+
+        if(!p) {
+            oi_error(_("Could not find a processor for stream, bailing\n"));
+            return;
+        }
+
+        if(p->isillegal && !p->shownillegal) {
+            char *constraint;
+            switch(p->constraint_violated) {
+                case CONSTRAINT_PAGE_AFTER_EOS:
+                    constraint = _("Page found for stream after EOS flag");
+                    break;
+                case CONSTRAINT_MUXING_VIOLATED:
+                    constraint = _("Ogg muxing constraints violated, new "
+                                   "stream before EOS of all previous streams");
+                    break;
+                default:
+                    constraint = _("Error unknown.");
+            }
+
+            oi_warn(_("WARNING: illegally placed page(s) for logical stream %d\n"
+                   "This indicates a corrupt Ogg file: %s.\n"),
+                    p->num, constraint);
+            p->shownillegal = 1;
+            /* If it's a new stream, we want to continue processing this page
+             * anyway to suppress additional spurious errors
+             */
+            if(!p->isnew)
+                continue;
+        }
+
+        if(p->isnew) {
+            oi_info(_("New logical stream (#%d, serial: %08x): type %s\n"),
+                    p->num, p->serial, p->type);
+            if(!p->start)
+                oi_warn(_("WARNING: stream start flag not set on stream %d\n"),
+                        p->num);
+        }
+        else if(p->start)
+            oi_warn(_("WARNING: stream start flag found in mid-stream "
+                      "on stream %d\n"), p->num);
+
+        if(p->seqno++ != ogg_page_pageno(&page)) {
+            if(!p->lostseq)
+                oi_warn(_("WARNING: sequence number gap in stream %d. Got page "
+                       "%ld when expecting page %ld. Indicates missing data.\n"
+                       ), p->num, ogg_page_pageno(&page), p->seqno - 1);
+            p->seqno = ogg_page_pageno(&page);
+            p->lostseq = 1;
+        }
+        else
+            p->lostseq = 0;
+
+        if(!p->isillegal) {
+            p->process_page(p, &page);
+
+            if(p->end) {
+                if(p->process_end)
+                    p->process_end(p);
+                oi_info(_("Logical stream %d ended\n"), p->num);
+                p->isillegal = 1;
+                p->constraint_violated = CONSTRAINT_PAGE_AFTER_EOS;
+            }
+        }
+    }
+
+    if(!gotpage)
+        oi_error(_("ERROR: No Ogg data found in file \"%s\".\n"
+                "Input probably not Ogg.\n"), filename);
+
+    free_stream_set(processors);
+
+    ogg_sync_clear(&sync);
+
+    fclose(file);
+}
+
+static void version (void) {
+    printf (_("opusinfo from %s %s\n"), PACKAGE, VERSION);
+}
+
+static void usage(void) {
+    version ();
+    printf (_(" by the Xiph.Org Foundation (http://www.xiph.org/)\n\n"));
+    printf(_("(c) 2003-2005 Michael Smith <msmith@xiph.org>\n"
+             "(c) 2012 Gregory Maxwell <greg@xiph.org>\n\n"
+             "Opusinfo is a version of ogginfo from the vorbis-tools package which only works with opus.\n\n"
+             "Usage: opusinfo [flags] file1.opua [file2.opua ... fileN.opus]\n"
+             "Flags supported:\n"
+             "\t-h Show this help message\n"
+             "\t-q Make less verbose. Once will remove detailed informative\n"
+             "\t   messages, two will remove warnings\n"
+             "\t-v Make more verbose. This may enable more detailed checks\n"
+             "\t   for some stream types.\n"));
+    printf (_("\t-V Output version information and exit\n"));
+}
+
+int main(int argc, char **argv) {
+    int f, ret;
+
+    if(argc < 2) {
+        fprintf(stdout,
+                _("Usage: opusinfo [flags] file1.opus [file2.opus ... fileN.opus]\n"
+                  "\n"
+                  "opusinfo is a tool for printing information about Opus files\n"
+                  "and for diagnosing problems with them.\n"
+                  "Full help shown with \"opusinfo -h\".\n"));
+        exit(1);
+    }
+
+    while((ret = getopt(argc, argv, "hqvV")) >= 0) {
+        switch(ret) {
+            case 'h':
+                usage();
+                return 0;
+            case 'V':
+                version();
+                return 0;
+            case 'v':
+                verbose++;
+                break;
+            case 'q':
+                verbose--;
+                break;
+        }
+    }
+
+    if(verbose > 1)
+        printlots = 1;
+    if(verbose < 1)
+        printinfo = 0;
+    if(verbose < 0)
+        printwarn = 0;
+
+    if(optind >= argc) {
+        fprintf(stderr,
+                _("No input files specified. \"opusinfo -h\" for help\n"));
+        return 1;
+    }
+
+    ret = 0;
+
+    for(f=optind; f < argc; f++) {
+        flawed = 0;
+        process_file(argv[f]);
+        if(flawed != 0)
+            ret = flawed;
+    }
+
+    return ret;
+}
--- /dev/null
+++ b/src/opusinfo.h
@@ -1,0 +1,51 @@
+/* Ogginfo
+ *
+ * A tool to describe ogg file contents and metadata.
+ *
+ * Copyright 2002-2005 Michael Smith <msmith@xiph.org>
+ * Licensed under the GNU GPL, distributed with this program.
+ */
+
+/*No NLS support for now*/
+#define _(X) (X)
+
+#ifdef _WIN32
+#define I64FORMAT "I64d"
+#else
+#define I64FORMAT "lld"
+#endif
+
+typedef struct _stream_processor {
+    void (*process_page)(struct _stream_processor *, ogg_page *);
+    void (*process_end)(struct _stream_processor *);
+    int isillegal;
+    int constraint_violated;
+    int shownillegal;
+    int isnew;
+    long seqno;
+    int lostseq;
+
+    int start;
+    int end;
+
+    int num;
+    char *type;
+
+    ogg_uint32_t serial; /* must be 32 bit unsigned */
+    ogg_stream_state os;
+    void *data;
+} stream_processor;
+
+typedef struct {
+    stream_processor *streams;
+    int allocated;
+    int used;
+
+    int in_headers;
+} stream_set;
+
+
+void oi_info(char *format, ...);
+void oi_warn(char *format, ...);
+void oi_error(char *format, ...);
+void check_xiph_comment(stream_processor *stream, int i, const char *comment, int comment_length);
--