Sophie

Sophie

distrib > Mandriva > 9.0 > i586 > by-pkgid > d67485fb8ce60f8952179bbde3b5d022 > files > 84

libgdal0-devel-1.1.7-2mdk.i586.rpm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><meta name="robots" content="noindex">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>GDAL Driver Implementation Tutorial</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
</head><body bgcolor="#ffffff">
<!-- Generated by Doxygen 1.2.3-20001105 on Thu Mar 28 09:47:33 2002 -->
<center>
<a class="qindex" href="index.html">Main Page</a> &nbsp; <a class="qindex" href="hierarchy.html">Class Hierarchy</a> &nbsp; <a class="qindex" href="annotated.html">Compound List</a> &nbsp; <a class="qindex" href="files.html">File List</a> &nbsp; <a class="qindex" href="functions.html">Compound Members</a> &nbsp; <a class="qindex" href="globals.html">File Members</a> &nbsp; <a class="qindex" href="pages.html">Related Pages</a> &nbsp; </center>
<hr><a name="gdal_drivertut"><h2>GDAL Driver Implementation Tutorial</h2></a>

<p>
<center>

<p>
</center>

<p>
<h2>Overall Approach</h2>

<p>
In general new formats are added to GDAL by implementing format specific drivers as subclasses of <a class="el" href="class_GDALDataset.html">GDALDataset</a>, and band accessors as subclasses of <a class="el" href="class_GDALRasterBand.html">GDALRasterBand</a>. As well, a <a class="el" href="class_GDALDriver.html">GDALDriver</a> instance is created for the  format, and registered with the <a class="el" href="class_GDALDriverManager.html">GDALDriverManager</a>, to ensure that the system <em>knows</em> about the format.
<p>
This tutorial will start with implementing a simple read-only driver (based on the JDEM driver), and then proceed to utilizing the RawRasterBand helper class, implementing creatable and updatable formats, and some  esoteric issues.
<p>
It is strongly advised that the <a href="gdal_datamodel.html">GDAL Data Model
</a> description be reviewed and understood before attempting to implement a GDAL driver.
<p>
<h2>Contents</h2>

<p>
<ol>
 <li> <a href="#dataset">Implementing the Dataset</a> <li> <a href="#rasterband">Implementing the RasterBand</a> <li> <a href="#driver">The Driver</a> <li> <a href="#addingdriver">Adding Driver to GDAL Tree</a> <li> <a href="#georef">Adding Georeferencing</a> <li> <a href="#overviews">Overviews</a> <li> <a href="#creation">File Creation</a> <li> <a href="#raw">RawDataset/RawRasterBand Helper Classes</a> <li> <a href="#metadata">Metadata, and Other Exotic Extensions</a> </ol>

<p>
<h2><a name="dataset"></a>Implementing the Dataset</h2>

<p>
We will start showing minimal implementation of a read-only driver for the Japanese DEM format (<a href="jdemdataset.cpp.html">jdemdataset.cpp</a>).  First we declare a format specific dataset class, JDEMDataset in this case.
<p>
<div class="fragment"><pre><font class="keyword">class </font>JDEMDataset : <font class="keyword">public</font> <a class="code" href="class_GDALDataset.html">GDALDataset</a>
{
    FILE        *fp;
    GByte       abyHeader[1012];

  <font class="keyword">public</font>:
                ~JDEMDataset();
    
    <font class="keyword">static</font> <a class="code" href="class_GDALDataset.html">GDALDataset</a> *Open( GDALOpenInfo * );
};</div></pre>
<p>
In general we provide capabilities for a driver, by overriding the various virtual methods on the <a class="el" href="class_GDALDataset.html">GDALDataset</a> base class. However, the Open() method is special. This is not a virtual method on the baseclass, and we will need a freestanding function for this operation, so we declare it static.  Implementing it as a method in the JDEMDataset class is convenient because we have priveledged access to modify the contents of the database object.
<p>
The open method itself may look something like this:
<p>
<div class="fragment"><pre>
GDALDataset *JDEMDataset::Open( GDALOpenInfo * poOpenInfo )

{
/* -------------------------------------------------------------------- */
/*      Before trying JDEMOpen() we first verify that there is at       */
/*      least one "\n#keyword" type signature in the first chunk of     */
/*      the file.                                                       */
/* -------------------------------------------------------------------- */
    if( poOpenInfo-&gt;fp == NULL || poOpenInfo-&gt;nHeaderBytes &lt; 50 )
        return NULL;

    /* check if century values seem reasonable */
    if( (!EQUALN((char *)poOpenInfo-&gt;pabyHeader+11,"19",2)
          &amp;&amp; !EQUALN((char *)poOpenInfo-&gt;pabyHeader+11,"20",2))
        || (!EQUALN((char *)poOpenInfo-&gt;pabyHeader+15,"19",2)
             &amp;&amp; !EQUALN((char *)poOpenInfo-&gt;pabyHeader+15,"20",2))
        || (!EQUALN((char *)poOpenInfo-&gt;pabyHeader+19,"19",2)
             &amp;&amp; !EQUALN((char *)poOpenInfo-&gt;pabyHeader+19,"20",2)) )
    {
        return NULL;
    }
    
/* -------------------------------------------------------------------- */
/*      Create a corresponding GDALDataset.                             */
/* -------------------------------------------------------------------- */
    JDEMDataset         *poDS;

    poDS = new JDEMDataset();

    poDS-&gt;poDriver = poJDEMDriver;
    poDS-&gt;fp = poOpenInfo-&gt;fp;
    poOpenInfo-&gt;fp = NULL;
    
/* -------------------------------------------------------------------- */
/*      Read the header.                                                */
/* -------------------------------------------------------------------- */
    VSIFSeek( poDS-&gt;fp, 0, SEEK_SET );
    VSIFRead( poDS-&gt;abyHeader, 1, 1012, poDS-&gt;fp );

    poDS-&gt;nRasterXSize = JDEMGetField( (char *) poDS-&gt;abyHeader + 23, 3 );
    poDS-&gt;nRasterYSize = JDEMGetField( (char *) poDS-&gt;abyHeader + 26, 3 );

/* -------------------------------------------------------------------- */
/*      Create band information objects.                                */
/* -------------------------------------------------------------------- */
    poDS-&gt;nBands = 1;
    poDS-&gt;SetBand( 1, new JDEMRasterBand( poDS, 1 ));

    return( poDS );
}
</div></pre>
<p>
The first step in any database Open function is to verify that the file being passed is in fact of the type this driver is for. It is important to realize that each driver's Open function is called in turn till one succeeds. Drivers must quitly return NULL if the passed file is not of their format. They should only produce an error if the file does appear to be of their supported format, but is for some reason unsupported or corrupt.
<p>
The information on the file to be opened is passed in contained in a GDALOpenInfo object. The GDALOpenInfo includes the following public  data members:
<p>
<div class="fragment"><pre>    <font class="keywordtype">char</font>        *pszFilename;

    GDALAccess  eAccess; 

    GBool       bStatOK;
    VSIStatBuf  sStat;
    
    FILE        *fp;

    <font class="keywordtype">int</font>         nHeaderBytes;
    GByte       *pabyHeader;</div></pre>
