[xiph-cvs] cvs commit: ogg-tools/omplay .cvsignore COPYING ChangeLog Makefile README midi.c midi.h omplay.c

Jack Moffitt jack at xiph.org
Sat Sep 22 21:18:34 PDT 2001



jack        01/09/22 21:18:34

  Added:       omplay   .cvsignore COPYING ChangeLog Makefile README midi.c
                        midi.h omplay.c
  Log:
  Working Ogg MIDI player.

Revision  Changes    Path
1.1                  ogg-tools/omplay/.cvsignore

Index: .cvsignore
===================================================================
*.o
omplay

1.1                  ogg-tools/omplay/COPYING

Index: COPYING
===================================================================
                    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.

1.1                  ogg-tools/omplay/ChangeLog

Index: ChangeLog
===================================================================
omplay 1.0

        * First release

1.1                  ogg-tools/omplay/Makefile

Index: Makefile
===================================================================
CFLAGS=-O3 -g
LDFLAGS=
LIBS=-logg -lvorbis -lasound

all: omplay

omplay: omplay.o midi.o
        $(CC) $(CFLAGS) -o $@ omplay.o midi.o $(LDFLAGS) $(LIBS)

omplay.o: omplay.c

midi.o: midi.c midi.h

.c.o:
        $(CC) $(CFLAGS) -c -o $@ $<

clean:
        rm -f omplay midi.o omplay.o

1.1                  ogg-tools/omplay/README

Index: README
===================================================================
This is omplay, the Ogg MIDI player.  It plays files that contain
MIDI and Vorbis substreams (in either order).  The files are played
synchronized.  It supports pause, stop and fast-forward via status files.

This player is dependent on ALSA (0.9.x+).  Currently this code will only
work with CVS versions of ALSA with a few patches.  Hopefully these
patches will become part of the stock ALSA.

The patches are included in alsa-cvs.patch. 

A test file test.ogg is included which contains test tones in both MIDI and
in Vorbis as well as short musical passages.

1.1                  ogg-tools/omplay/midi.c

Index: midi.c
===================================================================
/*****************************************************************

    This file is part of omplay.

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

    omplay 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 omplay; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    This code is copyright (c) 2001 by the Xiph.org Foundation 
    (http://www.xiph.org/).
**********************************************************************/

/* midi.c
** 
** Ogg MIDI decode routines
*/

#include <stdio.h>
#include <sys/asoundlib.h>
#include <ogg/ogg.h>
#include <vorbis/codec.h>
#include "midi.h"

int midi_header_init(midi_info_t *mi)
{
        memset(mi, 0, sizeof(midi_info_t));
       
        return 0;
}

int midi_header_clear(midi_info_t *mi)
{
        if (mi->data != NULL) free(mi->data);
        memset(mi, 0, sizeof(midi_info_t));

        return 0;
}

int midi_header_set_queue(midi_info_t *mi, int q)
{
        mi->q = q;
        return 0;
}

int midi_headerin(midi_info_t *mi, ogg_packet *op)
{
        int temp;

        // parse the packet for the OggMIDI header

        // make sure we have enough to read the version
        if (op->bytes < 9) 
                return EHEADER;
        
        if (memcmp(op->packet, "OggMIDI\000", 8) != 0) 
                return EHEADER;

        mi->version = op->packet[8] & 0xFF;
        if (mi->version != 0)
                return EVERSION;

        // version 0 has a 12 byte header; no more no less
        if (op->bytes != 12)
                return EHEADER;

        mi->smtpe = op->packet[9] & 0xFF;
        mi->ticks = (op->packet[11] << 8) | op->packet[10];
        
        // set tempo to default
        mi->tempo = 500000;

        return 0;
}

int midi_packetin(midi_info_t *mi, ogg_packet *op)
{
        if (mi->data != NULL) free(mi->data);

        mi->data = (unsigned char *)malloc(op->bytes);
        mi->size = op->bytes;
        mi->pos = 0;
        memcpy(mi->data, op->packet, mi->size);

        return 0;
}

tatic unsigned long _data_left(midi_info_t *mi)
{
        return (mi->size - mi->pos);
}

tatic int _read_byte(midi_info_t *mi)
{
        if (mi->pos >= mi->size) return -1;

        return mi->data[mi->pos++] & 0xFF;
}
        

tatic int64_t _read_var_value(midi_info_t *mi)
{
        unsigned long stamp = 0;
        int byte;

        do {
                byte = _read_byte(mi);
                if (byte == -1) return -1;
                stamp <<= 7;
                stamp |= byte & 0x7F;
        } while ((byte & 0x80) == 0x80);

        return stamp;
}

