Copyright (c) Hyperion Entertainment and contributors.

Difference between revisions of "IFF FORM and Chunk Registry"

From AmigaOS Documentation Wiki
Jump to navigation Jump to search
Line 486: Line 486:
 
| EA IFF 85 reserved serial num. prop
 
| EA IFF 85 reserved serial num. prop
 
|-
 
|-
  +
| [[PGTB_IFF_Program_Traceback#PGTB|PGTB]]
| <a href="http://amigan.1emu.net/reg/PGTB.txt">PGTB</a>
 
 
| IFF_TP
 
| IFF_TP
 
| Program traceback (SAS Institute)
 
| Program traceback (SAS Institute)
Line 2,790: Line 2,790:
 
for each Style change in the heading text.</pre>
 
for each Style change in the heading text.</pre>
   
=== Program traceback ===
 
 
<pre>Program traceback (SAS Institute)
 
 
FORM PGTB
 
 
Proposal:
 
New IFF chunk type, to be named PGTB, meaning ProGram TraceBack.
 
 
Format:
 
 
'PGTB' - chunk identifier
 
length - longword for length of chunk
 
 
'FAIL' - subfield giving environment at time of crash
 
length - longword length of subfield
 
NameLen - length of program name in longwords (BSTR)
 
Name - program name packed in longwords
 
Environment - copy of AttnFlags field from ExecBase,
 
gives type of processor, and existence of
 
math chip
 
VBlankFreq - copy of VBlankFrequency field from ExecBase
 
PowerSupFreq - copy of PowerSupplyFrequency field from ExecBase
 
above fields may be used to determine whether
 
machine was PAL or NTSC
 
Starter - non-zero = CLI, zero = WorkBench
 
GURUNum - exception number of crash
 
SegCount - number of segments for program
 
SegList - copy of seglist for program
 
(Includes all seglist pointers, paired with
 
sizes of the segments)
 
 
'REGS' - register dump subfield
 
length - length of subfield in longwords
 
GURUAddr - PC at time of crash
 
Flags - copy of Condition Code Register
 
DDump - dump of data registers
 
ADump - dump of address registers
 
 
'VERS' - revision of program which created this file
 
length - length of subfield in longwords
 
version - main version of writing program
 
revision - minor revision level of writing program
 
TBNameLen - length of name of writing program
 
TBName - name of writing program packed in longwords (BSTR)
 
 
'STAK' - stack dump subfield
 
length - length of subfield in longwords
 
(type) - tells type of stack subfield, which can be any of
 
the following:
 
-----------------------------------------------------------
 
Info - value 0
 
StackTop - address of top of stack
 
StackPtr - stack pointer at time of crash
 
StackLen - number of longwords on stack
 
 
-----------------------------------------------------------
 
Whole stack - value 1
 
only used if total stack to be dumped is 8k
 
or less in size
 
Stack - dump of stack from current to top
 
 
-----------------------------------------------------------
 
Top 4k - value 2
 
if stack used larger than 8k, this part
 
is a dump of the top 4k
 
Stack - dump of stack from top - 4k to top
 
 
-----------------------------------------------------------
 
Bottom 4k - value 3
 
if stack used larger than 8k, this part
 
is a dump of the bottom 4k
 
Stack - dump of stack from current to current + 4k
 
 
In other words, we will dump a maximum of 8k of stack data. This
 
does NOT mean the stack must be less than 8k in size to dump the
 
entire stack, just that the amount of stack USED be less than 8k.
 
 
'UDAT' - Optional User DATa chunk. If the user assigns
 
a function pointer to the label &quot;_ONGURU&quot;, the
 
catcher will call this routine prior to closing
 
the SnapShot file, passing one parameter on the
 
stack - an AmigaDOS file pointer to the SnapShot
 
file. Spec for the _ONGURU routine:
 
 
void &lt;function name&gt;(fp)
 
long fp;
 
 
In other words, your routine must be of type 'void'
 
and must take one parameter, an AmigaDOS file
 
handle (which AmigaDOS wants to see as a LONG).
 
length - length of the UserDATa chunk, calculated after the
 
user routine terminates.</pre>
 
 
=== PRSP ===
 
=== PRSP ===
   

Revision as of 21:40, 10 May 2012

IFF FORM and Chunk Registry

This section contains the official list of registered FORM and Chunk names that are reserved and in use. This list is often referred to as the 3rd party registry since these are FORM and Chunk types created by application developers and not part of the original IFF specification.

For all FORM and Chunk types that are public, the official specifications from the third party company are listed (in alphabetical order). At the end of this section are additional documents describing how the ILBM FORM type works on the Amiga.

New chunks and FORMS should be registered with the AmigaOS development team. Please make all submissions via the AmigaOS web site contact form.

Developing New IFF FORMs and Chunks

IFF has been one of the keys to the Amiga's superiority in multimedia applications, allowing interchange of media elements between packages. The wealth of standard IFF FORMs and chunks gives the Amiga user data-sharing capabilities that are virtually unequaled on other systems. The Amiga's ability to render an image, touch it up, convert it to a different display mode, and load it into in another package is something that is a chore on other platforms, simply because the format of the image file may be different from one application to the next. IFF files lessen the need for "conversion" software, because most Amiga applications can read and write them.

Since its introduction as an open standard in 1985, IFF has widened to encompass data of many sorts-and the need for new IFF types continues to grow. To satisfy these growing needs, developers will continue to define and support new IFF types.

When developing a new IFF type, there are several steps you should follow:

Discuss needs and specifications within the developer community and with the AmigaOS development team.
The most important thing about designing IFF FORMs and chunks is that they meet the data storage and transfer needs of multiple applications. When more than one product uses the same IFF type, the market widens for all products that use that IFF type. Users are not forced to use one product or another, but can buy as many as they need to get the job done, fully utilizing all the features that each product has to offer. This step helps to ensure that a proposed IFF form or chunk type is flexible and isn't redundant.
Implement the new type and conduct feasibility tests.
Before settling on a format, set up prototype code to test the proposed format. This will help to prove that the idea is sound and can be implemented in software before others try to use it.
Submit specifications to the AmigaOS development team.
Coming up with a new kind of IFF FORM or chunk is easy--almost too easy. Just about anyone can follow the IFF guidelines and define their own FORM or chunk. If every application used a different IFF FORM, one application would be unable to share data with another because it can't read the other application's IFF FORM. It's like making up a new word for something that everyone sees every day. You may understand what the word means, but when you try to use your new word to communicate with others, they won't understand you. Further, deciding to use a pre-existing FORM or chunk in a new and different way is a lot like making up your own meaning for a pre-existing word. Confusion results when programs try to read FORMs or chunks whose meaning was altered by a non-conforming program.
To avoid the problem of incompatible IFF types, register your new IFF types with the AmigaOS development team. The AmigaOS development team acts as a "dictionary" of IFF types. By submitting your proposals for FORM or chunk types to Amigan Software, you help prevent duplication of an existing data type. Also, if you register your new IFF type, it is more likely that it will be adopted as an IFF standard that other applications will use. For example, the ANIM form came from third party developers who proposed and refined the format. Now ANIM is the de facto standard for animation files.
For an excellent example of a third party FORM specification, see the WORD FORM. For an example of chunk descriptions, examine the 8SVX FORM's SEQN and FADE chunks.
Note that even you don't plan to release the specifications of your FORM or chunk, you must still register the name with the AmigaOS development team. This is the only way to prevent name conflicts in IFF files. You should register your FORM and chunk names before finalizing your product and its documentation in case there is a name conflict with an existing IFF type.
Distribute final specifications to the developer community.
Once you have registered your FORM or chunk with the AmigaOS development team, you should release the specifications of the chunk to the developer community. Although the AmigaOS development team publishes FORMs and chunks online developers should not rely on this method to distribute their IFF type specification. One of the most efficient ways to distribute your specification is to include it in your application's documentation. Distributing the specification will increase the probability of your FORM or chunk becoming a standard.

Third party FORMs

The following is an alphabetical list of registered FORMs, generic chunks (shown as (any).chunkname), and registered new chunks for existing FORMs (shown as formname.chunkname). The center column describes where additional information on the FORM or chunk may be found. Items marked “EA IFF” are described in the main chapters of the EA IFF specs. Those marked “IFF TP” are described in the third-party specifications section. Items marked “propos” are submitted proposals, some of which are private. And items marked with “—” are private or yet unreleased specifications.
Chunk ID Reference Description
(any).ANNO IFF Standard EA IFF 85 generic annotation chunk
(any).AUTH IFF Standard EA IFF 85 generic author chunk
(any).CHRS IFF Standard EA IFF 85 generic character string chunk
(any).CSET IFF_TP chunk for specifying character set
(any).FRED -- Private ASDG global chunk
(any).FVER IFF_TP chunk for 2.0 VERSION string of an IFF file
(any).HLID IFF_TP HotLink IDentification (Soft-Logik)
(any).INFO.proposal propos This chunk contains data usually found in a file's .info file
(any).JUNK IFF_TP Always ignore this chunk
(any).NAME IFF Standard EA IFF 85 generic name of art, music, etc. chunk
(any).TEXT IFF Standard EA IFF 85 generic unformatted ASCII text chunk
(any).(c) IFF Standard EA IFF 85 generic copyright text chunk
8SVX EA_IFF EA IFF 85 8-bit sound sample form
8SVX.CHAN.PAN IFF_TP Stereo chunks for 8SVX form
8SVX.SEQN.FADE IFF_TP Looping chunks for 8SVX form
ACBM IFF_TP Amiga Contiguous Bitmap form
AHAM ---- unregistered (???)
AHIM private AHI Modes
AHIM.AUDN private AUDio driver Name
AHIM.AUDD private AUDio driver Data
AHIM.AUDM private AUDio Mode
AIFF IFF_TP Audio 1-32 bit samples (Mac, Apple II, Synthia Pro)
ANBM IFF_TP Animated bitmap form (Framer, Deluxe Video)
ANIM IFF_TP Cel animation form
ANIM.brush IFF_TP ANIM brush format
ANIM.op6 IFF_TP Stereo (3D) animations
ANIM.op7 ---- unregistered (???)
ANIM.op8 IFF_TP -
ARC.proposal propos archive format proposal (old)
ARES ---- unregistered (???)
ATXT ---- temporarily reserved
AVCF private AmigaVision Flow format (currently private)
BANK ---- Soundquest Editor/Librarian MIDI Sysex dump
BBSD ---- BBS Database, F. Patnaude, Jr., Phalanx Software
C100 ---- Cloanto Italia private format
CAT IFF Standard EA IFF 85 group identifier
CELP.proposal propos For storage of compressed ZyXEL voice data (reserved)
CHBM ---- Chunky bitmap (name reserved by Eric Lavitsky)
CLIP ---- CAT CLIP to hold various formats in clipboard
CMUS.proposal propos Common MUsical Score
CPFM ---- Cloanto Personal FontMaker (doc in their manual)
DCCL ---- DCTV paint clip
DCPA ---- DCTV paint palette
DCTV ---- DCTV raw picture file
DECK ---- private format for Inovatronics CanDo
DEEP IFF_TP Chunky pixel image files (used in TV Paint)
DOC ---- unregistered (PageStream)
DR2D IFF_TP 2D object standard format
DSDR ---- unregistered (DrawStudio)
DRAW ---- reserved by Jim Bayless, 12/90
DTYP IFF_TP DataTypes identification
<a href="http://amigan.1emu.net/reg/EXEC.txt">EXEC.proposal</a> propos Proposed form for executable (loadseg-able) code
FANT IFF_TP Fantavision movie format
FAX3 ---- private GPSoftware FAX format, no longer used
FAXX.GPHD IFF_TP Additional header info for FAXX forms
FAXX IFF_TP Facsimile image form
FIGR ---- Deluxe Video - reserved
FILM ---- LIST FILM - For storing ILBMs with interleaved 8SVX audio
FNTR IFF Standard EA IFF 85 reserved for raster font
FNTV IFF Standard EA IFF 85 reserved for vector font
FORM IFF Standard EA IFF 85 group identifier
FTXT IFF Standard EA IFF 85 formatted text form
GRYP.proposal propos byteplane storage proposal (copyrighted)
GSCR IFF Standard EA IFF 85 reserved general music score
GMS IFF_TP Gesture and Motion Signal GMS Web Site
GUI.proposal propos user interface storage proposal (private)
HEAD IFF_TP Flow - New Horizons Software
ILBM EA_IFF EA IFF 85 raster bitmap form
ILBM.3DCM ---- reserved by Haitex
ILBM.3DPA ---- reserved by Haitex
ILBM.ASDG ---- private ASDG application chunk
ILBM.BHBA ---- private Photon Paint chunk (brushes)
ILBM.BHCP ---- private Photon Paint chunk (screens)
ILBM.BHSM ---- private Photon Paint chunk
ILBM.CLUT IFF_TP Color Lookup Table chunk
ILBM.CMYK IFF_TP Cyan, Magenta, Yellow, & Black color map (Soft-Logik)
ILBM.CNAM IFF_TP Color naming chunk (Soft-Logik)
ILBM.CTBL.DYCP IFF_TP Newtek Dynamic HAM color chunks
ILBM.DCTV ---- reserved
ILBM.DGVW ---- private Newtek DigiView chunk
ILBM.DPI IFF_TP Dots per inch chunk
ILBM.DPPV IFF_TP DPaint perspective chunk (EA)
ILBM.DRNG IFF_TP DPaint IV enhanced color cycle chunk (EA)
ILBM.EPSF IFF_TP Encapsulated Postscript chunk
ILBM.PCHG IFF_TP Line by line palette control information (Sebastiano Vigna)
ILBM.PRVW.proposal propos A mini duplicate ILBM used for preview (Gary Bonham)
ILBM.TMAP ---- Transparency map (temporarily reserved)
<a href="http://amigan.1emu.net/reg/ILBM.VTAG.proposal.txt" "="">ILBM.VTAG.proposal</a> propos Viewmode tags chunk suggestion
ILBM.XBMI IFF_TP eXtended BitMap Information (Soft-Logik)
ILBM.XSSL IFF_TP Identifier chunk for 3D X-Specs image (Haitex)
IOBJ ---- reserved by Seven Seas Software
IODK ---- reserved for Jean-Marc Porchet at Merging Technologies
ITRF ---- reserved
JMOV ---- reserved for Merging Technologies
LIST IFF Standard EA IFF 85 group identifier
MFAX ---- reserved for TKR GmbH & Co.
MIDI ---- Circum Design
MOVI ---- LIST MOVI - private format
MSCX ---- private Music-X format
MSMP ---- temporarily reserved
MTRX IFF_TP Numerical data storage (MathVision - Seven Seas)
NSEQ ---- Numerical sequence (Stockhausen GmbH)
<a href="http://amigan.1emu.net/reg/OB3D.proposal.txt">OB3D.proposal</a> propos Proposal for a standard 3D object format
OCMP IFF Standard EA IFF 85 reserved computer prop
OCPU IFF Standard EA IFF 85 reserved processor prop
OPGM IFF Standard EA IFF 85 reserved program prop
OSN IFF Standard EA IFF 85 reserved serial num. prop
PGTB IFF_TP Program traceback (SAS Institute)
PICS IFF Standard EA IFF 85 reserved Macintosh picture
PLBM IFF Standard EA IFF 85 reserved obsolete name
<a href="http://amigan.1emu.net/reg/PMBC.proposal.txt">PMBC.proposal</a> propos reserved for Black Belt Systems 91.12.01
PREF ---- Reserved by Commodore for user preferences data, currently private
PREF.AHIG private AHI Global preferences
PREF.AHIU private AHI Unit preferences
PROP IFF Standard EA IFF 85 group identifier
PRSP IFF_TP DPaint IV perspective move form (EA)
PTCH ---- Patch file format (SAS Institute)
PTXT ---- temporarily reserved
RGB4 ---- 4-bit RGB (format not available)
<a href="http://amigan.1emu.net/reg/RGBN-RGB8.txt">RGBN-RGB8</a> IFF_TP RGB image forms, Turbo Silver (Impulse)
RGBX ---- temporarily reserved
ROXN ---- private animation form
SAMP IFF_TP Sampled sound format
SC3D ---- private scene format (Sculpt-3D)
SHAK ---- private Shakespeare format
SHO1 ---- reserved by Gary Bonham (private)
SHOW ---- reserved by Gary Bonham (private)
SMUS EA_IFF EA IFF 85 simple music score form
<a href="http://amigan.1emu.net/reg/SPLT.txt">SPLT</a> IFF_TP ASDG's file SPLiTting system
SSRE ---- reserved for Merging Technologies 92.05.04
SWRT ---- unregistered (???)
SYTH ---- SoundQuest Master Librarian MIDI System driver
TCDE ---- reserved by Merging Technologies
TDDD IFF_TP 3D rendering data, Turbo Silver (Impulse)
TERM ---- unregistered (???)
<a href="http://amigan.1emu.net/reg/TMUI.txt">TMUI</a> IFF_TP Toolmaker IFF project file format (ToolMaker V1.19)
<a href="http://amigan.1emu.net/reg/TREE.txt">TREE</a> IFF_TP Storage of arbitrary data structures as trees (or nested lists)
<a href="http://amigan.1emu.net/reg/TRKR.proposal.txt">TRKR.proposal</a> propos TRacKeR style music module format proposal
UNAM IFF Standard EA IFF 85 reserved user name prop
USCR IFF Standard EA IFF 85 reserved Uhuru score
UVOX IFF Standard EA IFF 85 reserved Uhuru Mac voice
VDEO ---- private Deluxe Video format
WORD IFF_TP ProWrite document format (New Horizons)
WOWO ---- unregistered (Wordworth)
YAFA ---- unregistered animation format (Wildfire)
YUVN IFF_TP For storage of Y:U:V image data (MacroSystems)

(any).CSET

Chunk for specifying character set.

Registered by Martin Taillefer.

A chunk for use in any FORM, to specify character set used for text in FORM.

struct CSet {
  LONG    CodeSet;        /* 0=ECMA Latin 1 (std Amiga charset) */
                          /* AmigaOS development team will define additional values  */
  LONG    Reserved[7];
}

(any).FVER

Chunk for 2.0 VERSION string of an IFF file.

Registered by Martin Taillefer.

A chunk for use in any FORM, to contain standard 2.0 version string.

$VER: name ver.rev

where "name" is the name or identifier of the file and ver.rev is a version/revision such as 53.1

Example:

$VER: workbench.catalog 53.42


(any).HLID

HotLink IDentification (Soft-Logik)

HLID Generic chunk

Submitted by Dan Weiss, Deron Kazmaier, and Gary Knight (8/29/91)

Chunk ID: "HLID" (HotLink IDentification)

Description: This chunk is used by applications that store local copies of HotLink'ed files. When an application reads in a local copy and finds a HLID chunk, the application can check if any changes have been made to the file and get the new changes if any have been made. Also the application can set up a notification on the file, and treat it just like the application subscribed to the file. The format of the chunk is 3 long words. The first two hold the publication ID and the last one holds the publication version number. These are all the entries needed to load a hotlink'ed file from HotLinks.

Example:

                       HLID            ;chunk ID
                       0000000C        ;chunk length (12 bytes)
                       00000001        ;publication ID (part 1)
                       00000005        ;publication ID (part 2)
                       00000002        ;publication version number

(any).INFO.proposal

This chunk contains data usually found in a file's .info file.

Proposed by Chris Ludwig 91.12.19.

(any).JUNK

Always ignore this chunk.

This chunk was designed to let garbage data in an IFF file be quickly marked as such. Instead of actually having to remove the garbage chunk, just rename it "JUNK". All IFF readers should ignore "JUNK" chunks. Thanks to David Ellis for this idea. Registered 91.11.

ACBM

Amiga Contiguous Bitmap form

IFF FORM / CHUNK DESCRIPTION
============================

Form/Chunk ID:   FORM  ACBM  (Amiga Contiguous BitMap)
                 Chunk ABIT  (Amiga BITplanes)

Date Submitted:  05/29/86
Submitted by:    Carolyn Scheppner   CBM


FORM
====

FORM ID:  ACBM  (Amiga Contiguous BitMap)

FORM Description: 

   FORM ACBM has the same format as FORM ILBM except the normal BODY
chunk (InterLeaved BitMap) is replaced by an ABIT chunk (Amiga BITplanes). 

FORM Purpose:

   To enable faster loading/saving of screens, especially from Basic,
while retaining the flexibility and portability of IFF format files.


CHUNKS
======

Chunk ID:   ABIT  (Amiga BITplanes)

Chunk Description:

   The ABIT chunk contains contiguous bitplane data.  The chunk contains
sequential data for bitplane 0 through bitplane n.

Chunk Purpose:

   To enable loading/storing of bitmaps with one DOS Read/Write per
bitplane.  Significant speed increases are realized when loading/saving
screens from Basic.


SUPPORTING SOFTWARE
===================

(Public Domain, available soon via Fish PD disk, various networks)

LoadILBM-SaveACBM (AmigaBasic)
   Loads and displays an IFF ILBM pic file (Graphicraft, DPaint, Images).
   Optionally saves the screen in ACBM format.

LoadACBM (AmigaBasic)
   Loads and display an ACBM format pic file.

SaveILBM (AmigaBasic)
   Saves a demo screen as an ILBM pic file which can be loaded into
   Graphicraft, DPaint, Images.

ANBM

Animated bitmap form (Framer, Deluxe Video)

TITLE:  Form ANBM (animated bitmap form used by Framer, Deluxe Video) 
 
(note from the author) 
  
   The format was designed for simplicity at a time when the IFF  
standard was very new and strange to us all.  It was not designed 
to be a general purpose animation format.  It was intended to be 
a private format for use by DVideo, with the hope that a more  
powerful format would emerge as the Amiga became more popular. 
  
   I hope you will publish this format so that other formats will 
not inadvertantly conflict with it. 
  
PURPOSE:  To define simple animated bitmaps for use in DeluxeVideo. 
  
   In Deluxe Video objects appear and move in the foreground 
with a picture in the background.  Objects are "small" bitmaps 
usually saved as brushes from DeluxePaint and pictures are large 
full screen bitmaps saved as files from DeluxePaint.   
    
   Two new chunk headers are defined: ANBM and FSQN. 
  
   An animated bitmap (ANBM) is a series of bitmaps of the same  
size and depth.  Each bitmap in the series is called a frame and 
is labeled by a character, 'a b c ...' in the order they 
appear in the file. 
  
   The frame sequence chunk (FSQN) specifies the playback 
sequence of the individual bitmaps to achieve animation.   
FSQN_CYCLE and FSQN_TOFRO specify two algorithmic sequences.  If  
neither of these bits is set, an arbitrary sequence can be used 
instead. 
  
  
    ANBM         - identifies this file as an animated bitmap 
    .FSQN        - playback sequence information 
    .LIST ILBM   - LIST allows following ILBMs to share properties 
    ..PROP ILBM  - properties follow 
    ...BMHD      - bitmap header defines common size and depth 
    ...CMAP      - colormap defines common colors 
    ..FORM ILBM  - first frame follows  
    ..BODY       - the first frame 
       .         - FORM ILBM and BODY for each remaining frame 
       . 
       . 
  
Chunk Description: 
  
   The ANBM chunk identifes this file as an animated bitmap 
  
Chunk Spec:   
    
   #define ANBM    MakeID('A','N','B','M') 
  
Disk record:   
  
   none 
  
Chunk Description: 
  
   The FSQN chunk specifies the frame playback sequence 
  
Chunk Spec: 
  
   #define FSQN    MakeID('F','S','Q','N') 
  
   /* Flags */ 
   #define FSQN_CYCLE  0x0001  /* Ignore sequence, cycle a,b,..y,z,a,b,.. */ 
   #define FSQN_TOFRO  0x0002  /* Ignore sequence, cycle a,b,..y,z,y,..a,b, */ 
   /* Disk record */ 
   typedef struct { 
       WORD numframes;      /* Number of frames in the sequence */ 
       LONG dt;             /* Nominal time between frames in jiffies */ 
       WORDBITS flags;      /* Bits modify behavior of the animation */ 
       UBYTE sequence[80];  /* string of 'a'..'z' specifying sequence */ 
       } FrameSeqn; 
  
  
Supporting Software: 
  
   DeluxeVideo by Mike Posehn and Tom Case for Electronic Arts 
  
  
Thanks, 
   Mike Posehn


CMUS.proposal

Common MUsical Score

/* ========================================================================= *
                         CMUS - Common Musical Score

                     An IFF File format for interchanging
                   musical data using Common Music Notation

                            by Talin (David Joiner)

                                  Verion 0.4
 * ========================================================================= */

#ifndef CMUS_H
#define CMUS_H

/* ========================================================================= *
    Note to Non-Amiga users of this document
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        CMUS is an IFF (Interchange File Format) file. IFF is a "Meta-standard"
    for making extensible, self-identifying file formats, and was developed
    by Commodore and Electronic Arts. In order to understand CMUS you will
    need to get the IFF Documentation. The quickest way to do this is to
    get the "Amiga ROM Kernal Manual: Devices" volume and look in the Appendix.
 * ========================================================================= *
    Note on Timing:
    ~~~~~~~~~~~~~~~
        Common Music Notation is a symbolic, rather than a literal
    representation. It is supposed to be interpreted by the player. A note
    which is listed as "A quarter note", will seldom be played at the exact
    time or duration as written. These deviations from mathematically perfect
    time are important; they are part of what musicians call "feel" or
    "liveliness".
        Accordingly, FORM CMUS has two different kinds of timing information.
    _Formal Time_ is represented in symbolic form: Each symbol has a field
    which indicates it's duration (dotted quarter-note, etc) in symbolic units.
    The formal start time of an event can be obtained by summing the durations
    of all the previous times in the measure.
        In addition, there is also _Casual Time_. Each event has a "start time"
    which is the number of basic clock units from the start of the measure to
    the start of that event. Some event types also have "duration" fields of
    a similar nature.
        In general, although there will probably be a strong correlation
    between formal time and casual time, there is no guarantee of this.
    Certainly this FORM does not enforce any relationship between the two.
    This means that you cannot, in general, derive one from the other. You can
    at most make an educated guess, and even that is a non-trivial problem
    from an algorithmic point of view.

 * ========================================================================= *
    Note on Layout Measurements:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        In general, I have tried to make all measurements as "device-
    independent" as possible.

        Measurements of page dimensions and other page-related information
    such as margins and indentations are represented in micrometers.
        Converting from micrometers to inches and "big points" (the definition
    of points used by Adobe and Apple) can be done with the following
    formulas:

        inches = micrometers / 25400;

        points = micrometers * 72 / 25400;

        Vertical distances of musical items are all measured in "Levels".
    A level is one half the distance between the lines of a staff. A note on
    the centerline of the staff is at level zero. Placing the note just above
    that line (between the 2nd and 3rd staff line) makes it level 1, while
    placing it below the centerline makes it level -1. Note that up is positive
    in this coordinate system.
        Note positions are recorded as a fraction of the measure width.

 * ========================================================================= *
    Rules for clipboard use:
    ~~~~~~~~~~~~~~~~~~~~~~~~
        A CMUS chunk may be copied to the clipboard. In such cases, it is
    possible that only a subset of the data might be written. Specifically,
    measures and signatures which occur before the first selection point,
    or after the last selection point should not be included. Note that
    the measure containing the first selection point should be written,
    however, even if it is not in the selection range itself. (As to whether
    measure-lines are selectable is up to the application). In addition,
    an initial time signature item for that measure should be written as
    well; key signature and clef items are optional in this case. The
    application receiving the clip has the option of whether to use the
    signature items in the clip, or to ignore them and use the existing
    signatures in the score. The application can also decide to "insert"
    the clip into the score (causing existing other events to be shifted
    later in time), or "merging" the events with the existing items.
    The application can also choose to respect measure lines in the clip
    (each new measure line causes the notes to be pasted into the next
    measure) or to "flow" the notes across measure boundaries.
        Note that the notes in a clip may be non-contiguous. For example,
    If the user were to select every second note and copy those to the
    clipboard, there would be "gaps" in the clipped track. Unfortunately,
    a reader program would not be able to detect those gaps (since formal
    time does not have an explicit start time) and thus the formal time
    and the casual time would get out of sync. To avoid this problem,
    "filler" events can be inserted into the score to fill up the empty space.
    Note that the duration of a filler event is formal, unlike all the
    other events.
        Notation programs which only support contiguous selection (i.e.
    can't have a deselected note between two selected notes) can ignore
    filler items.
        A filler event at the end of the measure is not neccessary.
    In fact, there is no requirement in CMUS that a measure be "filled".
    In addition, certain music programs allow more notes in a measure than
    would legally fit (only while editing, the extra notes are never played).
    CMUS readers should handle this case robustly.

        This allows a reader to make intelligent use of the clip. The clip
    can be pasted relative to an insertion point, and the relationship of
    notes to measures can be (optionally) preserved, even if the selection
    was non-contiguous.
 * ========================================================================= *
    Future Directions
    ~~~~~~~~~~~~~~~~~
        A number of musical features are currently mising from the CMUS spec,
    such as the ability for a track to jump from one staff to another. In
    addition, there are a number of features which would be desirable on the
    "page" level, such as seperate margins for each page (currently, there is
    no representation of individual pages in the spec).
        All of these things can easily be added by defining new IFF chunks
    or new event types. I have not done this because I feel that these
    additional features would best be designed by the person who needs them,
    in other words someone designing a music product that requires such
    features and is familiar with the issues inolved. Otherwise, the format
    might be defined wrongly, missing subtle advantages which
*/

/* ========================================================================= *
                             General Definitions
 * ========================================================================= */

typedef long            Micrometers;

#if CM_MICRO_CONVERSION

    /* (optional) conversion to / from inches */

#define InchesToMicros(inches)  ((inches) * 25400)
#define MicrosToInches(micros)  (((micros) + 12700) / 25400)

#define HundredthsToMicros(inches)  ((inches) * 254)
#define MicrosToHundredths(micros)  (((micros) + 127) / 254)

#define PointsToMicros(points)  (((points) * 25400 + 36) / 72)
#define MicrosToPoints(micros)  (((micros) * 72 + 12700) / 25400)

#endif

/* ========================================================================= *
                           Score Header Chunk (SCHD)
 * ========================================================================= */

typedef struct {
    WORD                scBarsPerLine;      /* preferred bars per line      */
    WORD                scOverallVolume;    /* overall volume of score      */

    Micrometers         scPageWidth,        /* width of page                */
                        scPageHeight,       /* height of page               */
                        scTopMargin,        /* top margin of score on page 1*/
                        scFirstLineIndent,  /* left margin indent on line 1 */
                        scLineIndent;       /* left indent on other lines   */
} CM_ScoreHeader;

/* ========================================================================= *
                            Staff Table Chunk (STAF)

   This section describes the data structures which are used in the CMUS 'STAF'
   Chunk. There is one STFF chunk per score, which contains an array of
   StaffEntry structres (1 per staff in the document).

 * ========================================================================= */

typedef struct {
    WORD                staffFlags;         /* various flags                */

        /*  This defines the vertical size of a measure. Both of the distances
            are measured from the center line of the staff (in fact all staff-
            relative distances are represented this way).
        */

    Micrometers         staffSpaceAbove,    /* space above staff            */
                        staffSpaceBelow;    /* space below staff            */

    Micrometers         staffLevelSize;     /* distance between staff lines */

} CM_StaffEntry;

    /* This flag indicates that a formfeed should be done before printing
        this staff (used when a score has more staffs than will fit on a page.
    */

#define STAFF_PAGEBREAK (1<<0)

    /*  This indicates that the measure lines for this staff should not be
        connected to the measure lines for the staff below
    */

#define STAFF_BAR_BROKEN (1<<1)

    /*  This flag indicates that a set of "curly braces" should connect this
        staff with the staff below.
    */

#define STAFF_BRACED    (1<<2)              /* Staff is "braced" with next  */

    /*  These flags indicate the start and end of a square bracket which can
        span over several staffs. The brace should start at the staff
        marked with the "START" bit and continue until a staff with the
        "END" bit is encountered.
    */

#define STAFF_BRACKET_START (1<<3)
#define STAFF_BRACKET_END   (1<<4)

/* ========================================================================= *
                               Track Chunk (TRCK)

   This section describes the data structures which are used in the CMUS 'TRCK'
   Chunk.

   A track is a sequence of notes which reside on a staff. In the simplest
   case, there is one TRCK chunk per melody line in the score. However, a
   track can contain chords, rests, etc, as well.

   A more precise definition of a track is that a track is a sequence of
   chords, where all the notes within each chord have the same start time
   and the same duration (in formal time of course; in casual time anything
   is possible). Note that ties can be used to create the illusion of
   having broken this rule.

 * ========================================================================= */

/*  Track Header structure:

    Each track begins with a track header structure, followed by any number
    of score items. (Use the chunk length to determine when to stop reading
    score items).
*/

typedef struct {
    UWORD               trkStaff,           /* staff number to place this on*/
                        trkTrack,           /* track number within staff    */
                        trkFlags;           /* flags for staff header       */

        /*  Sometimes notes on the staff are written transposed from how they
            should actually be played. This is the number that should be added
            to the pitch before it is actually played back.
        */

    WORD                trkTransposition;   /* playback transposition       */

} CM_TrackHeader;

/* ========================================================================= *
                                      Track Item
 * ========================================================================= */

/*  Item Header:

    Score items are variable in length. The first byte of the item is the
    length of the item in WORDS. This will allow new item types to be added
    in the future. All score items are an integer number of WORDS long.

    Each score item has a standard header structure, followed by a variable
    amount of item-specific data. The 'itemType' field is used to determine what
    that data is.

    'itemLength' is the length of the item in WORDS. This allows items to be
    from 2 to 512 bytes long. (The value '0' is reserved as a special case).

    'itemXPos' contains the X position of the item in fractions of the measure's
    width. Note that the area containing the signatures, and the area just
    before the ending measure line are not considered part of this range.
    Think of it this way: The value 0 is the first possible note position.
    The value 0x7fff if the last possible note position. Items placed at
    these positions should not run into the graphics at either the beginning
    or the end of the measure. In addition, negative numbers are also
    allows, which is used for symbols which penetrate into the "signature"
    area. In this case, 0 represents the first possible note position, and
    -0x8000 represents the actual barline. This convention is normally only
    used for lyrics, which can intrude into the signature area.

    'itemStart' is used to represent the real starting time of each event.
    This is recorded as a delta-time, in other words itemStart contains
    how many clock ticks have elapsed between the current item and the item
    before it. Note that because of the fact that events can sometimes occur
    out of order (for example, notes in a chord can be ordered by pitch rather
    than by time, and they might not all start at exactly the same clock),
    this value can be negative.
        In addition, the clock is reset at each measure boundary. In other
    words, the length of a measure is determined only by it's time signature,
    and not by the delta between the last note and the next measure line.
    In fact, the itemStart field for measure line items is ignored and should
    always be set to zero.
        An item's start time does NOT have to exactly match the event's
    "formal" time. For example, an event at the beginning of a measure does
    not have to start at exactly time zero, but can be offset somewhat.
    This allows the subtle nuances of a live performance to be preserved, if
    the notation software allows for that capability.

    The 'itemStart' field (and the noteDuration field defined later) use a
    clock standard of 960 clock ticks per whole note. Thus, a quarter note
    is one/quarter that, or 240. This number is divisible by 3, 5, and several
    powers of two, making it convenient for representing triplets and
    quintuplets as well as small note values.
*/

typedef struct {
    UBYTE               itemLength,         /* length of item in WORDS      */
                        itemType;           /* type of item                 */
    WORD                itemXPos;           /* horizontal position of item  */
    WORD                itemStart;          /* start time, in ticks         */
} CM_ItemHeader;

#define WHOLE_NOTE_DURATION     960         /* duration of a whole note     */

#define MAX_ITEM_XPOS   0x7fff
#define MMIN_ITEM_XPOS  -0x8000

    /* type codes for chunk item types */

enum notation_item_types {
    MEASURE_ITEM = 0,                       /* measure line                 */
    SIGNATURE_ITEM,                         /* time sig., key sig., or clef */
    NOTE_ITEM,                              /* first note in a chord        */
    CHORD_ITEM,                             /* additional notes in a chord  */
    FILLER_ITEM,                            /* fills up empty gaps          */
    DYNAMIC_ITEM,                           /* dynamic volume item (fff)    */
    INSTRUMENT_ITEM,                        /* instrument change item       */
    TEMPO_ITEM,                             /* tempo change item            */
    REPEAT_ITEM,                            /* for jumping around in score  */
    BEGIN_GROUP_ITEM,                       /* begin slur, crescendo, etc.  */
    END_GROUP_ITEM,                         /* end slur, crecendo, etc.     */
    TABLATURE_ITEM,                         /* guitar or other tablature    */
};

/* ========================================================================= *
                                  Measure Line Item
 * ========================================================================= */

/*  This item represents the beginning of a new measure. As such, there should
    be one of these at the beginning of the track, but not at the end.
*/

typedef struct {
    CM_ItemHeader       measureItem;        /* item header                  */
    Micrometers         measureWidth;       /* width of measure             */
    UBYTE               measureFlags;       /* various flags, see below     */

        /*  measureEnding: If non-zero, it means that this measure is part
            of an ending block. The value indicates which ending this measure
            is part of. For example, if the value = 1, then this measure
            is only played the first time through, if the value = 2 then
            it is only played the second time through.

            Each "repeat" section in the score can have it's own set of
            endings.

            "Endings" can be longer than one measure. Each measure that
            is encountered that has the same value of measureEnding as the
            previous measure is considered part of the same ending.
        */

    UBYTE               measureEnding;      /* "ending" this measure is in  */
} CM_Measure;

#define MEASURE_FULL_WIDTH 0x7fff           /* full width of score          */

enum measureFlags {

        /*  Draw a double bar at the end of this measure. The reason for
            associating the double-bar flag with the next measure line is
            because double bar can occur at the end of the score but not
            at the beginning.
        */
    MEASUREF_DOUBLE_BAR = (1<<0),

        /*  This is a "line break", in other words it indicates that this
            measure should start a new line.
        */

    MEASUREF_NEW_LINE   = (1<<1),

        /*  If set, this flags means that the measure width was set by the
            user. It not set, it means that measure width was calculated on
            the fly, and can be re-adjusted feely if needed to line things
            up. Note that this width includes signatures, but does not include
            any indentation from the left margin of the document.
        */

    MEASUREF_FIXED      = (1<<2),

};

/* ========================================================================= *
                               Signature Items
 * ========================================================================= */

    /*  Signature items are usually placed just after the measure line.

        Some notators have the ability to change clef in the middle of a
        measure, but not all notators need support this. If it is not
        supported, and a clef is encountered in the middle of a measure, it
        is assumed to apply to the entire measure and therefore is associated
        with the previous measure line.
    */

    /*  Signature types: Each signature has a "sigSubType" field which
        indicates the type of signature. In addition, the high bit of the
        signature type field indicates that the signature should not be
        shown visibly.
    */

enum SignatureTypes {
    SIGTYPE_TIMESIG=1,
    SIGTYPE_CLEF,
    SIGTYPE_MAJORKEY,
    SIGTYPE_MINORKEY,

    SIGTYPE_HIDDEN=(1<<7)
};

    /*  Stores a time signature. 'Beats' is the number above the line, and
        'Notes' is the number below the line. For example, '3/4' time is
        stored as beats = 3, notes = 4.

        "Common Time" (The "C" symbol) which is equivalent to 4/4 is stored
        as 4/0 (beats = 4, notes = 0).

        "Cut Time" ("C" with a slash through it) which is equivalent to
        2/4 is stored as 2/0 (beats = 2, notes = 0).

        In other words, the value "0" in "sigNotes" should always be treated
        as the value "4" when calculating measure lengths. See the
        MEASURE_LENGTH macro for an example of this.
    */

typedef struct {
    CM_ItemHeader       sigItem;            /* item header                  */
    UBYTE               sigSubType,         /* (= SIGTYPE_TIMESIG)          */
                        sigBeats,           /* beats per bar                */
                        sigNotes,           /* size of each beat            */
                        sigPad;
} CM_TimeSignature;

    /* compute the measure length in clock ticks */

#define MEASURE_LENGTH(beats, notes) \
    (WHOLE_NOTE_DURATION * beats / (notes ? notes : 4))

    /* stores a Clef */

typedef struct {
    CM_ItemHeader       sigItem;            /* item header                  */
    UBYTE               sigSubType;         /* (= SIGTYPE_CLEF)             */
    UBYTE               sigClef;            /* new clef                     */
} CM_Clef;

    /*  Definitions of clef types. Note clef modifier bits which are used as
        part of this field as well.
    */

enum ClefTypes {
    TREBLE_CLEF = 0,                        /* G clef in normal position    */
    BASS_CLEF,                              /* F clef in normal position    */
    ALTO_CLEF,                              /* C clef centered on line 3    */
    TENOR_CLEF,                             /* C clef centered on line 2    */

        /* optional clefs, some of which are obselete (in the U.S.) */

    SOPRANO_CLEF,                           /* C clef centered on line 5    */
    MEZZO_SOPRANO_CLEF,                     /* C clef centered on line 4    */
    BARITONE_CLEF,                          /* F clef one line lower        */
    FRENCH_VIOLIN_CLEF,                     /* G clef one line lower        */

        /*  For drum scores. One of the things implied by a drum clef is that
            there might not be a relationship between a note's vertical
            position and it's MIDI note number, unlike other clef types.
            (This could be especially handy for work with MIDI drum machines).
        */

    DRUM_CLEF,                              /* vertical lines or box        */

        /* clef modifier bits: A clef can be raised or lowered by one or two
            octaves. This is notated by placing a small "8" or "15" above or
            below the clef.
        */

    CLEF_DOWN_1_OCTAVE=(1<<4),              /* clef 1 oct lower (8 below)   */
    CLEF_DOWN_2_OCTAVES=(1<<5),             /* clef 2 oct lower (15 below)  */
    CLEF_UP_1_OCTAVE=(1<<6),                /* clef 1 oct higher (8 above)  */
    CLEF_UP_2_OCTAVE=(1<<7),                /* clef 2 oct higher (15 above) */
};

    /*  stores a Key Signature. (used for both major and minor)

        'sigKeySig' is a signed BYTE, where '0' is the key of C. Positive
        numbers represent the number of sharps, so 1=G, 2=D, etc, around the
        circle of fifths. Negative numbers represent the number of flats,
        F=-1, B-Flat = -2, etc.

        For minor keys, 0 is the key of A-minor, which like C has no sharps
        or flats.

        Other types of key signatures may be supported in the future, but
        will probably be done as a different type of signature item.
    */

typedef struct {
    CM_ItemHeader       sigItem;            /* item header                  */
    UBYTE               sigSubType;         /* (== SIGTYPE_KEYSIG)          */
    BYTE                sigKeySig;          /* new key signature            */
} CM_KeySignature;

    /* major key definitions */

#define KEY_OF_C_MAJOR           0
#define KEY_OF_G_MAJOR           1
#define KEY_OF_D_MAJOR           2
#define KEY_OF_A_MAJOR           3
#define KEY_OF_E_MAJOR           4
#define KEY_OF_B_MAJOR           5
#define KEY_OF_F_SHARP_MAJOR     6
#define KEY_OF_C_SHARP_MAJOR     7
#define KEY_OF_F_MAJOR          -1
#define KEY_OF_B_FLAT_MAJOR     -2
#define KEY_OF_E_FLAT_MAJOR     -3
#define KEY_OF_A_FLAT_MAJOR     -4
#define KEY_OF_D_FLAT_MAJOR     -5
#define KEY_OF_G_FLAT_MAJOR     -6
#define KEY_OF_C_FLAT_MAJOR     -7

    /* minor key definitions */

#define KEY_OF_A_MINOR           0
#define KEY_OF_E_MINOR           1
#define KEY_OF_B_MINOR           2
#define KEY_OF_F_SHARP_MINOR     3
#define KEY_OF_C_SHARP_MINOR     4
#define KEY_OF_G_SHARP_MINOR     5
#define KEY_OF_D_SHARP_MINOR     6
#define KEY_OF_A_SHARP_MINOR     7
#define KEY_OF_D_MINOR          -1
#define KEY_OF_G_MINOR          -2
#define KEY_OF_C_MINOR          -3
#define KEY_OF_F_MINOR          -4
#define KEY_OF_B_FLAT_MINOR     -5
#define KEY_OF_E_FLAT_MINOR     -6
#define KEY_OF_A_FLAT_MINOR     -7

/* ========================================================================= *
                              Note or Chord item
 * ========================================================================= */

    /*  Note Items.

        CHORDS: The first note of a chord is always of type "note".
        Additional notes, or "intervals" are stored using the "chord"
        type. The itemXPos, noteTuple, noteDots, noteDivision, noteStyle,
        noteArpeggio, noteTrill and and noteBeamHeight fields are ignored
        for chord items and are derived from the base note, however score
        writers should set them to the same as the base note for consistency.

        RESTS: A rest is a note item with a notePitch of 255. Rests may not
        be chorded.

        DRUM HEADS: If the NOTEF_DRUM flag is set, indicating that the
        note has a "drum head" rather than an ordinary note head, then
        all of the pitch-modifier fields should be ignored.

        OPTIONAL FIELDS: For less sophisticated programs, many of the fields
        in the note structure can be ignored.
            At a minimum, notation programs should look at noteLevel,
        noteAccidental, noteDivision and noteDots. When writing, all other
        fields can be set to zero, with the exception of noteDuration
        which should be set to the formal duration of the note in clock
        ticks.
            Sequencer programs should look at notePitch and noteDuration
        when loading CMUS scores. Writing is more difficult. It is suggested
        that unless the program is very sophisticated, that a different
        FORM, or perhaps a Standard MIDI File, be used for writing out
        sequencer data, as most of the fields in CMUS have meaning only to
        a notator-type program.

        Explanation of Fields:
        ~~~~~~~~~~~~~~~~~~~~~~

        noteDuration -- The casual duration of the note.

        noteFlags -- various flags which affect either this note. Note that
            the NOTEF_TIED and NOTEF_TIEDOWN can be different for each
            note in a chord.

        noteDots: 0, 1 or 2 depending on the number of "dots" this note
            has. A dotted note is 50% longer. A double-dotted note is
            75% longer.

        noteDivision: Indicates the base duration of the note: whole note,
            half note, quarter note, etc.

        notePitch: The MIDI pitch number for this note.

        noteArpeggio: Indicates an arpeggiated chord, one where the individual
            notes are played sequentially (like a harp).

        noteTrill: Trills are a rapid alternation between two notes. There
            are vaious kinds, see below.

        noteAccidental: This includes things like sharps and flats.

        noteLevel: This is the distance, in levels, from the center line of
            the staff.

        noteBeamHeight: The height of a beamed group of notes isn't always
            related to the height that the stem would be if the note were not
            beamed. This field is the distance, in levels, from the center
            line of the staff to the beam's position. This field is only
            meaningful for the first and last note of a beam.

        noteStyle: This is a field of flags which indicate things like
            Staccato, Legato, and other "performance style" modifiers.
    */

/*  What the note structure looks like with bitfields:

    CM_ItemHeader       noteItem;           -- item header

    UWORD               noteDuration;       -- real duration, in ticks
    UWORD               noteFlags;

    unsigned int        Pad1           : 2
                        noteDots       : 2, -- dotted, double-dotted
                        noteDivision   : 4, -- quarter note, etc.

    UBYTE               notePitch;          -- MIDI note number
    unsigned int        noteArpeggio   : 2, -- arpeggiation
                        noteTrill      : 3, -- various trill types
                        noteAccidental : 3; -- sharp, flat, etc.

    BYTE                noteLevel;          -- dist from staff centerline
    BYTE                noteBeamHeight;     -- Y position of beam
    UBYTE               noteStyle;          -- Note Style type
*/

typedef struct {
    CM_ItemHeader       noteItem;           /* item header                  */

    UWORD               noteDuration;       /* real duration, in ticks      */
    UWORD               noteFlags;          /* various note flags           */

    UBYTE               noteDivision;       /* formal note length           */

    UBYTE               notePitch;          /* MIDI note number             */
    UBYTE               notePitchMods;      /* modifications to pitch       */
    BYTE                noteLevel;          /* vertical position            */

    BYTE                noteBeamHeight;     /* y position of beam           */
    UBYTE               noteStyle;          /* Note Style type              */
} CM_Note;

    /* macros to access the various bitfields */

#define CM_NoteDots(f)          (((f).noteDivision >> 4) & 0x03)
#define CM_NoteDivision(f)      ((f).noteDivision & 0x0f)

#define CM_NoteAccidental(f)    ((f).notePitchMods & 7)
#define CM_NoteTrill(f)         (((f).notePitchMods >> 3) & 7)
#define CM_NoteArpeggiation(f)  (((f).notePitchMods >> 6) & 3)

#define CM_SetNoteDivision(note, division, dots) \
        ((note).noteDivision = (dots << 4) | division)

#define CM_SetNotePitchMods(note, arp, trill, accidental) \
        ((note).notePitchMods = (arp << 6) | ((trill << 3) & 7) | (accidental & 7))

#define CM_RestPitch    255

enum note_dots {
    NO_DOT = 0,                             /* Note is normal duration      */
    DOTTED_NOTE = 1,                        /* Note is 50% longer           */
    DOUBLE_DOTTED = 2                       /* note is 75% longer           */
};

enum note_divisions {
    DOUBLE_WHOLE_NOTE = 0,
    WHOLE_NOTE,
    HALF_NOTE,
    QUARTER_NOTE,
    EIGHTH_NOTE,
    SIXTEENTH_NOTE,
    NOTE_32,
    NOTE_64,
    NOTE_128,
    NOTE_256
};

enum note_accidentals {
    NOTE_ACC_NONE=0,
    NOTE_ACC_DOUBLE_FLAT,
    NOTE_ACC_FLAT,
    NOTE_ACC_HALF_FLAT,
    NOTE_ACC_NATURAL,
    NOTE_ACC_HALF_SHARP,
    NOTE_ACC_SHARP,
    NOTE_ACC_DOUBLE_SHARP,

        /*  drum styles: used in place of accidental when NOTEF_DRUM is set.
            Hollow symbols are used in place of "hollow" note heads, such
            as half notes.

            Note that the assignment of drum parts to symbols is arbtrary,
            however the X symbol in jazz notation means "brush", and the
            triangle symbol is often assigned to the triangle instrument.
            Note also that normal note heads are often used for many
            drum instruments.
        */

    NOTE_DRUM_X=0,                          /* An "x" instead of note head  */
    NOTE_DRUM_DIAMOND,                      /* diamond shape                */
    NOTE_DRUM_SQUARE,                       /* square box                   */
    NOTE_DRUM_TRIANGLE,                     /* triangle                     */

};

    /*  trills and tremolos and other pitch modulations which can be attached
        to a note. Note that these apply to the entire chord.
    */

enum note_trills {
    NOTE_PMOD_NONE=0,
    NOTE_PMOD_TRILL,
    NOTE_PMOD_MORDENT,
    NOTE_PMOD_INV_MORDENT,
    NOTE_PMOD_TURN,
};

    /*  Arpeggiation, indicated as a vertical sqiggly line before the chord */

enum note_arp_mods {
    NOTE_ARPEGGIO = 1,
    NOTE_REV_ARPEGGIO = 2,
};

    /* note style flags */

#define NSTYLEF_STACCATO        (1<<0)      /* Staccatto mark ('.')         */
#define NSTYLEF_STACCATISSIMO   (1<<1)      /* Staccattissimo mark (wedge)  */
#define NSTYLEF_LEGATO          (1<<2)      /* Legato ('-')                 */
#define NSTYLEF_SFORZANDO       (1<<3)      /* Szorzando ('^')              */
#define NSTYLEF_ACCENT          (1<<4)      /* Accent ('>')                 */
#define NSTYLEF_TENUTO          (1<<5)      /* Tenuto (short '-')           */

    /* general note flags */

enum noteFlags {
    NOTEF_STEMDOWN      = (1<<0),           /* Note's stem is down          */
    NOTEF_BEAMED        = (1<<1),           /* Note is beamed with next note*/
    NOTEF_TIED          = (1<<2),           /* Note is tied with next note  */
    NOTEF_TIEDOWN       = (1<<3),           /* tie direction is DOWN        */
    NOTEF_GRACE         = (1<<4),           /* display as grace note        */
    NOTEF_CUE           = (1<<5),           /* display as cue note          */
    NOTEF_DRUM          = (1<<6),           /* note has a drum head         */
    NOTEF_STEMSET       = (1<<7),           /* Stem direction fixed by user */

    NOTEF_RES1          = (1<<12),          /* reserved by DMCS for play    */
    NOTEF_RES2          = (1<<13),          /*      styles (sorry :-)       */
    NOTEF_RES3          = (1<<14),
    NOTEF_RES4          = (1<<15),
};

/* ========================================================================= *
                                 Filler item
 * ========================================================================= */

    /*  This item is used for supporting sparse clips. The fillerDuration
        field contains the total of the formal durations of the missing
        items between the previous event and the next one.
    */

typedef struct {
    CM_ItemHeader       fillerItem;         /* item header                  */
    UWORD               fillerDuration;     /* formal size of items left out*/
} CM_Filler;

/* ========================================================================= *
                                 Dynamic Item
 * ========================================================================= */

    /*  This item specifies a MIDI volume. Note that the relationship between
        Volume and dynamic markings (such as fff, pp, etc) is defined
        elsewhere.
    */

typedef struct {
    CM_ItemHeader       dynItem;            /* item header                  */
    BYTE                dynLevelPos;        /* vertical position in leveks  */
    UBYTE               dynVolume;          /* midi pressure number (0..127)*/
    BYTE                dynSymbol;          /* dynamic symbol, see below    */
    UBYTE               dynPad;
} CM_Dynamic;

    /*  Dynamic symbols:

        0 = symbol not specified, derive from MIDI volume.
        +1 = mf         -1 = mp
        +2 = f          -2 = p
        +3 = ff         -3 = pp
        +4 = fff        -4 = ppp
                (etc)
    */

/* ========================================================================= *
                               Instrument item
 * ========================================================================= */

    /*  Rather than embedding the instrument names in the actual score, a
        seperate "instrument table" chunk will be defined.
    */

typedef struct {
    CM_ItemHeader       instItem;           /* instrument item              */
    UBYTE               instNumber;         /* instrument number from table */
    UBYTE               instPad;
} CM_Instrument;

/* ========================================================================= *
                                  Tempo Item
 * ========================================================================= */

    /*  For compatibility with Standard MIDI files, tempo is represented as
        microseconds per quarter note, rather than the more commonly used
        quarter notes per minute. To convert from one to the other, the
        following formula works both ways:

                T = 60,000,000 / t;

        For accuracy, you may want to round:

                T = (60,000,000 + t/2) / t;

        Of course, the user interface of the program should not use units
        like this.
    */

typedef struct {
    CM_ItemHeader       tempoItem;          /* item header                  */
    ULONG               tempoValue;         /* new tempo value              */
} CM_Tempo;

/* ========================================================================= *
                                 Repeat Item
 * ========================================================================= */

    /*  This is a general category of items for jumping around in the
        score in a non-sequential fashion. It includes things like
        begin/end repeat bars, repeat measure, Da Capo, etc.

        "repeatCount" is the number of times that the jump should occur,
        not the total number of times a passage should be played. For example,
        an begin/end repeat which is to play twice (once through, and then
        prepeated once) should have a repeatCount of "1".

        In addition, repeatCount should be associated with the jump rather
        than the label. This imples that the count should go with the
        "end" of a begin/end block rather than the "begin".
    */

typedef struct {
    CM_ItemHeader       repeatItem;         /* item header                  */
    UBYTE               repeatType;         /* subtype of group             */
    UBYTE               repeatCount;        /* number of times to jump      */
} CM_Repeat;

enum repeat_types {
    REPEAT_BLOCK_BEGIN=0,                   /* defines a repeat block       */
    REPEAT_BLOCK_END,

    REPEAT_LAST_MEASURE,                    /* jumps back 1 measure         */
    REPEAT_LAST_TWO_MEASURES,               /* jumps back 2 measures        */

    REPEAT_MEASURE_REST,                    /* rest for N measures          */
                                            /* (not really a jump)          */
        /* labels to go to */

    REPEAT_LABEL_SEGNO,                     /* The "sign" D.S. refers to    */
    REPEAT_LABEL_CODA,                      /* The Coda symbol              */

        /* goto operators */

    REPEAT_DC,                              /* D.C.                         */
    REPEAT_DC_AL_FINE,                      /* D.C. al fine                 */
    REPEAT_DS,                              /* D.S.                         */
    REPEAT_DS_AL_FINE,                      /* D.S. al fine                 */
    REPEAT_DS_AL_CODA,                      /* D.S. al coda                 */
};

/* ========================================================================= *
                                   Group Item
 * ========================================================================= */

    /*  A "Group" Item is defined as a Slur, Crescendo, or Octave Raiser.
        In general, groups can apply to any contiguous range of notes
        on a track, and groups of the same type can note overlap.

        Note that in some cases, such as for example a crecendo, although
        the modification is technically "attached" to a particular
        track, it affects all the tracks on that staff.
    */

typedef struct {
    CM_ItemHeader       groupItem;          /* item header                  */
    UBYTE               groupType;          /* subtype of group             */

        /*  To even out the structure, we'll add an extra byte which means
            different things based on the group type. Right now it is
            only defined in the case of a crescendo / decrescendo in which
            case it means the final volume.

            For all others, it should be set to zero.
        */

    UBYTE               groupVal;
} CM_Group;

    /* Types of group items supported */

enum group_types {
    GROUPTYPE_SLUR_UP=0,
    GROUPTYPE_SLUR_DOWN,
    GROUPTYPE_CRESCENDO,
    GROUPTYPE_DECRESCENDO,
    GROUPTYPE_OCTAVE_UP,                    /* "8va" symbol                 */
    GROUPTYPE_OCTAVE_DOWN,                  /* "8vb" symbol                 */
    GROUPTYPE_GLISSANDO_UP,
    GROUPTYPE_GLISSANDO_DOWN,

    GROUPTYPE_TUPLET,                       /* see below                    */
    GROUPTYPE_TRILL,                        /* the one with the wavy line   */
    GROUPTYPE_TREMOLO,                      /* Slashes below a beam         */
};

    /* Tuplets are a subtype of group items, and as such have an extended
        structure. Unlike other group types, tuplet group items can be nested.

        Note that for ending a tuplet, the extra fields are not required
        and a normal "Group" structure can be used. Each tuplet ending
        item matches the nearest previous unmatched tuplet item.
    */

typedef struct {
    CM_ItemHeader       tupletItem;         /* item header                  */
    UBYTE               tupletType;         /* subtype of group             */

        /*  tupletNumber indicates how many notes can fit in the space of
            'tupletSpace'. For example, a triplet, i.e. "3 in the space of 2",
            or 2/3 duration, can be represented as tupletNumber = 3,
            tupletSpace = 2.
        */

    UBYTE               tupletNumber,       /* How manu items               */
                        tupletSpace;        /* in the space of how many     */

        /*  tupletDigits represents the binary number which should be
            displayed above the tuplet; For example, for a triplet this
            should be 3.
        */

    UBYTE               tupletDigits;       /* number to display            */

        /*  tupletFlags is for later use when we want tuplets combined with
            slurs / brackets. Currently there are no flags defined, so the
            field should be all zeroes.
        */

    UBYTE               tupletFlags,        /* various flags                */
                        tupletPad;
} CM_Tuplet;

/* ========================================================================= *
                                    Tablature Item
 * ========================================================================= */

    /*  The Tablature item is used for guitar, banjo or other fretted
        instruments. It's a two-dimensional array of bits, which is drawn
        as a grid indicating the exact placement of fingers.

        In addition, most tablatures have the name of the chord placed above
        the grid. This can be quite complex, looking something like this:

                     7+6
                C min

        Which means: "C minor, with an added seventh and a raised sixth".
    */

typedef struct {
    CM_ItemHeader       tabItem;            /* item header                  */

        /*  tabRoot is used to indicate the name of the chord placed above
            the tablature. Note that the root can have superscripts, which
            are defined elsewhere.

            unsigned int    rootLetter      : 3,    -- A, B, C, etc.
                            rootAccidental  : 2,    -- accidental of root
                            rootType        : 3,    -- major, minor, etc.
        */

    UBYTE               tabRoot;            /* describes root of chord      */

        /*  tabDimensions is a field of two 4 bit values, representing the
            width and height of the tablature array. A dimension of (0,0)
            indicates that only the chord symbol should be used.
        */

    UBYTE               tabDimensions;      /* width/height of tab array    */

        /*  tabIntervals is an optional field -- if it's zero, it means that
            the writing program wasn't sophisticated enough to set it.
            (This is generally true for programs that are typographical
            rather than musical in orientation).

            The field used to exactly describe the intervals in the
            chord above the root. Each interval may be:

                0 - missing ( no interval)
                1 - lowered ( one half-step below major chord position )
                2 - normal  ( in the normal position for a major chord )
                3 - raised  ( one half-step above major chord position )

            unsigned int    chordThird      : 2,    -- (missing, -1, 0, +1)
                            chordFifth      : 2,    -- (missing, -1, 0, +1)
                            chordSeventh    : 2,    -- (missing, -1, 0, +1)
                            chordNinth      : 2,    -- (missing, -1, 0, +1)
                            chordEleventh   : 2,    -- (missing, -1, 0, +1)
                            chordThirteenth : 2,    -- (missing, -1, 0, +1)
                            chordFifteenth  : 2,    -- (missing, -1, 0, +1)
                            chordValid      : 1,    -- TRUE if field valid
                            chordPad        : 1;
        */

    UWORD               tabIntervals;       /* describes exact chord intervals*/

        /*  tabArray is a byte array of finger positions.

            Each byte represents a string. The value of the byte
            can be from 0 (representing an open string), or 1-16
            (representing a finger placed above the Nth fret). The high
            4 bits are reserved for now, but may be used later to indicate
            special placement of the fingers.

            Note that the tabArray can be longer or shorter than 6 bytes,
            up to a maximum of 16 strings. In such cases, the event length
            stored in the CM_ItemHeader would be adjusted accordingly.
        */

    UBYTE               tabArray[6];        /* tablature array              */

        /*  Following the tabArray field is an optional variable-length
            ASCII string which is the actual text of the superscript,
            such as "maj6+7".

            The length of the string can be computed comparing the end of
            the event with the end of the tab-array. Null termination is
            not required.
        */

};

enum chord_accidentals {
    CHORD_ACC_NONE=0,
    CHORD_ACC_FLAT,
    CHORD_ACC_NATURAL,
    CHORD_ACC_SHARP
};

enum chord_types {
    CHORD_TYPE_MAJOR,
    CHORD_TYPE_MINOR,
    CHORD_TYPE_DIMINISHED,
    CHORD_TYPE_AUGMENTED,
    CHORD_TYPE_SUSPENDED
};

enum chord_letters {
    CHORD_LETTER_A=0,
    CHORD_LETTER_B,
    CHORD_LETTER_C,
    CHORD_LETTER_D,
    CHORD_LETTER_E,
    CHORD_LETTER_F,
    CHORD_LETTER_G
};

/* ========================================================================= *
                           Lyric Font Chunk (LFON)

    This section describes the data structures which are used in the CMUS
    'LFON' Chunk.

    LFON chunks are used to store the font table for the document. Embedded
    within the Lyric, Annotation and title chunks are font specifiers which
    refer to a given font by number. That number is an index into this table.

    There is one LFON chunk per font. Each LFON chunk consists of the following
    header, and then the name of the font. The terminating NULL should be
    included in the font name.

 * ========================================================================= */

typedef struct {
    UWORD               fontNumber;             /* number assigned to font  */
    UWORD               fontHeight;             /* height of font in points */

    /* fontName follows */

} CM_FontEntry;

/* ========================================================================= *
                              Lyric Chunk (LYRC)

    This section describes the data structures which are used in the CMUS
    'LYRC' Chunk.

    Each lyric is associated with a particular track, and a particular measure
    within that track. The reason for this is because certain elements within
    the lyrics can be "attached" to notes within a track, so that syllables
    of the lyric can properly appear under the notes.

    Lyrics associated with a particular track are written immediately after
    that track. In other words, when reading a lyric, it should be associated
    with the previously read track.

 * ========================================================================= */

    /*  This is the header structure for a lyric. It is followed by the actual
        text of the lyric. No terminating NUL is used.

        Attaching syllables to notes: This is an optional feature which need
        not be supported by all readers. Basically, the TAB character is used
        to specify a block of text to align with the next note. Essentially,
        each chord on the track acts as a center-justified tab-stop. This is
        similar to the way tab stops work on medium- to high-end word
        processors: All the text between a tab, and the next tab (or the end
        of the line) is "centered" at the tab-stop position. Readers
        which don't wish to deal with this level of complexity can just
        treat the tab as a space.
    */

typedef struct {
    UWORD               lyricMeasure;       /* starting measure of lyric    */

        /*  Position of the upper-left coordinate of the lyric.
            This can be positive or negative, and is interpreted just like
            the 'itemXPos' field for track events.
        */

    WORD                lyricXPos;          /* position relative to measure */

        /*  lyricLevel is the position, in micrometers, of the upper-
            left corner of the lyric's extent box.

            lyricHeight is also in micrometers.
        */

    Micrometers         lyricLevel,         /* distance from center of staff*/
                        lyricHeight;        /* height of lyric extent       */

        /*  Width is in micrometers. */

    Micrometers         lyricWidth;

        /* lyric text string follows */

} CM_Lyric;

    /*  Codes for specification of fonts and text styles. The "newfont" code
        is followed by the font number. If no font is specified, font #0 is
        the default.
    */

enum {
    LSTYLE_BOLD_ON=0x80,
    LSTYLE_BOLD_OFF,
    LSTYLE_ITALIC_ON,
    LSTYLE_ITALIC_OFF,
    LSTYLE_UNDER_ON,
    LSTYLE_UNDER_OFF,
    LSTYLE_NEWFONT,                             /* font number follows      */
};

/* ========================================================================= *
                             Annotation chunks (ANOT)

    This section describes the data structures which are used in the CMUS
    'ANOT' Chunk. Note that there is a standard IFF chunk called 'ANNO'
    which can be added to any file to annotate the file. The 'ANOT' is
    used to specify annotations to the music, not to the file.

 * ========================================================================= */

    /*  Annotation chunks are specified exactly like Lyric chunks. The only
        reason for distinguishing between the two is that a "stripper" program
        might want to strip out one or the other.
    */

/* ========================================================================= *
                               Title Chunk (TITL)

    This section describes the data structures which are used in the CMUS 'TITL'
    Chunk. Unlike Lyrics, Titles are placed at fixed positions on the page
    (generally at the top) and are are not adjusted based on the positioning
    of any particular measure.

 * ========================================================================= */

    /*  Title chunks are specified exactly like Lyric chunks, except that the
        lyricMeasure field is ignored and should be set to 0.

        In particular, the lyricXPos field is no longer based on measure width,
        but is now a fractional width of the document. Similarly, the
        lyricLevel field is the number of levels from the top of the page.
        (Or should that be an absolute measure?)
    */

/* ========================================================================= *
                          CMUS Instrument Table (FORM INST)

        The instrument table fo the CMUS form is stored as an embedded FORM
    called 'INST'. Each instrument in the table is one INST form.

        Instruments can be configured for MIDI, internal audio, or both.
    When using internal sounds, samples can be sepcified using an embedded
    FORM 8SVX, or any other IFF sampled sound FORM that the program wishes
    to support. Sampled sounds can be embedded in the file, or external
    sample files can be referenced from within the file, by pathname.

        Here's a summary of the chunks which can be included in an INST
    form:

        'INHD': This is the instrument header. It contains the instrument
            number, and the various MIDI-related parameters. The chunk
            format is defined below.

        'FORM 8SVX': This is an embedded sampled sound file. The sampled
            sound is to be associated with the instrument.

        'SFIL': This is a reference to a sampled sound in a different file,
            and can be used instead of an embedded sample. The chunk format
            is simply the name of the file. If the file contains more than
            one sample, only the first is used. (A different chunk can be
            defined to select the Nth sample, if it turns out that this
            feature might be desired).

        'SHAR': This allows a instrument to share a sampled sound with
            another instrument. This would be used instead of either and
            embedded sample or an 'SFIL' chunk. The chunk format is simple
            a UWORD of the instrument number to share with; This
            instrument must have been previously loaded.

        'ATAK': Identical with the ATAK chunk in FORM 8SVX, this allows
            the instrument have a different envelope than the one in
            the sampled sound file.

        'RLSE': Identical with the RLSE chunk in FORM 8SVX, this allows the
            instrument have a different envelope than the one in the
            sampled sound file.

        'NAME': is a standard chunk which can be added to any IFF FORM.
            In this case, it is used to store the instrument name. Other
            standard chunks which can be added are "AUTH" (author name),
            "VERS" (version string), "ANNO" (Annotations) and "(C) "
            (copyright notice).

    Note: If there is no sampled sound specified, either through an
        embedded sample or SFIL or SHAR chunks, then this instrument is
        a MIDI-only instrument.

 * ========================================================================= */

    /* Instrument header chunk -- INHD */

typedef struct {

        /*  'instNumber' corresponds to the instrument number used
            in the "instrument event" in the TRCK chunk.
        */

    UBYTE               instNumber;

    UBYTE               instFlags;          /* various flags                */
    WORD                instTune;           /* tuning, in 1/100 semitones   */
    WORD                instVolume;         /* overall volume, 0-0xffff     */

        /*  "Pan" can be used by both MIDI and sampled sound instruments, and
            indicates a preferences for left or right. It ranges from 0 to
            127 (same as MIDI), with 0 being ?? and 127 being ??.
        */

    UBYTE               instPan;

        /*  MIDI-related variables */

    UBYTE               instMidiChannel;    /* MIDI channel to use          */
    UBYTE               instMidiPreset;     /* MIDI Preset for this channel */
    UBYTE               instMidiPort;       /* Hardware port #, if applies  */

} InstrumentHeader;

#define INST_MAXVOL     0x0ffff
#define INST_MAXPAN     127

    /* various flags for instFlags */

#define INSTF_MIDI      (1<<0)              /* MIDI is enabled              */
#define INSTF_MIDIVOL   (1<<1)              /* use MIDI volume, not velocity*/

#endif

DEEP

Chunky pixel image files (Used in TV Paint)

IFF FORM / CHUNK DESCRIPTION
============================

Form/Chunk ID:	FORM  DEEP	(DEEP pixels)
		Chunk DGBL	(Deep GloBaL information)
		Chunk DPEL	(Deep Pixel ELements)
		Chunk DLOC	(Deep display LOCation)
		Chunk DBOD	(Deep data BODy)
		Chunk DCHG	(Deep CHanGe buffer)

Date Submitted:	10-Sep-91
Submitted by:	Amiga Centre Scotland


FORM
====

FORM ID:	DEEP	(DEEP pixels)

FORM Purpose:

To allow faster loading and saving of images when pixels are
stored in consecutive memory locations and provide support for
common extensions implemented on advanced graphics cards.

FORM Description:

This form is designed to provide support for a variety of deep
pixels, including 24 bits images.  A deep pixel is one in which
the pixel value is used to directly produce the output colour
without the use of a colour look-up table and also where the
pixel is stored in consecutive memory locations.  The format
allows additional bits to be stored along with the colour bits
to provide support for additional features such as masks,
Z-buffers, linear keys, etc.

The format is designed to allow different colour formats to be
stored such as RGB, RGBA, YCM and YCMB with varying depths
supported.  Bit ordering will be most significant bit first.


CHUNKS
======

Chunk ID:	DGBL	(Deep GloBaL information)

Chunk Purpose:

Provide global information of relevance to all the data contained
in the file.  DGBL will always be the first chunk in the file.

Chunk Description:

Used to provide information that is constant for all contents of
the file.  One chunk is mandatory at the start of the file.  When
the file is used to store a group of images it may, in
exceptional circumstances, be necessary to add additional DGBL
chunks.  The contents of a DGBL chunk remain valid until another
DGBL chunk is encountered.


Chunk ID:	DPEL	(Deep Pixel Elements)

Chunk Purpose:

Defines the contents of each pixel.  Enables the data content to
be identified and handled.  Data that is unknown or not required
can be discarded.

Chunk Description:

This chunk is best described by an example:

	Original data = RGBA 8:8:8:4

	DPEL =
		4	(number of elements)
			RED	(first element)
			8	(bits in element)
			GREEN	(second element)
			8	(bits in second element)
			BLUE	(third element)
			8	(bits in third element)
			ALPHA	(fourth element)
			4	(bits in fourth element)

	Stored data (binary) = rrrrrrrr gggggggg bbbbbbbb aaaa0000

  Note:  The pixel has been padded to the next byte boundary.

The elements must be defined in the order in which they are
stored, with the most significant bit first.


Chunk ID:	DLOC	(Deep display LOCation)

Chunk Purpose:

Provides information specific to the following DBOD section.
Enables image sections to be located within the screen area
individually & allows images with a size different to
DisplayWidth & DisplayHeight to be stored.

Chunk Description:

Specifies the width, height and where to place the following Deep
data BODy.  If no DLOC is encountered before a DBOD, the
DisplayWidth & DisplayHeight parameters will be used as the DBOD
image data dimensions.  The contents of a DLOC chunk remain valid
until another DLOC chunk is encountered.


Chunk ID:	DBOD	(Deep BODy)

Chunk Purpose:

Contains the image data.

Chunk Description:

Contains image data compressed by the method defined in DGBL.
The image size and the location where it is to be displayed is
provided by a DLOC chunk.  If no DLOC chunk has been read the
data will be displayed in the upper left corner and will be
DisplayWidth wide and DisplayHeight high.


Chunk ID:	DCHG	(Deep CHanGe buffer)

Chunk Purpose:

Informs the IFF reader that a complete frame has been read.  Only
required when multiple images are stored for cell animation.

Chunk Description:

When a DCHG chunk is encounter the IFF reader knows that a
complete frame has been read.  The chunk gives the time *from the
last frame change* before the frame should be changed again.  If
the time has already elapsed the frame should be changed
immediately.  A FrameRate of 0 will cause the frame changes to
occur as fast as possible.  A FrameRate of -1 is used to indicate
the end of the data for one frame and the start of the next in
cases where multiple frames are stored but are not intended for
animation.  A DCHG chunk is not required when only a single frame
is stored.



//
//FORM DEEP
//=========
//
//  Chunk DGBL
//  ----------
//
    struct DGBL = {
//
// Size of source display
//
      UWORD  DisplayWidth,DisplayHeight;
//
// Type of compression
//
      UWORD  Compression;
//
// Pixel aspect, a ration w:h
//
      UBYTE  xAspect,yAspect;
    };

//
//   Chunk DPEL
//   ----------
    struct DPEL = {
//
// Number of pixel components
//
    ULONG nElements;
//
// The TypeDepth structure is repeated nElement times to identify
// the content of every pixel.  Pixels will always be padded to
// byte boundaries.  The DBOD chunk will be padded to an even
// longword boundary.
//
    struct TypeDepth = {
//
// Type of data
//
      UWORD cType;
//
// Bit depth of this type
//
      UWORD cBitDepth;
      } typedepth[Nelements];
    };

//
//  Chunk DLOC
//  ----------
//
    struct DLOC = {
//
// Body width & height in pixels
//
      UWORD	w,h
//
// Pixel position for this image
//
      WORD	x,y
    };

//
//  Chunk DBOD
//  ----------
//
    pixel[0], pixel[2], pixel[3], ...., pixel[w-1]
    pixel[((h-1)*w)], ...,pixel[h*w-1]

//
//  Chunk DCHG
//  ----------
//
    struct DCHG = {
//
// Animation control (When multiple images are stored)
// FrameRate - milli-seconds between frames changes
//
      LONG  FrameRate;
    };

Compressions currently defined:

NOCOMPRESSION	=	0
RUNLENGTH	=	1
HUFFMAN		=	2
DYNAMICHUFF	=	3
JPEG		=	4

Ctype currently defined:

RED		=	1
GREEN		=	2
BLUE		=	3
ALPHA		=	4	(no precise definition of use)
YELLOW		=	5
CYAN		=	6
MAGENTA		=	7
BLACK		=	8
MASK		=	9
ZBUFFER		=	10
OPACITY		=	11
LINEARKEY	=	12
BINARYKEY	=	13

----------------------------------------------------------------------

Addendum
========

The following information is an extension to the DEEP format
proposed by TecSoft and used in their 24 bit paint application,
TVPaint.  The extension provides an additional compression method
and its associated chunk.

Additional compression type:

TVDC		=	5

Chunk ID:	TVDC	(TVPaint Deep Compression)

Chunk Purpose:

Provides the table of values required to enable decompression of
the image data.

Chunk Description:

TVDC is a modified version of Delta compression, using a 16 word
lookup table of delta values and also incorporates Run Length
Limiting compression for short runs.

Note that the compression is made line by line for each element
of the chunk DPEL.  For RGBA for example we have a Red line, a
Green line, and so on.

CDepackTVDC(source,dest,table,size)
UBYTE	*source;
UBYTE	*dest;
WORD	*table;
int	size;
{
int	i;
int	d;
int	pos=0;
UBYTE	v=0;

	for(i=0;i<size;i++)
	{
		d=source[pos>>1];
		if(pos++&1) d&=0xf;
		else d>>=4;
		v+=table[d];
		dest[i]=v;
		if(!table[d])
		{
			d=source[pos>>1];
			if(pos++&1) d&=0xf;
			else d>>=4;
			while(d--) dest[++i]=v;
		}
	}
	return((pos+1)/2);
}

DTYP

DataTypes Identification

#ifndef  LIBRARIES_DATATYPES_H
#define  LIBRARIES_DATATYPES_H
/*
**	$Id: datatypes.h,v 39.1 91/12/13 10:17:52 davidj Exp $
**
**	(C) Copyright 1991-1999 Amiga, Inc.
**	    All Rights Reserved
*/
#ifndef  EXEC_TYPES_H
#include <exec/types.h>
#endif
#ifndef  EXEC_LISTS_H
#include <exec/lists.h>
#endif
#ifndef  EXEC_NODES_H
#include <exec/nodes.h>
#endif
#ifndef  EXEC_LIBRARIES_H
#include <exec/libraries.h>
#endif
#ifndef  LIBRARIES_IFFPARSE_H
#include <libraries/iffparse.h>
#endif

/*****************************************************************************/

#define ID_DTYP MAKE_ID('D','T','Y','P')

/*****************************************************************************/

#define ID_DTHD MAKE_ID('D','T','H','D')

struct DataTypeHeader
{
    STRPTR	 dth_Name;				/* Descriptive name of the data type */
    STRPTR	 dth_BaseName;				/* Base name of the data type */
    STRPTR	 dth_Pattern;				/* Match pattern for file name. */
    WORD	*dth_Mask;				/* Comparision mask */
    ULONG	 dth_GroupID;				/* Group that the DataType is in */
    ULONG	 dth_ID;				/* ID for DataType (same as IFF FORM type) */
    WORD	 dth_MaskLen;				/* Length of comparision mask */
    WORD	 dth_Pad;				/* Unused at present (must be 0) */
    UWORD	 dth_Flags;				/* Flags */
    UWORD	 dth_Priority;				/* Priority */
};

#define	DTHSIZE	sizeof(struct DataTypeHeader)

/*****************************************************************************/

/* Basic file type */
#define	DTF_TYPE_MASK	0x000F
#define	DTF_BINARY	0x0000
#define	DTF_ASCII	0x0001
#define	DTF_IFF		0x0002
#define	DTF_MISC	0x0003

/* Set if case is important */
#define	DTF_CASE	0x0010

/* Reserved for system use */
#define	DTF_SYSTEM1	0x1000

/*****************************************************************************
 *
 * GROUP ID and ID
 *
 * This is used for filtering out objects that you don't want.  For
 * example, you could make a filter for the ASL file requester so
 * that it only showed the files that were pictures, or even to
 * narrow it down to only show files that were ILBM pictures.
 *
 * Note that the Group ID's are in lower case, and always the first
 * four characters of the word.
 *
 * For ID's; If it is an IFF file, then the ID is the same as the
 * FORM type.  If it isn't an IFF file, then the ID would be the
 * first four characters of name for the file type.
 *
 *****************************************************************************/

/* System file, such as; directory, executable, library, device, font, etc. */
#define	GID_SYSTEM	MAKE_ID ('s','y','s','t')

/* Formatted or unformatted text */
#define	GID_TEXT	MAKE_ID ('t','e','x','t')

/* Formatted text with graphics or other DataTypes */
#define	GID_DOCUMENT	MAKE_ID ('d','o','c','u')

/* Sound */
#define	GID_SOUND	MAKE_ID ('s','o','u','n')

/* Musical instruments used for musical scores */
#define	GID_INSTRUMENT	MAKE_ID ('i','n','s','t')

/* Musical score */
#define	GID_MUSIC	MAKE_ID ('m','u','s','i')

/* Still picture */
#define	GID_PICTURE	MAKE_ID ('p','i','c','t')

/* Animated picture */
#define	GID_ANIMATION	MAKE_ID ('a','n','i','m')

/* Animation with audio track */
#define	GID_MOVIE	MAKE_ID ('m','o','v','i')

/*****************************************************************************/

/* A DTCD chunk contains an embedded executable that can be loaded
 * with InternalLoadSeg. */
#define ID_CODE MAKE_ID('D','T','C','D')

/* DataTypes comparision hook context (Read-Only).  This is the
 * argument that is passed to a custom comparision routine. */
struct DTHookContext
{
    /* Libraries that are already opened for your use */
    struct Library		*dthc_SysBase;
    struct Library		*dthc_DOSBase;
    struct Library		*dthc_IFFParseBase;
    struct Library		*dthc_UtilityBase;

    /* File context */
    BPTR			 dthc_Lock;
    struct FileInfoBlock	*dthc_FIB;
    BPTR			 dthc_FileHandle;
    struct IFFHandle		*dthc_IFF;
    STRPTR			 dthc_Buffer;		/* Buffer */
    ULONG			 dthc_BufferLength;	/* Length of the buffer */
};

/*****************************************************************************/

#define ID_DTTL MAKE_ID('D','T','T','L')

struct Tool
{
    UWORD	 tn_Which;				/* Which tool is this */
    UWORD	 tn_Flags;				/* Flags */
    STRPTR	 tn_Program;				/* Application to use */
};

#define	TSIZE	sizeof(struct Tool)

/* defines for tn_Which */
#define	TW_INFO			1
#define	TW_BROWSE		2
#define	TW_EDIT			3
#define	TW_PRINT		4
#define	TW_MAIL			5

/* defines for tn_Flags */
#define	TF_LAUNCH_MASK		0x000F
#define	TF_SHELL		0x0001
#define	TF_WORKBENCH		0x0002
#define	TF_RX			0x0003

/*****************************************************************************/

#ifndef	DATATYPE
#define	DATATYPE
struct DataType
{
    struct Node	 		 dtn_Node1;		/* Reserved for system use */
    struct Node			 dtn_Node2;		/* Reserved for system use */
    struct DataTypeHeader	*dtn_Header;		/* Pointer to the DataTypeHeader */
    struct List			 dtn_ToolList;		/* List of tool nodes */
    STRPTR			 dtn_FunctionName;	/* Name of comparision routine */
    ULONG			 dtn_Length;		/* Length of the memory block */
};
#endif

#define	DTNSIZE	sizeof(struct DataType)

/*****************************************************************************/

struct ToolNode
{
    struct Node	 tn_Node;				/* Embedded node */
    struct Tool  tn_Tool;				/* Embedded tool */
    ULONG	 tn_Length;				/* Length of the memory block */
};

#define	TNSIZE	sizeof(struct ToolNode)

/*****************************************************************************/

#ifndef	ID_NAME
#define	ID_NAME	MAKE_ID('N','A','M','E')
#endif

#endif   /* LIBRARIES_DATATYPES_H */

HEAD

TITLE:  HEAD  (FORM used by Flow - New Horizons Software, Inc.)

IFF FORM / CHUNK DESCRIPTION
============================

Form/Chunk ID:  FORM HEAD, Chunks NEST, TEXT, FSCC

Date Submitted: 03/87
Submitted by:   James Bayless - New Horizons Software, Inc.


FORM
====

FORM ID:  HEAD

FORM Description: 

   FORM HEAD is the file storage format of the Flow idea processor
by New Horizons Software, Inc.  Currently only the TEXT and NEST
chunks are used.  There are plans to incorporate FSCC and some
additional chunks for headers and footers.


CHUNKS
======

CHUNK ID:  NEST

   This chunk consists of only of a word (two byte) value that gives
the new current nesting level of the outline.  The initial nesting level
(outermost level) is zero.  It is necessary to include a NEST chunk only
when the nesting level changes.  Valid changes to the nesting level are
either to decrease the current value by any amount (with a minimum of 0)
or to increase it by one (and not more than one).


CHUNK ID:  TEXT

   This chunk is the actual text of a heading.  Each heading has a TEXT
chunk (even if empty).  The text is not NULL terminated - the chunk
size gives the length of the heading text.


CHUNK ID: FSCC

   This chunk gives the Font/Style/Color changes in the heading from the
most recent TEXT chunk.  It should occur immediately after the TEXT chunk
it modifies.  The format is identical to the FSCC chunk for the IFF
form type 'WORD' (for compatibility), except that only the 'Location'
and 'Style' values are used (i.e., there can be currently only be style
changes in an outline heading).  The structure definition is:

typedef struct {
   UWORD   Location;   /* Char location of change */
   UBYTE   FontNum;    /* Ignored */
   UBYTE   Style;      /* Amiga style bits */
   UBYTE   MiscStyle;  /* Ignored */
   UBYTE   Color;      /* Ignored */
   UWORD   pad;        /* Ignored */
} FSCChange;

   The actual chunk consists of an array of these structures, one entry
for each Style change in the heading text.

PRSP

DPaint IV perspective move.

/* ----------------------------------------------------------------------- 
   IFF Information:
       PRSP ::= "FORM" # {"PSRP" MOVE }
       MOVE ::= "MOVE" # { MoveState  }
 * ---------------------------------------------------------------------- */
typedef struct {
   BYTE reserved;         /* initialize to 0 */
   BYTE moveDir;          /* 0 = from point  1 = to point  */
   BYTE recordDir;        /* 0 = FORWARD,    1 = STILL, 2 = BACKWARD */
   BYTE rotationType;     /* 0 = SCREEN_RELATIVE, 1 = BRUSH_RELATIVE */
   BYTE translationType;  /* 0 = SCREEN_RELATIVE, 1 = BRUSH_RELATIVE */
   BYTE cyclic;           /* 0 = NO, 1 = YES */
   SHORT distance[3];     /* x,y,z distance displacement */
   SHORT angle[3];        /* x,y,z rotation angles */
   SHORT nframes;         /* number of frames to move */
   SHORT easeout;         /* number of frames to ease out */
   SHORT easein;          /* number of frames to ease in */
   } MoveState;

RGB image

FORM RGBN and FORM RGB8
-----------------------

RGBN and RGB8 files are used in Impulse's Turbo Silver and Imagine.
They are almost identical to FORM ILBM's except for the BODY chunk
and slight differences in the BMHD chunk.

A CAMG chunk IS REQUIRED.

The BMHD chunk specfies the number of bitplanes as 13 for type RGBN
and 25 for type RGB8, and the compression type as 4.

The FORM RGBN uses 12 bit RGB values, and the FORM RGB8 uses
24 bit RGB values.

The BODY chunk contains RGB values, a "genlock" bit, and repeat
counts.  In Silver, when "genlock" bit is set, a "zero color" is
written into the bitplanes for genlock video to show through.
In Diamond and Light24 (Impulse 12 & 24 bit paint programs),
the genlock bit is ignored if the file is loaded as a picture
(and the RGB color is used instead), and if the file is loaded
as a brush the genlock bit marks pixels that are not part of
the brush.

For both RGBN and RGB8 body chunks, each RGB value always has a
repeat count.  The values are written in different formats depending
on the magnitude of the repeat count.

For the RGBN BODY chunk:

        For each RGB value, a WORD (16-bits) is written: with the
        12 RGB bits in the MSB (most significant bit) positions;
        the "genlock" bit next; and then a 3 bit repeat count.  
        If the repeat count is greater than 7, the 3-bit count is
        zero, and a BYTE repeat count follows.  If the repeat count
        is greater than 255, the BYTE count is zero, and a WORD
        repeat count follows.  Repeat counts greater than 65536 are
        not supported.

For the RGB8 body chunk:

        For each RGB value, a LONG-word (32 bits) is written:
        with the 24 RGB bits in the MSB positions; the "genlock"
        bit next, and then a 7 bit repeat count.

        In a previous version of this document, there appeared the
        following line:

        "If the repeat count is greater than 127, the same rules apply
        as in the RGBN BODY."

        But Impulse has never written more than a 7 bit repeat count,
        and when Imagine and Light24 were written, they didn't support
        reading anything but 7 bit counts.

Sample BODY code:

                if(!count) {
                        if (Rgb8) {
                                fread (&w, 4, 1, RGBFile);
                                lock = w & 0x00000080;
                                rgb = w >> 8;
                                count = w & 0x0000007f;
                        } else {
                                w = (UWORD) getw (RGBFile);
                                lock = w & 8;
                                rgb = w >> 4;
                                count = w & 7;
                        }
                        if (!count)
                                if (!(count = (UBYTE) getc (RGBFile)))
                                        count = (UWORD) getw (RGBFile);
                }

The pixels are scanned from left to right across horizontal
lines, processing from top to bottom.  The (12 or 24 bit) RGB
values are stored with the red bits as the MSB's, the green
bits next, and the blue bits as the LSB's.

Special note:  As of this writing (Sep 88), Silver does NOT
support anything but black for color zero.

Additional documents

Intro to IFF Amiga ILBM Files and Amiga Viewmodes

The IFF (Interchange File Format) for graphic images on the Amiga is called FORM ILBM (InterLeaved BitMap). It follows a standard parsable IFF format.

Sample hex dump of beginning of an ILBM

Important note! You can NOT ever depend on any particular ILBM chunk being at any particular offset into the file! IFF files are composed, in their simplest form, of chunks within a FORM. Each chunk starts starts with a 4-letter chunkID, followed by a 32-bit length of the rest of the chunk. You PARSE IFF files, skipping past unneeded or unknown chunks by seeking their length (+1 if odd length) to the next 4-letter chunkID.

0000: 464F524D 00016418 494C424D 424D4844    FORM..d.ILBMBMHD
0010: 00000014 01400190 00000000 06000100    .....@..........
0020: 00000A0B 01400190 43414D47 00000004    .....@..CAMG....
0030: 00000804 434D4150 00000030 001100EE    ....CMAP...0....
0040: EEEE0000 22000055 33333355 55550033    .... ..P000PPP.0
0050: 99885544 77777711 66EE2266 EE6688DD    ..P@ppp.`. `.`..
0060: AAAAAAAA 99EECCCC CCDDAAEE 424F4459    ............BODY
0070: 000163AC F8000F80 148A5544 2ABDEFFF    ..c.......UD*...  etc.

Interpretation:

      'F O R M' length  'I L B M''B M H D'<-start of BitMapHeader chunk
0000: 464F524D 00016418 494C424D 424D4844    FORM..d.ILBMBMHD

       length  WideHigh XorgYorg PlMkCoPd <- Planes Mask Compression Pad
0010: 00000014 01400190 00000000 06000100    .....@..........

                                             start of C-AMiGa
      TranAspt PagwPagh 'C A M G' length  <- View modes chunk
0020: 00000A0B 01400190 43414D47 00000004    .....@..CAMG....

      Viewmode 'C M A P' length  R g b R  <- Viewmode 800=HAM | 4=LACE
0030: 00000804 434D4150 00000030 001100EE    ....CMAP...0....

      g b R g  b R g b  R g b R  g b R g  <- Rgb's are for reg0 thru regN
0040: EEEE0000 22000055 33333355 55550033    .... ..P000PPP.0

      b R g b  R g b R  g b R g  b R g b
0050: 99885544 77777711 66EE2266 EE6688DD    ..P@ppp.`. `.`..

      R g b R  g b R g  b R g b 'B O D Y'
0060: AAAAAAAA 99EECCCC CCDDAAEE 424F4459    ............BODY

                                             Compacted
       length   start of body data        <- (Compression=1 above)
0070: 000163AC F8000F80 148A5544 2ABDEFFF    ..c.......UD*...
0080: FFBFF800 0F7FF7FC FF04F85A 77AD5DFE    ...........Zw.].  etc.

Notes on CAMG Viewmodes:  HIRES=0x8000  LACE=0x4  HAM=0x800  HALFBRITE=0x80

Interpreting ILBMs

ILBM is a fairly simple IFF FORM. All you really need to deal with to extract the image are the following chunks:

(Note - Also watch for AUTH Author chunks and (c) Copyright chunks
 and preserve any copyright information if you rewrite the ILBM)

   BMHD - info about the size, depth, compaction method
          (See interpreted hex dump above)

   CAMG - optional Amiga viewmodes chunk
          Most HAM and HALFBRITE ILBMs should have this chunk.  If no
          CAMG chunk is present, and image is 6 planes deep, assume
          HAM and you'll probably be right.  Some Amiga viewmodes
          flags are HIRES=0x8000, LACE=0x4, HAM=0x800, HALFBRITE=0x80.
        Note that new Amiga 2.0 ILBMs may have more complex 32-bit
        numbers (modeid) stored in the CAMG.  However, the bits
        described above should get you a compatible old viewmode.

   CMAP - RGB values for color registers 0 to n
          (each component left justified in a byte)
        If a deep ILBM (like 12 or 24 planes), there should be no CMAP
        and instead the BODY planes are interpreted as the bits of RGB
        in the order R0...Rn G0...Gn B0...Bn

   BODY - The pixel data, stored in an interleaved fashion as follows:
          (each line individually compacted if BMHD Compression = 1)
             plane 0 scan line 0
             plane 1 scan line 0
             plane 2 scan line 0
             ...
             plane n scan line 0
             plane 0 scan line 1
             plane 1 scan line 1
             etc.

Body Compression

The BODY contains pixel data for the image. Width, Height, and depth (Planes) is specified in the BMHD.

If the BMHD Compression byte is 0, then the scan line data is not compressed. If Compression=1, then each scan line is individually compressed as follows:

More than 2 bytes the same stored as BYTE code value n from -1 to -127 followed by byte to be repeated (-n) + 1 times. Varied bytes stored as BYTE code n from 0 to 127 followed by n+1 bytes of data.

The byte code -128 is a NOP.

Interpreting the Scan Line Data

If the ILBM is not HAM or HALFBRITE, then after parsing and uncompacting if necessary, you will have N planes of pixel data. Color register used for each pixel is specified by looking at each pixel thru the planes. I.e., if you have 5 planes, and the bit for a particular pixel is set in planes 0 and 3:

PLANE     4 3 2 1 0
PIXEL     0 1 0 0 1

then that pixel uses color register binary 01001 = 9

The RGB value for each color register is stored in the CMAP chunk of the ILBM, starting with register 0, with each register’s RGB value stored as one byte of R, one byte G, and one byte of B, with each component scaled to 8-bits. (ie. 4-bit Amiga R, G, and B components are each stored in the high nibble of a byte. The low nibble may also contain valid data if the color was stored with 8-bit-per-gun color resolution).

BUT - if the picture is HAM or HALFBRITE, it is interpreted differently.

Hopefully, if the picture is HAM or HALFBRITE, the package that saved it properly saved a CAMG chunk (look at a hex dump of your file with ACSII interpretation - you will see the chunks - they all start with a 4-ASCII- character chunk ID). If the picture is 6 planes deep and has no CAMG chunk, it is probably HAM. If you see a CAMG chunk, the "CAMG" is followed by the 32-bit chunk length, and then the 32-bit Amiga Viewmode flags.

HAM pics with a 16-bit CAMG will have the 0x800 bit set in CAMG ViewModes. HALBRITE pics will have the 0x80 bit set.

To transport a HAM or HALFBRITE picture to another machine, you must understand how HAM and HALFBRITE work on the Amiga.

How Amiga HAM mode works

Amiga HAM (Hold and Modify) mode lets the Amiga display all 4096 RGB values. In HAM mode, the bits in the two last planes describe an R G or B modification to the color of the previous pixel on the line to create the color of the current pixel. So a 6-plane HAM picture has 4 planes for specifying absolute color pixels giving up to 16 absolute colors which would be specified in the ILBM CMAP chunk. The bits in the last two planes are color modification bits which cause the Amiga, in HAM mode, to take the RGB value of the previous pixel (Hold and), substitute the 4 bits in planes 0-3 for the previous color’s R G or B component (Modify) and display the result for the current pixel. If the first pixel of a scan line is a modification pixel, it modifies the RGB value of the border color (register 0). The color modification bits in the last two planes (planes 4 and 5) are interpreted as follows:

   00 - no modification.  Use planes 0-3 as normal color register index
   10 - hold previous, replacing Blue component with bits from planes 0-3
   01 - hold previous, replacing Red component with bits from planes 0-3
   11 - hold previous. replacing Green component with bits from planes 0-3

How Amiga HALFBRITE mode works

This one is simpler. In HALFBRITE mode, the Amiga interprets the bit in the last plane as HALFBRITE modification. The bits in the other planes are treated as normal color register numbers (RGB values for each color register is specified in the CMAP chunk). If the bit in the last plane is set (1), then that pixel is displayed at half brightness. This can provide up to 64 absolute colors.

Other Notes

Amiga ILBMs images must be a even number of bytes wide. Smaller images (such as brushes) are padded to an even byte width.

ILBMs created with Electronic Arts IBM and Amiga “DPaintII” packages are compatible (though you may have to use a ’.lbm’ filename extension on an IBM). The ILBM graphic files may be transferred between the machines (or between the Amiga and IBM sides your Amiga if you have a CBM Bridgeboard card installed) and loaded into either package.