<p>
The driver can inspect these to establish if the file is supported. If the pszFilename refers to an object in the file system, the <b>bStatOK</b> flag  will be set, and the <b>sStat</b> structure will contain normal stat()  information about the object (be it directory, file, device). If the object  is a regular readable file, the <b>fp</b> will be non-NULL, and can be used for reads on the file (please use the VSI stdio functions from  <a class="el" href="cpl_vsi_h.html">cpl_vsi.h</a>). As well, if the file was successfully opened, the first kilobyte or so is read in, and put in <b>pabyHeader</b>, with the exact size in  <b>nHeaderBytes</b>.
<p>
In this typical testing example it is verified that the file was successfully opened, that we have at least enough header information to perform our test, and that various parts of the header are as expected for this format. In this case, there are no <em>magic</em> numbers for JDEM format so we check various date fields to ensure they have reasonable century values. If the test fails, we quietly return NULL indicating this file isn't of our supported format.
<p>
<div class="fragment"><pre>    <font class="keywordflow">if</font>( poOpenInfo-&gt;fp == NULL || poOpenInfo-&gt;nHeaderBytes &lt; 50 )
        <font class="keywordflow">return</font> NULL;

    
    <font class="keywordflow">if</font>( (!EQUALN((<font class="keywordtype">char</font> *)poOpenInfo-&gt;pabyHeader+11,<font class="stringliteral">"19"</font>,2)
          &amp;&amp; !EQUALN((<font class="keywordtype">char</font> *)poOpenInfo-&gt;pabyHeader+11,<font class="stringliteral">"20"</font>,2))
        || (!EQUALN((<font class="keywordtype">char</font> *)poOpenInfo-&gt;pabyHeader+15,<font class="stringliteral">"19"</font>,2)
             &amp;&amp; !EQUALN((<font class="keywordtype">char</font> *)poOpenInfo-&gt;pabyHeader+15,<font class="stringliteral">"20"</font>,2))
        || (!EQUALN((<font class="keywordtype">char</font> *)poOpenInfo-&gt;pabyHeader+19,<font class="stringliteral">"19"</font>,2)
             &amp;&amp; !EQUALN((<font class="keywordtype">char</font> *)poOpenInfo-&gt;pabyHeader+19,<font class="stringliteral">"20"</font>,2)) )
    {
        <font class="keywordflow">return</font> NULL;
    }</div></pre>
<p>
It is important to make the <em>is this my format</em> test as stringent as possible. In this particular case the test is weak, and a file that happened to have 19s or 20s at a few locations could be erroneously recognised as JDEM format, causing it to not be handled properly.
<p>
Once we are satisfied that the file is of our format, we need to create an instance of the database class in which we will set various information of interest.
<p>
<div class="fragment"><pre>    JDEMDataset         *poDS;

    poDS = <font class="keyword">new</font> JDEMDataset();

    poDS-&gt;poDriver = poJDEMDriver;
    poDS-&gt;fp = poOpenInfo-&gt;fp;
    poOpenInfo-&gt;fp = NULL;</div></pre>
<p>
The setting of poDriver is required. We will see poJDEMDriver later when we discuss the driver instance object.
<p>
Generally at this point we would open the file, to acquire a file handle for the dataset; however, if read-only access is sufficient it is permitted to <b>assume ownership</b> of the FILE * from the GDALOpenInfo object.  Just ensure that it is set to NULL in the GDALOpenInfo to avoid having it get closed twice. It is also important to note that the state of the  FILE * adopted is indeterminate. Ensure that the current location is reset with <a class="el" href="cpl_vsi_h.html">VSIFSeek</a>() before assuming you can read from it. This is accomplished in the following statements which reset the file and read the header.
<p>
<div class="fragment"><pre>    VSIFSeek( poDS-&gt;fp, 0, SEEK_SET );
    VSIFRead( poDS-&gt;abyHeader, 1, 1012, poDS-&gt;fp );</div></pre>