int midi_eventout(midi_info_t *mi, snd_seq_event_t *ev)
{
        int64_t stamp, length;
        int status, data;
        int tempo;
        int err;
        void *buf;

        if (_data_left(mi) == 0) return EDATA;

        snd_seq_ev_clear(ev);
        snd_seq_ev_set_fixed(ev);
        // We know at this point that the entire event
        // is within the packet, since it's illegal
        // to span packet boundries for events.
        // this makes our lives _so_ much easier.

        stamp = _read_var_value(mi);
        if (stamp < 0) return EEVENT;
        mi->time += stamp;
        snd_seq_ev_schedule_tick(ev, mi->q, 0, mi->time);

        status = _read_byte(mi);
        if (status < 0) return EEVENT;

        switch (status & 0xF0) {
        case 0x80:
                ev->type = SND_SEQ_EVENT_NOTEOFF;
                ev->data.note.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.note.note = data & 0x7F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.note.velocity = data & 0x7F;
                break;
        case 0x90:
                ev->type = SND_SEQ_EVENT_NOTEON;
                ev->data.note.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.note.note = data & 0x7F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.note.velocity = data & 0x7F;
                break;
        case 0xA0:
                ev->type = SND_SEQ_EVENT_KEYPRESS;
                ev->data.note.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.note.note = data & 0x7F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.note.velocity = data & 0x7F;
                break;
        case 0xB0:
                ev->type = SND_SEQ_EVENT_CONTROLLER;
                ev->data.control.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.control.param = data & 0x7F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.control.value = data & 0x7F;
                break;
        case 0xC0:
                ev->type = SND_SEQ_EVENT_PGMCHANGE;
                ev->data.control.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.control.value = data & 0x7F;
                break;
        case 0xD0:
                ev->type = SND_SEQ_EVENT_CHANPRESS;
                ev->data.control.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0 ) return EEVENT;
                ev->data.control.value = data & 0x7F;
                break;
        case 0xE0:
                ev->type = SND_SEQ_EVENT_PITCHBEND;
                ev->data.control.channel = status & 0x0F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.control.param = data & 0x7F;
                data = _read_byte(mi);
                if (data < 0) return EEVENT;
                ev->data.control.value = data & 0x7F;
                break;
        case 0xF0:
                // these events are special
                // we should not send only the tempo changes
                // and sysex events
                switch (status & 0xFF) {
                case 0xF0:
                        ev->type = SND_SEQ_EVENT_SYSEX;
                        length = _read_var_value(mi);
                        if (length < 1) return EEVENT;
                        if (_data_left(mi) < length) return EEVENT;
                        ev->data.ext.len = length;
                        buf = (void *)malloc(length);
                        if (buf == NULL) return EMALLOC;
                        memcpy(buf, &mi->data[mi->pos], length);
                        snd_seq_ev_set_variable(ev, length, buf);
                        mi->pos += length;
                        break;
                case 0xFF:
                        data = _read_byte(mi);
                        if (data < 0) return EEVENT;

                        if (data == 0x51) {
                                length = _read_var_value(mi);
                                if (length != 3) return EEVENT;
                                if (_data_left(mi) < length) return EEVENT;
                                ev->type = SND_SEQ_EVENT_TEMPO;
                                ev->data.queue.queue = mi->q;
                                ev->data.queue.param.value = (mi->data[mi->pos] << 16) | (mi->data[mi->pos+1] << 8) | (mi->data[mi->pos+2]);
                                mi->pos += length;
                        } else {
                                snd_seq_ev_clear(ev);
                                // skip this event
                                length = _read_var_value(mi);
                                if (length < 0) return EEVENT;
                                if (_data_left(mi) < length) return EEVENT;
                                mi->pos += length;
                        }
                        break;
                default:
                        return EEVENT;
                }
                break;
        default:
                return EEVENT;
        }

        return 0;
}

1.1                  ogg-tools/omplay/midi.h

Index: midi.h
===================================================================
/*****************************************************************

    This file is part of omplay.

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

    omplay 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 omplay; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    This code is copyright (c) 2001 by the Xiph.org Foundation 
    (http://www.xiph.org/).
**********************************************************************/

/* midi.h
** 
** Ogg MIDI decode routines header file
*/

#ifndef __MIDI_H__
#define __MIDI_H__

#include <ogg/ogg.h>
#include <sys/asoundlib.h>