<p>
Next the X and Y size are extracted from the header. The nRasterXSize and nRasterYSize are data fields inherited from the <a class="el" href="class_GDALDataset.html">GDALDataset</a> base class, and must be set by the Open() method.
<p>
<div class="fragment"><pre>    poDS-&gt;nRasterXSize = JDEMGetField( (<font class="keywordtype">char</font> *) poDS-&gt;abyHeader + 23, 3 );
    poDS-&gt;nRasterYSize = JDEMGetField( (<font class="keywordtype">char</font> *) poDS-&gt;abyHeader + 26, 3 );</div></pre>
<p>
Finally, all the bands related to this dataset must be attached using the SetBand() method. We will explore the JDEMRasterBand() class shortly.
<p>
<div class="fragment"><pre>    poDS-&gt;SetBand( 1, <font class="keyword">new</font> JDEMRasterBand( poDS, 1 ));

    <font class="keywordflow">return</font>( poDS );</div></pre>
<p>
<h2><a name="rasterband"></a>Implementing the RasterBand</h2>

<p>
Similar to the customized JDEMDataset class subclassed from <a class="el" href="class_GDALDataset.html">GDALDataset</a>,  we also need to declare and implement a customized JDEMRasterBand derived from <a class="el" href="class_GDALRasterBand.html">GDALRasterBand</a> for access to the band(s) of the JDEM file. For JDEMRasterBand the declaration looks like this:
<p>
<div class="fragment"><pre><font class="keyword">class </font>JDEMRasterBand : <font class="keyword">public</font> <a class="code" href="class_GDALRasterBand.html">GDALRasterBand</a>
{
  <font class="keyword">public</font>:
                JDEMRasterBand( JDEMDataset *, <font class="keywordtype">int</font> );
    <font class="keyword">virtual</font> CPLErr IReadBlock( <font class="keywordtype">int</font>, <font class="keywordtype">int</font>, <font class="keywordtype">void</font> * );
};</div></pre>
<p>
The constructor may have any signature, and is only called from the Open() method. Other virtual methods, such as IReadBlock() must be exactly  matched to the method signature in gdal_priv.h.
<p>
The constructor implementation looks like this:
<p>
<div class="fragment"><pre>JDEMRasterBand::JDEMRasterBand( JDEMDataset *poDS, <font class="keywordtype">int</font> nBand )<font class="keyword"></font>
<font class="keyword"></font>
<font class="keyword"></font>{
    this-&gt;poDS = poDS;
    this-&gt;nBand = nBand;
    
    eDataType = GDT_Float32;

    nBlockXSize = poDS-&gt;<a class="code" href="class_GDALDataset.html#a1">GetRasterXSize</a>();
    nBlockYSize = 1;
}</div></pre>
<p>
The following data members are inherited from <a class="el" href="class_GDALRasterBand.html">GDALRasterBand</a>, and should generally be set in the band constructor.
<p>
<ul>
 <li> <b>poDS</b>: Pointer to the parent <a class="el" href="class_GDALDataset.html">GDALDataset</a>.  <li> <b>nBand</b>: The band number within the dataset.  <li> <b>eDataType</b>: The data type of pixels in this band.  <li> <b>nBlockXSize</b>: The width of one block in this band.  <li> <b>nBlockYSize</b>: The height of one block in this band.  </ul>

<p>
The full set of possible GDALDataType values are declared in <a class="el" href="gdal_h.html">gdal.h</a>, and  include GDT_Byte, GDT_UInt16, GDT_Int16, and GDT_Float32. The block size is  used to establish a <em>natural</em> or efficient block size to access the data with. For tiled datasets this will be the size of a tile, while for most  other datasets it will be one scanline, as in this case.
<p>
Next we see the implementation of the code that actually reads the image data, IReadBlock().
<p>
<div class="fragment"><pre>CPLErr JDEMRasterBand::IReadBlock( <font class="keywordtype">int</font> nBlockXOff, <font class="keywordtype">int</font> nBlockYOff,
                                  <font class="keywordtype">void</font> * pImage )<font class="keyword"></font>
<font class="keyword"></font>
<font class="keyword"></font>{
    JDEMDataset *poGDS = (JDEMDataset *) poDS;
    <font class="keywordtype">char</font>        *pszRecord;
    <font class="keywordtype">int</font>         nRecordSize = nBlockXSize*5 + 9 + 2;
    <font class="keywordtype">int</font>         i;

    VSIFSeek( poGDS-&gt;fp, 1011 + nRecordSize*nBlockYOff, SEEK_SET );

    pszRecord = (<font class="keywordtype">char</font> *) <a class="code" href="cpl_conv_h.html#a3">CPLMalloc</a>(nRecordSize);
    VSIFRead( pszRecord, 1, nRecordSize, poGDS-&gt;fp );

    <font class="keywordflow">if</font>( !EQUALN((<font class="keywordtype">char</font> *) poGDS-&gt;abyHeader,pszRecord,6) )
    {
        CPLFree( pszRecord );

        <a class="code" href="cpl_error_h.html#a17">CPLError</a>( CE_Failure, CPLE_AppDefined, 
                  <font class="stringliteral">"JDEM Scanline corrupt.  Perhaps file was not transferred\n"</font>
                  <font class="stringliteral">"in binary mode?"</font> );
        <font class="keywordflow">return</font> CE_Failure;
    }
    
    <font class="keywordflow">if</font>( JDEMGetField( pszRecord + 6, 3 ) != nBlockYOff + 1 )
    {
        CPLFree( pszRecord );

        <a class="code" href="cpl_error_h.html#a17">CPLError</a>( CE_Failure, CPLE_AppDefined, 
                  <font class="stringliteral">"JDEM scanline out of order, JDEM driver does not\n"</font>
                  <font class="stringliteral">"currently support partial datasets."</font> );
        <font class="keywordflow">return</font> CE_Failure;
    }

    <font class="keywordflow">for</font>( i = 0; i &lt; nBlockXSize; i++ )
        ((<font class="keywordtype">float</font> *) pImage)[i] = JDEMGetField( pszRecord + 9 + 5 * i, 5) * 0.1;

    <font class="keywordflow">return</font> CE_None;
}</div></pre>
<p>
Key items to note are:
<p>
<ul>
 <li> It is typical to cast the GDALRasterBand::poDS member to the derived  type of the owning dataset. If your RasterBand class will need priveledged access to the owning dataset object, ensure it is declared as a friend (omitted above for brevity).
<p>
<li> If an error occurs, report it with <a class="el" href="cpl_error_h.html#a17">CPLError</a>(), and return CE_Failure.  Otherwise return CE_None.
<p>
<li> The pImage buffer should be filled with one block of data. The block is the size declared in nBlockXSize and nBlockYSize for the raster band. The type of the data within pImage should match the type declared in  eDataType in the raster band object.
<p>
<li> The nBlockXOff and nBlockYOff are block offsets, so with 128x128 tiled  datasets values of 1 and 1 would indicate the block going from (128,128) to  (255,255) should be loaded.
<p>
</ul>

<p>
<h2><a name="driver"></a>The Driver</h2>

<p>
While the JDEMDataset and JDEMRasterBand are now ready to use to read image data, it still isn't clear how the GDAL system knows about the new driver. This is accomplished via the <a class="el" href="class_GDALDriverManager.html">GDALDriverManager</a>. To register our format we implement a registration function:
<p>
<div class="fragment"><pre><font class="keyword">static</font> <a class="code" href="class_GDALDriver.html">GDALDriver</a>       *poJDEMDriver = NULL;

CPL_C_START
<font class="keywordtype">void</font>    GDALRegister_JDEM(<font class="keywordtype">void</font>);
CPL_C_END

...

void GDALRegister_JDEM()<font class="keyword"></font>
<font class="keyword"></font>
<font class="keyword"></font>{
    <a class="code" href="class_GDALDriver.html">GDALDriver</a>  *poDriver;

    <font class="keywordflow">if</font>( poJDEMDriver == NULL )
    {
        poJDEMDriver = poDriver = <font class="keyword">new</font> GDALDriver();
        
        poDriver-&gt;pszShortName = <font class="stringliteral">"JDEM"</font>;
        poDriver-&gt;pszLongName = <font class="stringliteral">"Japanese DEM (.mem)"</font>;
        poDriver-&gt;pszHelpTopic = <font class="stringliteral">"frmt_various.html#JDEM"</font>;
        
        poDriver-&gt;pfnOpen = JDEMDataset::Open;

        GetGDALDriverManager()-&gt;RegisterDriver( poDriver );
    }
}</div></pre>
<p>
The registration function will create an instance of a <a class="el" href="class_GDALDriver.html">GDALDriver</a> object when first called, and keep track of it in the local poJDEMDriver static pointer. The following fields in the <a class="el" href="class_GDALDriver.html">GDALDriver</a> can be set before  registering it with the GDALDriverManager().
<p>
<ul>
 <li> pszShortName: A short unique name for this format, often used to identity the driver in scripts and commandline programs. Normally 3-5 characters in length, and matching the prefix of the format classes. (manditory)
<p>
<li> pszLongName: A longer descriptive name for the file format, often indicating the typical extension for the format. (manditory)
<p>
<li> pszHelpTopic: The name of a help topic to display for this driver, if any. In this case JDEM format is contained within the various format  web page held in gdal/html. (optional)
<p>
<li> pfnOpen: The function to call to try opening files of this format.  (optional)
<p>
<li> pfnCreate: The function to call to create new updatable datasets of this format. (optional)
<p>
<li> pfnCreateCopy: The function to call to create a new dataset of this format copied from another source, but not necessary updatable. (optional)
<p>
<li> pfnDelete: The function to call to delete a dataset of this format. (optional)
<p>
</ul>

<p>
<h2><a name="addingdriver"></a>Adding Driver to GDAL Tree</h2>

<p>
Note that the GDALRegister_JDEM() method must be called by the higher level program in order to have access to the JDEM driver. Normal practice when writing new drivers is to:
<p>
<ol>
 <li> Add a driver directory under gdal/frmts, with the directory name the same as the pszShortName value.
<p>
<li> Add a GNUmakefile and makefile.vc in that directory modelled on those from other similar directories (ie. the jdem directory).
<p>
<li> Add the module with the dataset, and rasterband implementation.  Generally this is called &lt;short_name&gt;dataset.cpp, with all the GDAL specifc code in one file, though that is not required.
<p>
<li> Add the registration entry point declaration (ie. GDALRegister_JDEM()) to gdal/core/gdal_frmts.h.
<p>
<li> Add a call to the registration function to frmts/gdalallregister.c, protected by an appropriate ifdef.
<p>
<li> Add the format short name to the GDAL_FORMATS macro in  GDALmake.opt.in (and to GDALmake.opt).
<p>
<li> Add a format specific item to the EXTRAFLAGS macro in frmts/makefile.vc.  </ol>

<p>
Once this is all done, it should be possible to rebuild GDAL, and have the new format available in all the utilities. The gdalinfo utility can be used to test that opening and reporting on the format is working, and the gdal_translate utility can be used to test image reading.
<p>
<h2><a name="georef"></a>Adding Georeferencing</h2>

<p>
Now we will take the example a step forward, adding georeferencing support.  We add the following two virtual method overrides to JDEMDataset, taking care to exactly match the signature of the method on the GDALRasterDataset base class.
<p>
<div class="fragment"><pre>    CPLErr      GetGeoTransform( <font class="keywordtype">double</font> * padfTransform );
    <font class="keyword">const</font> <font class="keywordtype">char</font> *GetProjectionRef();</div></pre>