typedef struct {
        int version;
        
        int smtpe;
        int ticks;

        u_int64_t time;

        unsigned long tempo;

        unsigned long pos;
        unsigned long size;
        unsigned char *data;

        int q;
} midi_info_t;

int midi_header_init(midi_info_t *mi);
int midi_header_clear(midi_info_t *mi);
int midi_header_set_queue(midi_info_t *mi, int q);
int midi_headerin(midi_info_t *mi, ogg_packet *op);
int midi_packetin(midi_info_t *mi, ogg_packet *op);
int midi_eventout(midi_info_t *mi, snd_seq_event_t *ev);

#define EDATA -1
#define EHEADER -2
#define EVERSION -3
#define EEVENT -4
#define EMALLOC -5

#endif  /* __MIDI_H__ */

1.1                  ogg-tools/omplay/omplay.c

Index: omplay.c
===================================================================
/*****************************************************************

    This file is part of omplay.

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

    omplay 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 omplay; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    This code is copyright (c) 2001 by the Xiph.org Foundation 
    (http://www.xiph.org/).
**********************************************************************/

/* omplay.c
**
** main program for omplay, the Ogg MIDI player
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <sys/asoundlib.h>

#include <ogg/ogg.h>
#include <vorbis/codec.h>

#include "midi.h"

#define STATUS_FILE_PLAY "status.PLAY"
#define STATUS_FILE_PAUSE "status.PAUSE"
#define STATUS_FILE_FFWD "status.FFWD"
#define FFWD_SPEED 4

typedef struct status_file_tag
{
        int fd;
        char *filemap;
        size_t len;
        int status;
} status_file_t;

typedef struct device_tag
{
        // settings
        char *pcm_device;
        snd_seq_addr_t seq_addr;

        // device handles
        snd_pcm_t *pcmhandle;
        snd_seq_t *seqhandle;
        // audio device stuff
        snd_pcm_hw_params_t *hwparams;
        snd_pcm_sw_params_t *swparams;
        snd_pcm_info_t *pcminfo;
        snd_pcm_status_t *pcmstat;
        int card;
        int device;
        int subdevice;
        // midi device stuff
        int q;
        int srcport;

        FILE *fp;
        ogg_sync_state oy;
        ogg_stream_state *os_v;
        ogg_stream_state *os_m;

        int midi_serialno;
        int vorbis_serialno;

        midi_info_t mi;
        vorbis_info vi;
        vorbis_comment vc;
        vorbis_dsp_state vd;
        vorbis_block vb;

        // status files
        status_file_t play;
        status_file_t pause;
        status_file_t ffwd;

        int fast_forwarding;
        int verbose;
} device_t;

device_t device;

int open_devices(void)
{
        int err;
        
        err = snd_pcm_open(&device.pcmhandle, device.pcm_device, SND_PCM_STREAM_PLAYBACK, 0);
        if (err < 0) return err;
        err = snd_seq_open(&device.seqhandle, "hw", SND_SEQ_OPEN_DUPLEX, 0);
        if (err < 0) {
                snd_pcm_close(device.pcmhandle);
                return err;
        }

        return err;
}

void close_devices(void)
{
        snd_seq_free_queue(device.seqhandle, device.q);
        snd_seq_close(device.seqhandle);
        snd_pcm_close(device.pcmhandle);
}

int configure_audio_device(void)
{
        int err;

        // hardware parameters
        snd_pcm_hw_params_malloc(&device.hwparams);
        err = snd_pcm_hw_params_any(device.pcmhandle, device.hwparams);
        if (err < 0) return err;
        err = snd_pcm_hw_params_set_access(device.pcmhandle, device.hwparams, 
                                           SND_PCM_ACCESS_RW_INTERLEAVED);
        if (err < 0) return err;
        err = snd_pcm_hw_params_set_format(device.pcmhandle, device.hwparams, 
                                           SND_PCM_FORMAT_S16_LE);
        if (err < 0) return err;
        err = snd_pcm_hw_params_set_channels(device.pcmhandle, device.hwparams, 
                                             device.vi.channels);
        if (err < 0) return err;
        err = snd_pcm_hw_params_set_rate_near(device.pcmhandle, device.hwparams,
                                              device.vi.rate, 0);
        if (err < 0) return err;
        err = snd_pcm_hw_params_set_period_size(device.pcmhandle, device.hwparams,
                                                32, 0);
        if (err < 0) return err;
        err = snd_pcm_hw_params_set_periods(device.pcmhandle, device.hwparams,
                                            100, 0);
        if (err < 0) return err;
        err = snd_pcm_hw_params(device.pcmhandle, device.hwparams);
        if (err < 0) return err;

        return 0;

        // software parameters
        snd_pcm_sw_params_malloc(&device.swparams);
        err = snd_pcm_sw_params_set_xfer_align(device.pcmhandle, device.swparams, 1);
        if (err < 0) return err;
        err = snd_pcm_sw_params(device.pcmhandle, device.swparams);
        if (err < 0) return err;
        
        return 0;
}

int configure_midi_device(void)
{
        int err;

        device.q = snd_seq_alloc_queue(device.seqhandle);
        err = snd_seq_create_simple_port(device.seqhandle, NULL,
                                         SND_SEQ_PORT_CAP_WRITE |
                                         SND_SEQ_PORT_CAP_SUBS_WRITE |
                                         SND_SEQ_PORT_CAP_READ,
                                         SND_SEQ_PORT_TYPE_MIDI_GENERIC);
        if (err < 0) {
                snd_seq_free_queue(device.seqhandle, device.q);
                return err;
        }
        device.srcport = err;
        err = snd_seq_connect_to(device.seqhandle, device.srcport,
                                 device.seq_addr.client, device.seq_addr.port);
        if (err < 0) {
                snd_seq_free_queue(device.seqhandle, device.q);
                return err;
        }

        return 0;
}

int set_midi_tempo(void)
{
        int err;
        snd_seq_queue_tempo_t *qtempo;

        snd_seq_queue_tempo_alloca(&qtempo);
        snd_seq_queue_tempo_set_ppq(qtempo, device.mi.ticks);
        snd_seq_queue_tempo_set_tempo(qtempo, device.mi.tempo);
        err = snd_seq_set_queue_tempo(device.seqhandle, device.q, qtempo);
        if (err < 0) {
                printf("Error setting queue tempo\n");
                snd_seq_free_queue(device.seqhandle, device.q);
                return err;
        }

        return 0;
}

int sync_devices(void)
{
        int err;
        snd_seq_queue_timer_t *qt;
        snd_timer_id_t *qtid;

        // get pcm device information
        snd_pcm_info_malloc(&device.pcminfo);
        err = snd_pcm_info(device.pcmhandle, device.pcminfo);
        if (err < 0) return err;
        err = snd_pcm_info_get_card(device.pcminfo);
        if (err < 0) return err;
        device.card = err;
        err = snd_pcm_info_get_device(device.pcminfo);
        if (err < 0) return err;
        device.device = err;
        err = snd_pcm_info_get_subdevice(device.pcminfo);
        if (err < 0) return err;
        device.subdevice = err << 1;

        if (device.verbose >= 1)
                printf("using card %d, device %d, subdev %d\n", device.card, device.device, device.subdevice);

        snd_pcm_status_malloc(&device.pcmstat);

        // setup the queue timer

        snd_seq_queue_timer_alloca(&qt);
        snd_timer_id_alloca(&qtid);

        err = snd_seq_get_queue_timer(device.seqhandle, device.q, qt);
        if (err < 0) {
                return err;
        }
        snd_timer_id_set_class(qtid, SND_TIMER_CLASS_PCM);
        snd_timer_id_set_sclass(qtid, SND_TIMER_SCLASS_NONE);
        snd_timer_id_set_card(qtid, device.card);
        snd_timer_id_set_device(qtid, device.device);
        snd_timer_id_set_subdevice(qtid, device.subdevice);
        snd_seq_queue_timer_set_type(qt, SND_SEQ_TIMER_ALSA);
        snd_seq_queue_timer_set_id(qt, qtid);
        snd_seq_set_queue_timer(device.seqhandle, device.q, qt);
        return 0;
}

void open_file(char *filename)
{
        int numpages = 0;
        ogg_stream_state *temp;
        ogg_page og;
        int err = 0;
        ogg_packet op;
        int bytes;
        int serialno;
        int i;
        char *buffer;
        char buf[1024];

        // open the file
        device.fp = fopen(filename, "r");
        if (device.fp == NULL) {
                printf("Could not open file %s.\n", filename);
                close_devices();
                exit(1);
        }

        // setup sync and stream states
        ogg_sync_init(&device.oy);
        device.os_m = (ogg_stream_state *)malloc(sizeof(ogg_stream_state));
        device.os_v = (ogg_stream_state *)malloc(sizeof(ogg_stream_state));
        
        // get the headers
        while (!feof(device.fp) && numpages < 2) {
                while (numpages < 2 && (err = ogg_sync_pageout(&device.oy, &og)) == 1) {
                        // play stuff here
                        if (numpages == 0) {
                                ogg_stream_init(device.os_v, ogg_page_serialno(&og));
                                device.vorbis_serialno = ogg_page_serialno(&og);
                                if (ogg_stream_pagein(device.os_v, &og) < 0) {
                                        printf("Error reading first page\n");
                                        close_devices();
                                        exit(1);
                                }
                        }
                        if (numpages == 1) {
                                ogg_stream_init(device.os_m, ogg_page_serialno(&og));
                                device.midi_serialno = ogg_page_serialno(&og);
                                if (ogg_stream_pagein(device.os_m, &og) < 0) {
                                        printf("Error reading second page\n");
                                        close_devices();
                                        exit(1);
                                }
                        }

                        numpages++;
                }
                
                if (err < 0) break;

                bytes = fread(buf, 1, 1024, device.fp);
                buffer = ogg_sync_buffer(&device.oy, bytes);
                memcpy(buffer, buf, bytes);
                ogg_sync_wrote(&device.oy, bytes);
        }

        if (numpages != 2) {
                printf("Couldn't read headers.\n");
                close_devices();
                exit(1);
        }

        // first try to verify os_v as a vorbis stream.
        vorbis_info_init(&device.vi);
        vorbis_comment_init(&device.vc);
        if (ogg_stream_packetpeek(device.os_v, &op) < 0) {
                printf("Error reading intial header packet\n");
                close_devices();
                exit(1);
        }

        if (vorbis_synthesis_headerin(&device.vi, &device.vc, &op) < 0) {
                // this is not the vorbis stream
                // so swap the stream states
                temp = device.os_v;
                device.os_v = device.os_m;
                device.os_m = temp;

                serialno = device.vorbis_serialno;
                device.vorbis_serialno = device.midi_serialno;
                device.midi_serialno = serialno;

                // and try again
                if (ogg_stream_packetout(device.os_v, &op) < 0) {
                        printf("Error reading intial header packet for Vorbis\n");
                        close_devices();
                        exit(1);
                }

                if (vorbis_synthesis_headerin(&device.vi, &device.vc, &op) < 0) {
                        printf("No vorbis stream found.\n");
                        close_devices();
                        exit(1);
                }
        } else {
                ogg_stream_packetout(device.os_v, &op);
        }

        // at this point we've verified vorbis, and os_m should point to the midi stream
        // but we need to verify it
        if (ogg_stream_packetout(device.os_m, &op) < 0) {
                printf("Error reading intial header packet for MIDI.\n");
                close_devices();
                exit(1);
        }

        midi_header_init(&device.mi);
        midi_header_set_queue(&device.mi, device.q);

        if (midi_headerin(&device.mi, &op) < 0) {
                printf("No MIDI stream found.\n");
                close_devices();
                exit(1);
        }

        // finish reading vorbis headers
        i = 0;
        while (i < 2) {
                while (i < 2) {
                        err = ogg_sync_pageout(&device.oy, &og);
                        if (err == 0) break; // need more data
                        if (err == 1) {
                                if (ogg_page_serialno(&og) == device.midi_serialno) {
                                        // got a midi page
                                        ogg_stream_pagein(device.os_m, &og);
                                        break;
                                }
                                ogg_stream_pagein(device.os_v, &og);
                                while (i < 2) {
                                        err = ogg_stream_packetout(device.os_v, &op);
                                        if (err == 0) break;
                                        if (err < 0) {
                                                printf("Corrupt Vorbis headers.\n");
                                                close_devices();
                                                exit(1);
                                        }
                                        vorbis_synthesis_headerin(&device.vi, &device.vc, &op);
                                        i++;
                                }
                        }
                }
                
                buffer = ogg_sync_buffer(&device.oy, 1024);
                bytes = fread(buffer, 1, 1024, device.fp);
                if (bytes == 0 && i < 2) {
                        printf("Premature end of file.\n");
                        close_devices();
                        exit(1);
                }
                ogg_sync_wrote(&device.oy, bytes);
        }

        vorbis_synthesis_init(&device.vd, &device.vi);
        vorbis_block_init(&device.vd, &device.vb);
}

void close_file(void)
{
        midi_header_clear(&device.mi);

        vorbis_comment_clear(&device.vc);
        vorbis_info_clear(&device.vi);
        ogg_stream_clear(device.os_v);
        ogg_stream_clear(device.os_m);
        free(device.os_v);
        free(device.os_m);
        ogg_sync_clear(&device.oy);

        fclose(device.fp);
}	

void start_queue(void)
{
        snd_seq_event_t ev;

//	snd_seq_ev_set_queue_pos_tick(&ev, device.q, 0);
        snd_seq_ev_clear(&ev);
        snd_seq_ev_schedule_tick(&ev, device.q, 0, 0);
        ev.type = SND_SEQ_EVENT_NOTE;
        ev.data.note.note = 44;
        ev.data.note.velocity = 0;
        ev.data.note.duration = 120;
        ev.source.port = device.srcport;
        ev.dest = device.seq_addr;

        snd_seq_event_output(device.seqhandle, &ev);
        snd_seq_drain_output(device.seqhandle);
}

tatic int64_t samples_played = 0;

void decode_midi_packet(ogg_packet *op)
{
        snd_seq_event_t ev;
        int err, result;
        snd_seq_queue_status_t *qs;

        snd_seq_queue_status_alloca(&qs);

        // submit packet
        midi_packetin(&device.mi, op);

        while ((err = midi_eventout(&device.mi, &ev)) == 0) {
                snd_pcm_status(device.pcmhandle, device.pcmstat);
                snd_seq_get_queue_status(device.seqhandle, device.q, qs);
                if (ev.type == 0) {
                        continue;
                }
                if (ev.type == SND_SEQ_EVENT_TEMPO) {
                        if (device.verbose >= 2)
                                printf("Changing tempo (us/beat) to: %d\n", ev.data.queue.param.value);
                        device.mi.tempo = ev.data.queue.param.value;
                        snd_seq_change_queue_tempo(device.seqhandle, device.q, 
                                                   ev.data.queue.param.value, NULL);
                        continue;
                }
                ev.dest = device.seq_addr;
                ev.source.port = device.srcport;
                result = snd_seq_event_output(device.seqhandle, &ev);
                if (result < 0) printf("Event output result = %d\n", result);
                snd_seq_drain_output(device.seqhandle);
        }

        if (err < 0 && err != EDATA) {
                printf("MIDI packet decoding error (%d).\n", err);
                close_devices();
                exit(1);
        }
}

void decode_vorbis_packet(ogg_packet *op)
{
        float **pcm;
        int samples;
        ogg_int16_t convbuffer[4096];
        int convsize = 4096 / device.vi.channels;
        int i, err;
        unsigned long count, pos;
        snd_seq_queue_status_t *qs;

        snd_seq_queue_status_alloca(&qs);

        if (vorbis_synthesis(&device.vb, op) == 0)
                vorbis_synthesis_blockin(&device.vd, &device.vb);

        while ((samples = vorbis_synthesis_pcmout(&device.vd, &pcm)) > 0) {
                int j;
                int clipflag = 0;
                int bout = (samples < convsize ? samples : convsize);

                for (i = 0; i < device.vi.channels; i++) {
                        ogg_int16_t *ptr = convbuffer+1;
                        float *mono = pcm[i];

                        for (j = 0; j < bout; j++) {
                                int val = mono[j] * 32767.f;

                                if (val > 32767) {
                                        val = 32767;
                                        clipflag = 1;
                                }
                                if (val < -32768) {
                                        val = -32768;
                                        clipflag = 1;
                                }

                                *ptr = val;
                                ptr += device.vi.channels;
                        }
                }

                // write data
                if (!device.fast_forwarding) {
                        count = bout;
                } else {
                        count = bout / FFWD_SPEED;
                        for (i = 0; i < count; i++) {
                                for (j = 0; j < device.vi.channels; j++) {
                                        convbuffer[i*device.vi.channels + j] = convbuffer[i*FFWD_SPEED*device.vi.channels + j];
                                }
                        }
                }
                pos = 0;
                while (1) {
                        do {
                                err = snd_pcm_writei(device.pcmhandle, &convbuffer[pos], count);
                                if (err > 0) {
                                        if (device.fast_forwarding)
                                                samples_played += err * FFWD_SPEED;
                                        else
                                                samples_played += err;
                                        count -= err;
                                        pos += err*2;
                                }
                        } while (count > 0 && (err > 0 || err == -EAGAIN));
                        if (err == -EPIPE) {
                                if (device.verbose >= 1)
                                        printf("audio underrun\n");
                                snd_pcm_prepare(device.pcmhandle);
                        } else {
                                break;
                        }
                }
                
                snd_pcm_status(device.pcmhandle, device.pcmstat);
                snd_seq_get_queue_status(device.seqhandle, device.q, qs);
                if (device.verbose >= 3)
                        printf("queue is at %d, samples_played == %lld\n", snd_seq_queue_status_get_tick_time(qs), samples_played - snd_pcm_status_get_delay(device.pcmstat));

                vorbis_synthesis_read(&device.vd, bout);
        }
}

ogg_page *copy_page(ogg_page *page)
{
        ogg_page *og;

        og = (ogg_page *)malloc(sizeof(ogg_page));
        og->header_len = page->header_len;
        og->body_len = page->body_len;
        og->header = (char *)malloc(og->header_len);
        og->body = (char *)malloc(og->body_len);
        memcpy(og->header, page->header, og->header_len);
        memcpy(og->body, page->body, og->body_len);

        return og;
}

int init_status_file(status_file_t *sf, char *name, char defval)
{
        /* Create/open the file */
        sf->fd = open(name, O_RDWR | O_CREAT);
        if (sf->fd < 0) return -1;

        /* Map the file to memory */
        sf->filemap = mmap(0, 1, PROT_READ | PROT_WRITE, MAP_SHARED, sf->fd, 0);
        if (sf->filemap < 0) {
                close(sf->fd);
                return -1;
        }

        /* Initialize default value */
        sf->filemap[0] = defval;
        
        /* Flush to file and update other mappings */
        if (msync(sf->filemap, 1, MS_SYNC | MS_INVALIDATE) < 0) {
                munmap(sf->filemap, 1);
                close(sf->fd);
                return -1;
        }

        sf->status = (defval != '0');

        return 0;
}