<p>
The implementation of GetGeoTransform() just copies the usual geotransform matrix into the supplied buffer. Note that GetGeoTransform() may be called alot, so it isn't generally wise to do alot of computation in it. In many cases the Open() will collect the geotransform, and this method will just copy it over. Also note that the geotransform return is based on an  anchor point at the top left corner of the top left pixel, not the center of pixel approach used in some packages.
<p>
<div class="fragment"><pre>CPLErr <a class="code" href="class_GDALDataset.html#a8">JDEMDataset::GetGeoTransform</a>( <font class="keywordtype">double</font> * padfTransform )<font class="keyword"></font>
<font class="keyword"></font>
<font class="keyword"></font>{
    <font class="keywordtype">double</font>      dfLLLat, dfLLLong, dfURLat, dfURLong;

    dfLLLat = JDEMGetAngle( (<font class="keywordtype">char</font> *) abyHeader + 29 );
    dfLLLong = JDEMGetAngle( (<font class="keywordtype">char</font> *) abyHeader + 36 );
    dfURLat = JDEMGetAngle( (<font class="keywordtype">char</font> *) abyHeader + 43 );
    dfURLong = JDEMGetAngle( (<font class="keywordtype">char</font> *) abyHeader + 50 );
    
    padfTransform[0] = dfLLLong;
    padfTransform[3] = dfURLat;
    padfTransform[1] = (dfURLong - dfLLLong) / <a class="code" href="class_GDALDataset.html#a1">GetRasterXSize</a>();
    padfTransform[2] = 0.0;
        
    padfTransform[4] = 0.0;
    padfTransform[5] = -1 * (dfURLat - dfLLLat) / <a class="code" href="class_GDALDataset.html#a2">GetRasterYSize</a>();


    <font class="keywordflow">return</font> CE_None;
}</div></pre>
<p>
The GetProjectionRef() method returns a pointer to an internal string  containing a coordinate system definition in OGC WKT format. In this case the coordinate system is fixed for all files of this format, but in more complex cases a definition may need to be composed on the fly, in which case it may be helpful to use the OGRSpatialReference class to help build the definition.
<p>
<div class="fragment"><pre><font class="keyword">const</font> <font class="keywordtype">char</font> *<a class="code" href="class_GDALDataset.html#a6">JDEMDataset::GetProjectionRef</a>()<font class="keyword"></font>
<font class="keyword"></font>
<font class="keyword"></font>{
    <font class="keywordflow">return</font>( <font class="stringliteral">"GEOGCS[\"Tokyo\",DATUM[\"Tokyo\",SPHEROID[\"Bessel 1841\","</font>
        <font class="stringliteral">"6377397.155,299.1528128,AUTHORITY[\"EPSG\",7004]],TOWGS84[-148,"</font>
        <font class="stringliteral">"507,685,0,0,0,0],AUTHORITY[\"EPSG\",6301]],PRIMEM[\"Greenwich\","</font>
        <font class="stringliteral">"0,AUTHORITY[\"EPSG\",8901]],UNIT[\"DMSH\",0.0174532925199433,"</font>
        <font class="stringliteral">"AUTHORITY[\"EPSG\",9108]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],"</font>
        <font class="stringliteral">"AUTHORITY[\"EPSG\",4301]]"</font> );
}</div></pre>
<p>
This completes explanation of the features of the JDEM driver. The full source for <a href="jdemdataset.cpp.html">jdemdataset.cpp</a> can be reviewed  as needed.
<p>
<h2><a name="overviews"></a>Overviews</h2>

<p>
GDAL allows file formats to make pre-built overviews available to applications via the <a class="el" href="class_GDALRasterBand.html#a29">GDALRasterBand::GetOverview</a>() and related methods. However,  implementing this is pretty involved, and goes beyond the scope of this  document for now. The GeoTIFF driver (gdal/frmts/gtiff/geotiff.cpp) and related source can be reviewed for an example of a file format implementing overview reporting and creation support.
<p>
Formats can also report that they have arbitrary overviews, by overriding the HasArbitraryOverviews() method on the <a class="el" href="class_GDALRasterBand.html">GDALRasterBand</a>, returning TRUE.  In this case the raster band object is expected to override the RasterIO() method itself, to implement efficient access to imagery with resampling.  This is also involved, and there are alot of requirements for correct implementation of the RasterIO() method. An example of this can be found in the ogdi and ecw formats.
<p>
However, by far the most common approach to implementing overviews is to  use the default support in GDAL for external overviews stored in TIFF files with the same name as the dataset, but the extension .ovr appended. In  order to enable reading and creation of this style of overviews it is necessary for the <a class="el" href="class_GDALDataset.html">GDALDataset</a> to initialize the oOvManager object within itself. This is typically accomplished with a call like the following near the end of the Open() method.
<p>
<div class="fragment"><pre>    poDS-&gt;oOvManager.Initialize( poDS, poOpenInfo-&gt;pszFilename );</div></pre>
<p>
This will enable default implementations for reading and creating overviews for the format. It is advised that this be enabled for all simple file system based formats unless there is a custom overview mechanism to be tied into.
<p>
<h2><a name="creation"></a>File Creation</h2>

<p>
There are two approaches to file creation. The first method is called the CreateCopy() method, and involves implementing a function that can write a file in the output format, pulling all imagery and other information needed from a source <a class="el" href="class_GDALDataset.html">GDALDataset</a>. The second method, the dynamic creation method, involves implementing a Create method to create the shell of the file, and then the application writes various information by calls to set methods.
<p>
The benefits of the first method are that that all the information is available at the point the output file is being created. This can be especially important when implementing file formats using external libraries which  require information like colormaps, and georeferencing information at the point the file is created. The other advantage of this method is that the CreateCopy() method can read some kinds of information, such as min/max,  scaling, description and GCPs for which there are no equivelent set methods.
<p>
The benefits of the second method are that applications can create an empty new file, and write results to it as they become available. A complete image of the desired data does not have to be available in advance.
<p>
For very important formats both methods may be implemented, otherwise do  whichever is simpler, or provides the required capabilities.
<p>
<h3>CreateCopy</h3>

<p>
The <a class="el" href="class_GDALDriver.html#a4">GDALDriver::CreateCopy</a>() method call is passed through directly, so  that method should be consulted for details of arguments. However, some  things to keep in mind are:
<p>
<ul>
 <li> If the bStrict flag is FALSE the driver should try to do something reasonable when it cannot exactly represent the source dataset, transforming data types on the fly, droping georeferencing and so forth.
<p>
<li> Implementing progress reporting correctly is somewhat involved. The return result of the progress function needs always to be checked for cancellation, and progress should be reported at reasonable intervals. The JPEGCreateCopy() method demonstrates good handling of the progress function.
<p>
<li> Special creation options should be documented in the online help. If the options take the format "NAME=VALUE" the papszOptions list can be manipulated with CPLFetchNameValue() as demonstrated in the handling of the QUALITY and PROGRESSIVE flags for JPEGCreateCopy().
<p>
<li> The returned <a class="el" href="class_GDALDataset.html">GDALDataset</a> handle can be in ReadOnly or Update mode.  Return it in Update mode if practical, otherwise in ReadOnly mode is fine.
<p>
</ul>

<p>
The full implementation of the CreateCopy function for JPEG (which is assigned to pfnCreateCopy in the <a class="el" href="class_GDALDriver.html">GDALDriver</a> object) is here.
<p>
<div class="fragment"><pre>
static GDALDataset *
JPEGCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, 
                int bStrict, char ** papszOptions, 
                GDALProgressFunc pfnProgress, void * pProgressData )

{
    int  nBands = poSrcDS-&gt;GetRasterCount();
    int  nXSize = poSrcDS-&gt;GetRasterXSize();
    int  nYSize = poSrcDS-&gt;GetRasterYSize();
    int  nQuality = 75;
    int  bProgressive = FALSE;

/* -------------------------------------------------------------------- */
/*      Some some rudimentary checks                                    */
/* -------------------------------------------------------------------- */
    if( nBands != 1 &amp;&amp; nBands != 3 )
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "JPEG driver doesn't support %d bands.  Must be 1 (grey) "
                  "or 3 (RGB) bands.\n", nBands );

        return NULL;
    }

    if( poSrcDS-&gt;GetRasterBand(1)-&gt;GetRasterDataType() != GDT_Byte &amp;&amp; bStrict )
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "JPEG driver doesn't support data type %s. "
                  "Only eight bit byte bands supported.\n", 
                  GDALGetDataTypeName( 
                      poSrcDS-&gt;GetRasterBand(1)-&gt;GetRasterDataType()) );

        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      What options has the user selected?                             */
/* -------------------------------------------------------------------- */
    if( CSLFetchNameValue(papszOptions,"QUALITY") != NULL )
    {
        nQuality = atoi(CSLFetchNameValue(papszOptions,"QUALITY"));
        if( nQuality &lt; 10 || nQuality &gt; 100 )
        {
            CPLError( CE_Failure, CPLE_IllegalArg,
                      "QUALITY=%s is not a legal value in the range 10-100.",
                      CSLFetchNameValue(papszOptions,"QUALITY") );
            return NULL;
        }
    }

    if( CSLFetchNameValue(papszOptions,"PROGRESSIVE") != NULL )
    {
        bProgressive = TRUE;
    }

/* -------------------------------------------------------------------- */
/*      Create the dataset.                                             */
/* -------------------------------------------------------------------- */
    FILE        *fpImage;

    fpImage = VSIFOpen( pszFilename, "wb" );
    if( fpImage == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed, 
                  "Unable to create jpeg file %s.\n", 
                  pszFilename );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Initialize JPG access to the file.                              */
/* -------------------------------------------------------------------- */
    struct jpeg_compress_struct sCInfo;
    struct jpeg_error_mgr sJErr;
    
    sCInfo.err = jpeg_std_error( &amp;sJErr );
    jpeg_create_compress( &amp;sCInfo );
    
    jpeg_stdio_dest( &amp;sCInfo, fpImage );
    
    sCInfo.image_width = nXSize;
    sCInfo.image_height = nYSize;
    sCInfo.input_components = nBands;

    if( nBands == 1 )
    {
        sCInfo.in_color_space = JCS_GRAYSCALE;
    }
    else
    {
        sCInfo.in_color_space = JCS_RGB;
    }

    jpeg_set_defaults( &amp;sCInfo );
    
    jpeg_set_quality( &amp;sCInfo, nQuality, TRUE );

    if( bProgressive )
        jpeg_simple_progression( &amp;sCInfo );

    jpeg_start_compress( &amp;sCInfo, TRUE );