int setup_status_files(void)
{
        if (init_status_file(&device.play, STATUS_FILE_PLAY, '1') != 0) {
                printf("Could not initialize status file %s\n", STATUS_FILE_PLAY);
                return -1;
        }

        if (init_status_file(&device.pause, STATUS_FILE_PAUSE, '0') != 0) {
                printf("Could not initialize status file %s\n", STATUS_FILE_PAUSE);
                return -1;
        }

        if (init_status_file(&device.ffwd, STATUS_FILE_FFWD, '0') != 0) {
                printf("Could not initialize status file %s\n", STATUS_FILE_FFWD);
                return -1;
        }

        return 0;
}

void update_status(void)
{
        device.play.status = (device.play.filemap[0] != '0');
        device.pause.status = (device.pause.filemap[0] != '0');
        device.ffwd.status = (device.ffwd.filemap[0] != '0');
}

void close_status_files(void)
{
        munmap(device.play.filemap, 1);
        munmap(device.pause.filemap, 1);
        munmap(device.ffwd.filemap, 1);

        close(device.play.fd);
        close(device.pause.fd);
        close(device.ffwd.fd);
}

int main(int argc, char **argv)
{
        int err;
        ogg_page og;
        ogg_packet op;
        int eos = 0;
        int serialno;
        unsigned long bytes;
        char *buffer;
        snd_seq_timestamp_t ts;
        snd_seq_event_t ev;
        int c;
        int use_status_files = 0;
        ogg_page *buffered_page = NULL;

        memset(&ts, 0, sizeof(snd_seq_timestamp_t));
        
        device.pcm_device = "default";
        device.seq_addr.client = 64;
        device.seq_addr.port = 0;
        device.fast_forwarding = 0;
        device.play.status = 1;
        device.pause.status = 0;
        device.ffwd.status = 0;
        device.verbose = 0;

        while ((c = getopt(argc, argv, "D:p:sv")) != -1) {
                switch (c) {
                case 'D':
                        device.pcm_device = optarg;
                        break;
                case 'p':
                        snd_seq_parse_address(NULL, &device.seq_addr, optarg);
                        break;
                case 's':
                        use_status_files = 1;
                        break;
                case 'v':
                        device.verbose++;
                        break;
                default:
                        fprintf(stderr, "invalid options %c\n", c);
                        return 1;
                }
        }

        open_file(argv[optind]);

        err = open_devices();
        if (err < 0) {
                printf("Coudln't open devices\n");
                return -1;
        }

        err = configure_audio_device();
        if (err < 0) {
                printf("Couldn't configure audio device\n");
                close_devices();
                return -1;
        }

        err = configure_midi_device();
        if (err < 0) {
                printf("Couldn't configure midi device\n");
                close_devices();
                return -1;
        }

        err = sync_devices();
        if (err < 0) {
                printf("Could not sync devices\n");
                close_devices();
                return -1;
        }

        if (use_status_files) {
                err = setup_status_files();
                if (err < 0) {
                        printf("Could not open/initialize status files\n");
                        close_devices();
                        return -1;
                }
        }

        err = set_midi_tempo();
        if (err < 0) {
                printf("Could not set midi tempo\n");
                close_devices();
                return -1;
        }

        snd_seq_start_queue(device.seqhandle, device.q, 0);
        start_queue();

        /****** GUTS *********/

        

        // decode any midi packets that were queued
        while (1) {
                err = ogg_stream_packetout(device.os_m, &op);
                if (err == 0) break; // need more data
                if (err > 0) {	 
                        // we have a packet!
                        decode_midi_packet(&op);
                }
        }

        // decode any vorbis packets tthat were queued
        while (1) {
                err = ogg_stream_packetout(device.os_v, &op);
                if (err == 0) break; // need more data
                if (err > 0) {
                        // we have a packet!
                        decode_vorbis_packet(&op);
                }
        }

        // PLAYBACK :)
        while (!eos && device.play.status) {
                /* Pause if we're supposed to */
                while (device.pause.status) {
                        usleep(10000);
                        update_status();
                }

                /* Handle fast foward */
                if (device.ffwd.status && !device.fast_forwarding) {
                        // start fast forward
                        device.fast_forwarding = 1;
                        snd_seq_change_queue_tempo(device.seqhandle, device.q, device.mi.tempo / FFWD_SPEED, NULL);
                        snd_seq_drain_output(device.seqhandle);
                } else if (!device.ffwd.status && device.fast_forwarding) {
                        // stop fast forward
                        device.fast_forwarding = 0;
                        snd_seq_ev_clear(&ev);
                        snd_pcm_status(device.pcmhandle, device.pcmstat);

                        snd_seq_change_queue_tempo(device.seqhandle, device.q, device.mi.tempo, NULL);
                        snd_seq_ev_set_queue_pos_tick(&ev, device.q, (1000000 * (samples_played - snd_pcm_status_get_delay(device.pcmstat)) / 44100) / 
                                ((double)device.mi.tempo / (double)device.mi.ticks));
                        snd_seq_event_output_direct(device.seqhandle, &ev);
                        snd_seq_drain_output(device.seqhandle);
                }

                while (!eos && device.play.status) {
                        err = ogg_sync_pageout(&device.oy, &og);
                        if (err == 0) break; // need more data
                        if (err < 0) {
                                printf("Corrupt or missing data in bitstream.\n");
                                close_devices();
                                exit(1);
                        }

                        serialno = ogg_page_serialno(&og);
                        
                        if (serialno == device.midi_serialno) {
                                ogg_stream_pagein(device.os_m, &og);
                        } else if (serialno == device.vorbis_serialno) {
                                if (buffered_page == NULL) {
                                        buffered_page = copy_page(&og);
                                } else {
                                        ogg_stream_pagein(device.os_v, buffered_page);
                                        free(buffered_page->header);
                                        free(buffered_page->body);
                                        free(buffered_page);
                                        buffered_page = copy_page(&og);
                                }
                        } else {
                                printf("Got a foreign page.\n");
                                close_devices();
                                exit(1);
                        }

                        while (1) {
                                if (serialno == device.midi_serialno) {
                                        err = ogg_stream_packetout(device.os_m, &op);
                                } else {
                                        err = ogg_stream_packetout(device.os_v, &op);
                                }
                                if (err == 0) break; // need more data
                                if (err > 0) {
                                        // we have a packet!
                                        if (serialno == device.midi_serialno) {
                                                decode_midi_packet(&op);
                                        } else {
                                                decode_vorbis_packet(&op);
                                        }
                                }
                        }

                        // NOTE: this is wrong.  we should wait for _both_ eos's
                        if (ogg_page_eos(&og)) eos = 1;
                }

                if (!eos && device.play.status) {
                        buffer = ogg_sync_buffer(&device.oy, 1024);
                        bytes = fread(buffer, 1, 1024, device.fp);
                        ogg_sync_wrote(&device.oy, bytes);
                        if (bytes == 0) eos = 1;
                }

                if (use_status_files) update_status();
        }
        

        close_file();

        if (use_status_files) close_status_files();

        snd_seq_stop_queue(device.seqhandle, device.q, 0);

        close_devices();

        return 0;
}

--- >8 ----
List archives:  http://www.xiph.org/archives/
Ogg project homepage: http://www.xiph.org/ogg/
To unsubscribe from this list, send a message to 'cvs-request at xiph.org'
containing only the word 'unsubscribe' in the body.  No subject is needed.
Unsubscribe messages sent to the list will be ignored/filtered.



More information about the commits mailing list