/* -------------------------------------------------------------------- */
/*      Loop over image, copying image data.                            */
/* -------------------------------------------------------------------- */
    GByte       *pabyScanline;
    CPLErr      eErr;

    pabyScanline = (GByte *) CPLMalloc( nBands * nXSize );

    for( int iLine = 0; iLine &lt; nYSize; iLine++ )
    {
        JSAMPLE      *ppSamples;

        for( int iBand = 0; iBand &lt; nBands; iBand++ )
        {
            GDALRasterBand * poBand = poSrcDS-&gt;GetRasterBand( iBand+1 );
            eErr = poBand-&gt;RasterIO( GF_Read, 0, iLine, nXSize, 1, 
                                     pabyScanline + iBand, nXSize, 1, GDT_Byte,
                                     nBands, nBands * nXSize );
        }

        ppSamples = pabyScanline;
        jpeg_write_scanlines( &amp;sCInfo, &amp;ppSamples, 1 );
    }

    CPLFree( pabyScanline );

    jpeg_finish_compress( &amp;sCInfo );
    jpeg_destroy_compress( &amp;sCInfo );

    VSIFClose( fpImage );

    return (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly );
}
</div></pre>
<p>
<h3>Dynamic Creation</h3>

<p>
In the case of dynamic creation, there is no source dataset. Instead the size, number of bands, and pixel data type of the desired file is provided but other information (such as georeferencing, and imagery data) would be supplied later via other method calls on the resulting <a class="el" href="class_GDALDataset.html">GDALDataset</a>.
<p>
The following sample implement PCI .aux labelled raw raster creation. It follows a common approach of creating a blank, but valid file using non-GDAL calls, and then calling GDALOpen(,GA_Update) at the end to return a writable file handle. This avoids having to duplicate the various setup actions in the Open() function.
<p>
<div class="fragment"><pre>
GDALDataset *PAuxDataset::Create( const char * pszFilename,
                                  int nXSize, int nYSize, int nBands,
                                  GDALDataType eType,
                                  char ** /* papszParmList */ )

{
    char        *pszAuxFilename;

/* -------------------------------------------------------------------- */
/*      Verify input options.                                           */
/* -------------------------------------------------------------------- */
    if( eType != GDT_Byte &amp;&amp; eType != GDT_Float32 &amp;&amp; eType != GDT_UInt16
        &amp;&amp; eType != GDT_Int16 )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
              "Attempt to create PCI .Aux labelled dataset with an illegal\n"
              "data type (%s).\n",
              GDALGetDataTypeName(eType) );

        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Try to create the file.                                         */
/* -------------------------------------------------------------------- */
    FILE        *fp;

    fp = VSIFOpen( pszFilename, "w" );

    if( fp == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Attempt to create file `%s' failed.\n",
                  pszFilename );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Just write out a couple of bytes to establish the binary        */
/*      file, and then close it.                                        */
/* -------------------------------------------------------------------- */
    VSIFWrite( (void *) "\0\0", 2, 1, fp );
    VSIFClose( fp );

/* -------------------------------------------------------------------- */
/*      Create the aux filename.                                        */
/* -------------------------------------------------------------------- */
    pszAuxFilename = (char *) CPLMalloc(strlen(pszFilename)+5);
    strcpy( pszAuxFilename, pszFilename );;

    for( int i = strlen(pszAuxFilename)-1; i &gt; 0; i-- )
    {
        if( pszAuxFilename[i] == '.' )
        {
            pszAuxFilename[i] = '\0';
            break;
        }
    }

    strcat( pszAuxFilename, ".aux" );

/* -------------------------------------------------------------------- */
/*      Open the file.                                                  */
/* -------------------------------------------------------------------- */
    fp = VSIFOpen( pszAuxFilename, "wt" );
    if( fp == NULL )
    {
        CPLError( CE_Failure, CPLE_OpenFailed,
                  "Attempt to create file `%s' failed.\n",
                  pszAuxFilename );
        return NULL;
    }
    
/* -------------------------------------------------------------------- */
/*      We need to write out the original filename but without any      */
/*      path components in the AuxilaryTarget line.  Do so now.         */
/* -------------------------------------------------------------------- */
    int         iStart;

    iStart = strlen(pszFilename)-1;
    while( iStart &gt; 0 &amp;&amp; pszFilename[iStart-1] != '/'
           &amp;&amp; pszFilename[iStart-1] != '\\' )
        iStart--;

    VSIFPrintf( fp, "AuxilaryTarget: %s\n", pszFilename + iStart );

/* -------------------------------------------------------------------- */
/*      Write out the raw definition for the dataset as a whole.        */
/* -------------------------------------------------------------------- */
    VSIFPrintf( fp, "RawDefinition: %d %d %d\n",
                nXSize, nYSize, nBands );

/* -------------------------------------------------------------------- */
/*      Write out a definition for each band.  We always write band     */
/*      sequential files for now as these are pretty efficiently        */
/*      handled by GDAL.                                                */
/* -------------------------------------------------------------------- */
    int         nImgOffset = 0;
    
    for( int iBand = 0; iBand &lt; nBands; iBand++ )
    {
        const char * pszTypeName;
        int          nPixelOffset;
        int          nLineOffset;

        nPixelOffset = GDALGetDataTypeSize(eType)/8;
        nLineOffset = nXSize * nPixelOffset;

        if( eType == GDT_Float32 )
            pszTypeName = "32R";
        else if( eType == GDT_Int16 )
            pszTypeName = "16S";
        else if( eType == GDT_UInt16 )
            pszTypeName = "16U";
        else
            pszTypeName = "8U";

        VSIFPrintf( fp, "ChanDefinition-%d: %s %d %d %d %s\n",
                    iBand+1, pszTypeName,
                    nImgOffset, nPixelOffset, nLineOffset,



                    "Unswapped"

                    );

        nImgOffset += nYSize * nLineOffset;
    }

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
    VSIFClose( fp );

    return (GDALDataset *) GDALOpen( pszFilename, GA_Update );
}
</div></pre>
<p>
File formats supporting dynamic creation, or even just update-in-place access also need to implement an IWriteBlock() method on the raster band class. It has semantics similar to IReadBlock().  As well, for various esoteric reasons, it is critical that a FlushCache() method be implemented in the raster band destructor. This is to ensure that any write cache blocks for the band be flushed out before the destructor is called.
<p>
<h2><a name="raw"></a>RawDataset/RawRasterBand Helper Classes</h2>

<p>
Many file formats have the actual imagery data stored in a regular, binary, scanline oriented format. Rather than re-implement the access  semantics for this for each formats, there are provided RawDataset and RawRasterBand classes declared in gdal/frmts/raw that can be utilized to implement efficient and convenient access.
<p>
In these cases the format specific band class may not be required, or if required it can be derived from RawRasterBand. The dataset class should be derived from RawDataset.
<p>
The Open() method for the dataset then instantiates raster bands passing all the layout information to the constructor. For instance, the PNM driver uses the following calls to create it's raster bands.
<p>
<div class="fragment"><pre>    <font class="keywordflow">if</font>( poOpenInfo-&gt;pabyHeader[1] == <font class="charliteral">'5'</font> )
    {
        poDS-&gt;SetBand( 
            1, <font class="keyword">new</font> RawRasterBand( poDS, 1, poDS-&gt;fpImage,
                                  iIn, 1, nWidth, GDT_Byte, TRUE ));
    }
    <font class="keywordflow">else</font> 
    {
        poDS-&gt;SetBand( 
            1, <font class="keyword">new</font> RawRasterBand( poDS, 1, poDS-&gt;fpImage,
                                  iIn, 3, nWidth*3, GDT_Byte, TRUE ));
        poDS-&gt;SetBand( 
            2, <font class="keyword">new</font> RawRasterBand( poDS, 2, poDS-&gt;fpImage,
                                  iIn+1, 3, nWidth*3, GDT_Byte, TRUE ));
        poDS-&gt;SetBand( 
            3, <font class="keyword">new</font> RawRasterBand( poDS, 3, poDS-&gt;fpImage,
                                  iIn+2, 3, nWidth*3, GDT_Byte, TRUE ));
    }</div></pre>
<p>
The RawRasterBand takes the following arguments.
<p>
<ul>
 <li> <b>poDS</b>: The <a class="el" href="class_GDALDataset.html">GDALDataset</a> this band will be a child of. This dataset must be of a class derived from RawRasterDataset.  <li> <b>nBand</b>: The band it is on that dataset, 1 based.  <li> <b>fpRaw</b>: The FILE * handle to the file containing the raster data. <li> <b>nImgOffset</b>: The byte offset to the first pixel of raster data for  the first scanline.  <li> <b>nPixelOffset</b>: The byte offset from the start of one pixel to the  start of the next within the scanline.  <li> <b>nLineOffset</b>: The byte offset from the start of one scanline to the start of the next.  <li> <b>eDataType</b>: The GDALDataType code for the type of the data on disk. <li> <b>bNativeOrder</b>: FALSE if the data is not in the same endianness as the machine GDAL is running on. The data will be automatically byte swapped. </ul>

<p>
Simple file formats utilizing the Raw services are normally placed all within one file in the gdal/frmts/raw directory. There are numerous examples there of format implementation.
<p>

<p>
<h2><a name="metadata"></a>Metadata, and Other Exotic Extensions</h2>

<p>
There are various other items in the GDAL data model, for which virtual  methods exist on the <a class="el" href="class_GDALDataset.html">GDALDataset</a> and <a class="el" href="class_GDALRasterBand.html">GDALRasterBand</a>. They include:
<p>
<ul>
 <li> <b>Metadata</b>: Name/value text values about a dataset or band. The GDALMajorObject (base class for <a class="el" href="class_GDALRasterBand.html">GDALRasterBand</a> and <a class="el" href="class_GDALDataset.html">GDALDataset</a>) has builtin support for holding metadata, so for read access it only needs to be set with calls to SetMetadataItem() during the Open(). The SAR_CEOS  (frmts/ceos2/sar_ceosdataset.cpp) and GeoTIFF drivers are examples of drivers implementing readable metadata.
<p>
<li> <b>ColorTables</b>: GDT_Byte raster bands can have color tables associated with them. The frmts/png/pngdataset.cpp driver contains an example of a format that supports colortables.
<p>
<li> <b>ColorInterpretation</b>: The PNG driver contains an example of a driver that returns an indication of whether a band should be treated as a Red, Green, Blue, Alpha or Greyscale band.
<p>
<li> <b>GCPs</b>: GDALDatasets can have a set of ground control points  associated with them (as opposed to an explicit affine transform returned by GetGeotransform()) relating the raster to georeferenced coordinates. The MFF2 (gdal/frmts/raw/hkvdataset.cpp) format is a simple example of a format supporting GCPs.
<p>
<li> <b>NoDataValue</b>: Bands with known "nodata" values can implement the GetNoDataValue() method. See the PAux (frmts/raw/pauxdataset.cpp) for an example of this.
<p>
<li> <b>Category Names</b>: Classified images with names for each class can return them using the GetCategoryNames() method though no formats currently implement this.
<p>
</ul>

<p>
<hr><address><small>Generated at Thu Mar 28 09:47:33 2002 for GDAL by
<a href="http://www.stack.nl/~dimitri/doxygen/index.html">
<img src="doxygen.gif" alt="doxygen" align="middle" border=0 
width=110 height=53></a>1.2.3-20001105 written by <a href="mailto:dimitri@stack.nl">Dimitri van Heesch</a>,
 &copy;&nbsp;1997-2000</small></address>
</body>
</html>