opusfile.h 112 KB
Newer Older
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/********************************************************************
 *                                                                  *
 * THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
 *                                                                  *
 * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012           *
 * by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
 *                                                                  *
 ********************************************************************

 function: stdio-based convenience library for opening/seeking/decoding
 last mod: $Id: vorbisfile.h 17182 2010-04-29 03:48:32Z xiphmont $

 ********************************************************************/
17
18
#if !defined(_opusfile_h)
# define _opusfile_h (1)
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
19

20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**\mainpage
   \section Introduction

   This is the documentation for the <tt>libopusfile</tt> C API.

   The <tt>libopusfile</tt> package provides a convenient high-level API for
    decoding and basic manipulation of all Ogg Opus audio streams.
   <tt>libopusfile</tt> is implemented as a layer on top of Xiph.Org's
    reference
    <tt><a href="https://www.xiph.org/ogg/doc/libogg/reference.html">libogg</a></tt>
    and
    <tt><a href="https://mf4.xiph.org/jenkins/view/opus/job/opus/ws/doc/html/index.html">libopus</a></tt>
    libraries.

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
34
   <tt>libopusfile</tt> provides several sets of built-in routines for
35
36
37
38
    file/stream access, and may also use custom stream I/O routines provided by
    the embedded environment.
   There are built-in I/O routines provided for ANSI-compliant
    <code>stdio</code> (<code>FILE *</code>), memory buffers, and URLs
39
    (including <file:> URLs, plus optionally <http:> and <https:> URLs).
40
41
42
43
44
45
46
47
48
49
50
51

   \section Organization

   The main API is divided into several sections:
   - \ref stream_open_close
   - \ref stream_info
   - \ref stream_decoding
   - \ref stream_seeking

   Several additional sections are not tied to the main API.
   - \ref stream_callbacks
   - \ref header_info
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
   - \ref error_codes

   \section Overview

   The <tt>libopusfile</tt> API always decodes files to 48&nbsp;kHz.
   The original sample rate is not preserved by the lossy compression, though
    it is stored in the header to allow you to resample to it after decoding
    (the <tt>libopusfile</tt> API does not currently provide a resampler,
    but the
    <a href="http://www.speex.org/docs/manual/speex-manual/node7.html#SECTION00760000000000000000">the
    Speex resampler</a> is a good choice if you need one).
   In general, if you are playing back the audio, you should leave it at
    48&nbsp;kHz, provided your audio hardware supports it.
   When decoding to a file, it may be worth resampling back to the original
    sample rate, so as not to surprise users who might not expect the sample
    rate to change after encoding to Opus and decoding.

   Opus files can contain anywhere from 1 to 255 channels of audio.
   The channel mappings for up to 8 channels are the same as the
    <a href="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">Vorbis
    mappings</a>.
   A special stereo API can convert everything to 2 channels, making it simple
74
    to support multichannel files in an application which only has stereo
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    output.
   Although the <tt>libopusfile</tt> ABI provides support for the theoretical
    maximum number of channels, the current implementation does not support
    files with more than 8 channels, as they do not have well-defined channel
    mappings.

   Like all Ogg files, Opus files may be "chained".
   That is, multiple Opus files may be combined into a single, longer file just
    by concatenating the original files.
   This is commonly done in internet radio streaming, as it allows the title
    and artist to be updated each time the song changes, since each link in the
    chain includes its own set of metadata.

   <tt>libopusfile</tt> fully supports chained files.
   It will decode the first Opus stream found in each link of a chained file
    (ignoring any other streams that might be concurrently multiplexed with it,
    such as a video stream).

93
94
95
96
   The channel count can also change between links.
   If your application is not prepared to deal with this, it can use the stereo
    API to ensure the audio from all links will always get decoded into a
    common format.
97
98
99
100
101
   Since <tt>libopusfile</tt> always decodes to 48&nbsp;kHz, you do not have to
    worry about the sample rate changing between links (as was possible with
    Vorbis).
   This makes application support for chained files with <tt>libopusfile</tt>
    very easy.*/
102

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
103
104
105
106
# if defined(__cplusplus)
extern "C" {
# endif

107
# include <stdarg.h>
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
108
109
# include <stdio.h>
# include <ogg/ogg.h>
110
# include <opus_multistream.h>
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
111

112
113
/**@cond PRIVATE*/

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*Enable special features for gcc and gcc-compatible compilers.*/
# if !defined(OP_GNUC_PREREQ)
#  if defined(__GNUC__)&&defined(__GNUC_MINOR__)
#   define OP_GNUC_PREREQ(_maj,_min) \
 ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
#  else
#   define OP_GNUC_PREREQ(_maj,_min) 0
#  endif
# endif

# if OP_GNUC_PREREQ(4,0)
#  pragma GCC visibility push(default)
# endif

128
129
130
131
132
133
typedef struct OpusHead          OpusHead;
typedef struct OpusTags          OpusTags;
typedef struct OpusPictureTag    OpusPictureTag;
typedef struct OpusServerInfo    OpusServerInfo;
typedef struct OpusFileCallbacks OpusFileCallbacks;
typedef struct OggOpusFile       OggOpusFile;
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
134
135
136
137
138
139
140
141
142
143
144
145
146

/*Warning attributes for libopusfile functions.*/
# if OP_GNUC_PREREQ(3,4)
#  define OP_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
# else
#  define OP_WARN_UNUSED_RESULT
# endif
# if OP_GNUC_PREREQ(3,4)
#  define OP_ARG_NONNULL(_x) __attribute__((__nonnull__(_x)))
# else
#  define OP_ARG_NONNULL(_x)
# endif

147
148
/**@endcond*/

149
150
151
152
153
154
155
156
157
/**\defgroup error_codes Error Codes*/
/*@{*/
/**\name List of possible error codes
   Many of the functions in this library return a negative error code when a
    function fails.
   This list provides a brief explanation of the common errors.
   See each individual function for more details on what a specific error code
    means in that context.*/
/*@{*/
158

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/**A request did not succeed.*/
#define OP_FALSE         (-1)
/*Currently not used externally.*/
#define OP_EOF           (-2)
/**There was a hole in the page sequence numbers (e.g., a page was corrupt or
    missing).*/
#define OP_HOLE          (-3)
/**An underlying read, seek, or tell operation failed when it should have
    succeeded.*/
#define OP_EREAD         (-128)
/**A <code>NULL</code> pointer was passed where one was unexpected, or an
    internal memory allocation failed, or an internal library error was
    encountered.*/
#define OP_EFAULT        (-129)
/**The stream used a feature that is not implemented, such as an unsupported
    channel family.*/
#define OP_EIMPL         (-130)
/**One or more parameters to a function were invalid.*/
#define OP_EINVAL        (-131)
178
/**A purported Ogg Opus stream did not begin with an Ogg page, a purported
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
179
    header packet did not start with one of the required strings, "OpusHead" or
180
181
    "OpusTags", or a link in a chained file was encountered that did not
    contain any logical Opus streams.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#define OP_ENOTFORMAT    (-132)
/**A required header packet was not properly formatted, contained illegal
    values, or was missing altogether.*/
#define OP_EBADHEADER    (-133)
/**The ID header contained an unrecognized version number.*/
#define OP_EVERSION      (-134)
/*Currently not used at all.*/
#define OP_ENOTAUDIO     (-135)
/**An audio packet failed to decode properly.
   This is usually caused by a multistream Ogg packet where the durations of
    the individual Opus packets contained in it are not all the same.*/
#define OP_EBADPACKET    (-136)
/**We failed to find data we had seen before, or the bitstream structure was
    sufficiently malformed that seeking to the target destination was
    impossible.*/
#define OP_EBADLINK      (-137)
/**An operation that requires seeking was requested on an unseekable stream.*/
#define OP_ENOSEEK       (-138)
/**The first or last granule position of a link failed basic validity checks.*/
#define OP_EBADTIMESTAMP (-139)
202

203
204
205
206
207
/*@}*/
/*@}*/

/**\defgroup header_info Header Information*/
/*@{*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

/**The maximum number of channels in an Ogg Opus stream.*/
#define OPUS_CHANNEL_COUNT_MAX (255)

/**Ogg Opus bitstream information.
   This contains the basic playback parameters for a stream, and corresponds to
    the initial ID header packet of an Ogg Opus stream.*/
struct OpusHead{
  /**The Ogg Opus format version, in the range 0...255.
     The top 4 bits represent a "major" version, and the bottom four bits
      represent backwards-compatible "minor" revisions.
     The current specification describes version 1.
     This library will recognize versions up through 15 as backwards compatible
      with the current specification.
     An earlier draft of the specification described a version 0, but the only
      difference between version 1 and version 0 is that version 0 did
      not specify the semantics for handling the version field.*/
  int           version;
  /**The number of channels, in the range 1...255.*/
  int           channel_count;
  /**The number of samples that should be discarded from the beginning of the
      stream.*/
  unsigned      pre_skip;
  /**The sampling rate of the original input.
     All Opus audio is coded at 48 kHz, and should also be decoded at 48 kHz
      for playback (unless the target hardware does not support this sampling
      rate).
     However, this field may be used to resample the audio back to the original
      sampling rate, for example, when saving the output to a file.*/
  opus_uint32   input_sample_rate;
  /**The gain to apply to the decoded output, in dB, as a Q8 value in the range
      -32768...32767.
240
241
242
     The <tt>libopusfile</tt> API will automatically apply this gain to the
      decoded output before returning it, scaling it by
      <code>pow(10,output_gain/(20.0*256))</code>.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
  int           output_gain;
  /**The channel mapping family, in the range 0...255.
     Channel mapping family 0 covers mono or stereo in a single stream.
     Channel mapping family 1 covers 1 to 8 channels in one or more streams,
      using the Vorbis speaker assignments.
     Channel mapping family 255 covers 1 to 255 channels in one or more
      streams, but without any defined speaker assignment.*/
  int           mapping_family;
  /**The number of Opus streams in each Ogg packet, in the range 1...255.*/
  int           stream_count;
  /**The number of coupled Opus streams in each Ogg packet, in the range
      0...127.
     This must satisfy <code>0 <= coupled_count <= stream_count</code> and
      <code>coupled_count + stream_count <= 255</code>.
     The coupled streams appear first, before all uncoupled streams, in an Ogg
      Opus packet.*/
  int           coupled_count;
  /**The mapping from coded stream channels to output channels.
     Let <code>index=mapping[k]</code> be the value for channel <code>k</code>.
     If <code>index<2*coupled_count</code>, then it refers to the left channel
      from stream <code>(index/2)</code> if even, and the right channel from
      stream <code>(index/2)</code> if odd.
     Otherwise, it refers to the output of the uncoupled stream
      <code>(index-coupled_count)</code>.*/
  unsigned char mapping[OPUS_CHANNEL_COUNT_MAX];
};

/**The metadata from an Ogg Opus stream.

   This structure holds the in-stream metadata corresponding to the 'comment'
    header packet of an Ogg Opus stream.
   The comment header is meant to be used much like someone jotting a quick
    note on the label of a CD.
   It should be a short, to the point text note that can be more than a couple
    words, but not more than a short paragraph.

   The metadata is stored as a series of (tag, value) pairs, in length-encoded
    string vectors, using the same format as Vorbis (without the final "framing
    bit"), Theora, and Speex, except for the packet header.
   The first occurrence of the '=' character delimits the tag and value.
   A particular tag may occur more than once, and order is significant.
   The character set encoding for the strings is always UTF-8, but the tag
    names are limited to ASCII, and treated as case-insensitive.
   See <a href="http://www.xiph.org/vorbis/doc/v-comment.html">the Vorbis
    comment header specification</a> for details.

289
   In filling in this structure, <tt>libopusfile</tt> will null-terminate the
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    #user_comments strings for safety.
   However, the bitstream format itself treats them as 8-bit clean vectors,
    possibly containing NUL characters, so the #comment_lengths array should be
    treated as their authoritative length.

   This structure is binary and source-compatible with a
    <code>vorbis_comment</code>, and pointers to it may be freely cast to
    <code>vorbis_comment</code> pointers, and vice versa.
   It is provided as a separate type to avoid introducing a compile-time
    dependency on the libvorbis headers.*/
struct OpusTags{
  /**The array of comment string vectors.*/
  char **user_comments;
  /**An array of the corresponding length of each vector, in bytes.*/
  int   *comment_lengths;
  /**The total number of comment streams.*/
  int    comments;
  /**The null-terminated vendor string.
     This identifies the software used to encode the stream.*/
  char  *vendor;
};

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/**\name Picture tag image formats*/
/*@{*/

/**The MIME type was not recognized, or the image data did not match the
    declared MIME type.*/
#define OP_PIC_FORMAT_UNKNOWN (-1)
/**The MIME type indicates the image data is really a URL.*/
#define OP_PIC_FORMAT_URL     (0)
/**The image is a JPEG.*/
#define OP_PIC_FORMAT_JPEG    (1)
/**The image is a PNG.*/
#define OP_PIC_FORMAT_PNG     (2)
/**The image is a GIF.*/
#define OP_PIC_FORMAT_GIF     (3)

/*@}*/

/**The contents of a METADATA_BLOCK_PICTURE tag.*/
struct OpusPictureTag{
  /**The picture type according to the ID3v2 APIC frame:
     <ol start="0">
     <li>Other</li>
     <li>32x32 pixels 'file icon' (PNG only)</li>
     <li>Other file icon</li>
     <li>Cover (front)</li>
     <li>Cover (back)</li>
     <li>Leaflet page</li>
     <li>Media (e.g. label side of CD)</li>
     <li>Lead artist/lead performer/soloist</li>
     <li>Artist/performer</li>
     <li>Conductor</li>
     <li>Band/Orchestra</li>
     <li>Composer</li>
     <li>Lyricist/text writer</li>
     <li>Recording Location</li>
     <li>During recording</li>
     <li>During performance</li>
     <li>Movie/video screen capture</li>
     <li>A bright colored fish</li>
     <li>Illustration</li>
     <li>Band/artist logotype</li>
     <li>Publisher/Studio logotype</li>
     </ol>
     Others are reserved and should not be used.
     There may only be one each of picture type 1 and 2 in a file.*/
  opus_int32     type;
  /**The MIME type of the picture, in printable ASCII characters 0x20-0x7E.
     The MIME type may also be <code>"-->"</code> to signify that the data part
      is a URL pointing to the picture instead of the picture data itself.
     In this case, a terminating NUL is appended to the URL string in #data,
      but #data_length is set to the length of the string excluding that
      terminating NUL.*/
  char          *mime_type;
  /**The description of the picture, in UTF-8.*/
  char          *description;
  /**The width of the picture in pixels.*/
  opus_uint32    width;
  /**The height of the picture in pixels.*/
  opus_uint32    height;
  /**The color depth of the picture in bits-per-pixel (<em>not</em>
      bits-per-channel).*/
  opus_uint32    depth;
  /**For indexed-color pictures (e.g., GIF), the number of colors used, or 0
      for non-indexed pictures.*/
  opus_uint32    colors;
  /**The length of the picture data in bytes.*/
  opus_uint32    data_length;
  /**The binary picture data.*/
  unsigned char *data;
  /**The format of the picture data, if known.
     One of
     <ul>
     <li>#OP_PIC_FORMAT_UNKNOWN,</li>
     <li>#OP_PIC_FORMAT_URL,</li>
     <li>#OP_PIC_FORMAT_JPEG,</li>
387
388
389
     <li>#OP_PIC_FORMAT_PNG, or</li>
     <li>#OP_PIC_FORMAT_GIF.</li>
     </ul>*/
390
391
392
  int            format;
};

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
393
/**\name Functions for manipulating header data
394

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
395
   These functions manipulate the #OpusHead and #OpusTags structures,
396
397
398
399
    which describe the audio parameters and tag-value metadata, respectively.
   These can be used to query the headers returned by <tt>libopusfile</tt>, or
    to parse Opus headers from sources other than an Ogg Opus stream, provided
    they use the same format.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
400
/*@{*/
401

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**Parses the contents of the ID header packet of an Ogg Opus stream.
   \param[out] _head Returns the contents of the parsed packet.
                     The contents of this structure are untouched on error.
                     This may be <code>NULL</code> to merely test the header
                      for validity.
   \param[in]  _data The contents of the ID header packet.
   \param      _len  The number of bytes of data in the ID header packet.
   \return 0 on success or a negative value on error.
   \retval #OP_ENOTFORMAT If the data does not start with the "OpusHead"
                           string.
   \retval #OP_EVERSION   If the version field signaled a version this library
                           does not know how to parse.
   \retval #OP_EIMPL      If the channel mapping family was 255, which general
                           purpose players should not attempt to play.
   \retval #OP_EBADHEADER If the contents of the packet otherwise violate the
                           Ogg Opus specification:
                          <ul>
                           <li>Insufficient data,</li>
                           <li>Too much data for the known minor versions,</li>
                           <li>An unrecognized channel mapping family,</li>
                           <li>Zero channels or too many channels,</li>
                           <li>Zero coded streams,</li>
                           <li>Too many coupled streams, or</li>
                           <li>An invalid channel mapping index.</li>
                          </ul>*/
OP_WARN_UNUSED_RESULT int opus_head_parse(OpusHead *_head,
 const unsigned char *_data,size_t _len) OP_ARG_NONNULL(2);
429

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**Converts a granule position to a sample offset for a given Ogg Opus stream.
   The sample offset is simply <code>_gp-_head->pre_skip</code>.
   Granule position values smaller than OpusHead#pre_skip correspond to audio
    that should never be played, and thus have no associated sample offset.
   This function returns -1 for such values.
   This function also correctly handles extremely large granule positions,
    which may have wrapped around to a negative number when stored in a signed
    ogg_int64_t value.
   \param _head The #OpusHead information from the ID header of the stream.
   \param _gp   The granule position to convert.
   \return The sample offset associated with the given granule position
            (counting at a 48 kHz sampling rate), or the special value -1 on
            error (i.e., the granule position was smaller than the pre-skip
            amount).*/
ogg_int64_t opus_granule_sample(const OpusHead *_head,ogg_int64_t _gp)
 OP_ARG_NONNULL(1);

/**Parses the contents of the 'comment' header packet of an Ogg Opus stream.
   \param[out] _tags An uninitialized #OpusTags structure.
                     This returns the contents of the parsed packet.
                     The contents of this structure are untouched on error.
                     This may be <code>NULL</code> to merely test the header
                      for validity.
   \param[in]  _data The contents of the 'comment' header packet.
   \param      _len  The number of bytes of data in the 'info' header packet.
455
   \retval 0              Success.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
456
457
458
459
460
461
462
   \retval #OP_ENOTFORMAT If the data does not start with the "OpusTags"
                           string.
   \retval #OP_EBADHEADER If the contents of the packet otherwise violate the
                           Ogg Opus specification.
   \retval #OP_EFAULT     If there wasn't enough memory to store the tags.*/
OP_WARN_UNUSED_RESULT int opus_tags_parse(OpusTags *_tags,
 const unsigned char *_data,size_t _len) OP_ARG_NONNULL(2);
463

464
465
466
467
468
469
470
471
472
/**Performs a deep copy of an #OpusTags structure.
   \param _dst The #OpusTags structure to copy into.
               If this function fails, the contents of this structure remain
                untouched.
   \param _src The #OpusTags structure to copy from.
   \retval 0          Success.
   \retval #OP_EFAULT If there wasn't enough memory to copy the tags.*/
int opus_tags_copy(OpusTags *_dst,const OpusTags *_src) OP_ARG_NONNULL(1);

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
473
474
475
476
477
/**Initializes an #OpusTags structure.
   This should be called on a freshly allocated #OpusTags structure before
    attempting to use it.
   \param _tags The #OpusTags structure to initialize.*/
void opus_tags_init(OpusTags *_tags) OP_ARG_NONNULL(1);
478

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
479
480
481
482
483
/**Add a (tag, value) pair to an initialized #OpusTags structure.
   \note Neither opus_tags_add() nor opus_tags_add_comment() support values
    containing embedded NULs, although the bitstream format does support them.
   To add such tags, you will need to manipulate the #OpusTags structure
    directly.
484
485
486
487
   \param _tags  The #OpusTags structure to add the (tag, value) pair to.
   \param _tag   A NUL-terminated, case-insensitive, ASCII string containing
                  the tag to add (without an '=' character).
   \param _value A NUL-terminated UTF-8 containing the corresponding value.
488
   \return 0 on success, or a negative value on failure.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
489
   \retval #OP_EFAULT An internal memory allocation failed.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
490
491
int opus_tags_add(OpusTags *_tags,const char *_tag,const char *_value)
 OP_ARG_NONNULL(1) OP_ARG_NONNULL(2) OP_ARG_NONNULL(3);
492

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
493
494
495
496
497
498
499
/**Add a comment to an initialized #OpusTags structure.
   \note Neither opus_tags_add_comment() nor opus_tags_add() support comments
    containing embedded NULs, although the bitstream format does support them.
   To add such tags, you will need to manipulate the #OpusTags structure
    directly.
   \param _tags    The #OpusTags structure to add the comment to.
   \param _comment A NUL-terminated UTF-8 string containing the comment in
500
501
                    "TAG=value" form.
   \return 0 on success, or a negative value on failure.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
502
   \retval #OP_EFAULT An internal memory allocation failed.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
503
504
int opus_tags_add_comment(OpusTags *_tags,const char *_comment)
 OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);
505

506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/**Replace the binary suffix data at the end of the packet (if any).
   \param _tags An initialized #OpusTags structure.
   \param _data A buffer of binary data to append after the encoded user
                 comments.
                The least significant bit of the first byte of this data must
                 be set (to ensure the data is preserved by other editors).
   \param _len  The number of bytes of binary data to append.
                This may be zero to remove any existing binary suffix data.
   \return 0 on success, or a negative value on error.
   \retval #OP_EINVAL \a _len was negative, or \a _len was positive but
                       \a _data was <code>NULL</code> or the least significant
                       bit of the first byte was not set.
   \retval #OP_EFAULT An internal memory allocation failed.*/
int opus_tags_set_binary_suffix(OpusTags *_tags,
 const unsigned char *_data,int _len) OP_ARG_NONNULL(1);

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/**Look up a comment value by its tag.
   \param _tags  An initialized #OpusTags structure.
   \param _tag   The tag to look up.
   \param _count The instance of the tag.
                 The same tag can appear multiple times, each with a distinct
                  value, so an index is required to retrieve them all.
                 The order in which these values appear is significant and
                  should be preserved.
                 Use opus_tags_query_count() to get the legal range for the
                  \a _count parameter.
   \return A pointer to the queried tag's value.
           This points directly to data in the #OpusTags structure.
           It should not be modified or freed by the application, and
            modifications to the structure may invalidate the pointer.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
536
   \retval NULL If no matching tag is found.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
537
538
const char *opus_tags_query(const OpusTags *_tags,const char *_tag,int _count)
 OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);
539

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
540
541
542
543
544
545
546
547
548
/**Look up the number of instances of a tag.
   Call this first when querying for a specific tag and then iterate over the
    number of instances with separate calls to opus_tags_query() to retrieve
    all the values for that tag in order.
   \param _tags An initialized #OpusTags structure.
   \param _tag  The tag to look up.
   \return The number of instances of this particular tag.*/
int opus_tags_query_count(const OpusTags *_tags,const char *_tag)
 OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);
549

550
551
552
553
554
555
556
557
/**Retrieve the binary suffix data at the end of the packet (if any).
   \param      _tags An initialized #OpusTags structure.
   \param[out] _len  Returns the number of bytes of binary suffix data returned.
   \return A pointer to the binary suffix data, or <code>NULL</code> if none
            was present.*/
const unsigned char *opus_tags_get_binary_suffix(const OpusTags *_tags,
 int *_len) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);

558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/**Get the album gain from an R128_ALBUM_GAIN tag, if one was specified.
   This searches for the first R128_ALBUM_GAIN tag with a valid signed,
    16-bit decimal integer value and returns the value.
   This routine is exposed merely for convenience for applications which wish
    to do something special with the album gain (i.e., display it).
   If you simply wish to apply the album gain instead of the header gain, you
    can use op_set_gain_offset() with an #OP_ALBUM_GAIN type and no offset.
   \param      _tags    An initialized #OpusTags structure.
   \param[out] _gain_q8 The album gain, in 1/256ths of a dB.
                        This will lie in the range [-32768,32767], and should
                         be applied in <em>addition</em> to the header gain.
                        On error, no value is returned, and the previous
                         contents remain unchanged.
   \return 0 on success, or a negative value on error.
   \retval #OP_FALSE There was no album gain available in the given tags.*/
int opus_tags_get_album_gain(const OpusTags *_tags,int *_gain_q8)
 OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);

576
577
578
579
580
581
582
583
584
585
586
587
588
589
/**Get the track gain from an R128_TRACK_GAIN tag, if one was specified.
   This searches for the first R128_TRACK_GAIN tag with a valid signed,
    16-bit decimal integer value and returns the value.
   This routine is exposed merely for convenience for applications which wish
    to do something special with the track gain (i.e., display it).
   If you simply wish to apply the track gain instead of the header gain, you
    can use op_set_gain_offset() with an #OP_TRACK_GAIN type and no offset.
   \param      _tags    An initialized #OpusTags structure.
   \param[out] _gain_q8 The track gain, in 1/256ths of a dB.
                        This will lie in the range [-32768,32767], and should
                         be applied in <em>addition</em> to the header gain.
                        On error, no value is returned, and the previous
                         contents remain unchanged.
   \return 0 on success, or a negative value on error.
590
   \retval #OP_FALSE There was no track gain available in the given tags.*/
591
592
593
int opus_tags_get_track_gain(const OpusTags *_tags,int *_gain_q8)
 OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
594
595
596
597
598
599
600
/**Clears the #OpusTags structure.
   This should be called on an #OpusTags structure after it is no longer
    needed.
   It will free all memory used by the structure members.
   \param _tags The #OpusTags structure to clear.*/
void opus_tags_clear(OpusTags *_tags) OP_ARG_NONNULL(1);

601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/**Check if \a _comment is an instance of a \a _tag_name tag.
   \see opus_tagncompare
   \param _tag_name A NUL-terminated, case-insensitive, ASCII string containing
                     the name of the tag to check for (without the terminating
                     '=' character).
   \param _comment  The comment string to check.
   \return An integer less than, equal to, or greater than zero if \a _comment
            is found respectively, to be less than, to match, or be greater
            than a "tag=value" string whose tag matches \a _tag_name.*/
int opus_tagcompare(const char *_tag_name,const char *_comment);

/**Check if \a _comment is an instance of a \a _tag_name tag.
   This version is slightly more efficient than opus_tagcompare() if the length
    of the tag name is already known (e.g., because it is a constant).
   \see opus_tagcompare
   \param _tag_name A case-insensitive ASCII string containing the name of the
                     tag to check for (without the terminating '=' character).
   \param _tag_len  The number of characters in the tag name.
                    This must be non-negative.
   \param _comment  The comment string to check.
   \return An integer less than, equal to, or greater than zero if \a _comment
            is found respectively, to be less than, to match, or be greater
            than a "tag=value" string whose tag matches the first \a _tag_len
            characters of \a _tag_name.*/
int opus_tagncompare(const char *_tag_name,int _tag_len,const char *_comment);

627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/**Parse a single METADATA_BLOCK_PICTURE tag.
   This decodes the BASE64-encoded content of the tag and returns a structure
    with the MIME type, description, image parameters (if known), and the
    compressed image data.
   If the MIME type indicates the presence of an image format we recognize
    (JPEG, PNG, or GIF) and the actual image data contains the magic signature
    associated with that format, then the OpusPictureTag::format field will be
    set to the corresponding format.
   This is provided as a convenience to avoid requiring applications to parse
    the MIME type and/or do their own format detection for the commonly used
    formats.
   In this case, we also attempt to extract the image parameters directly from
    the image data (overriding any that were present in the tag, which the
    specification says applications are not meant to rely on).
   The application must still provide its own support for actually decoding the
    image data and, if applicable, retrieving that data from URLs.
   \param[out] _pic Returns the parsed picture data.
                    No sanitation is done on the type, MIME type, or
                     description fields, so these might return invalid values.
                    The contents of this structure are left unmodified on
                     failure.
   \param      _tag The METADATA_BLOCK_PICTURE tag contents.
                    The leading "METADATA_BLOCK_PICTURE=" portion is optional,
                     to allow the function to be used on either directly on the
                     values in OpusTags::user_comments or on the return value
                     of opus_tags_query().
   \return 0 on success or a negative value on error.
   \retval #OP_ENOTFORMAT The METADATA_BLOCK_PICTURE contents were not valid.
655
656
657
658
   \retval #OP_EFAULT     There was not enough memory to store the picture tag
                           contents.*/
OP_WARN_UNUSED_RESULT int opus_picture_tag_parse(OpusPictureTag *_pic,
 const char *_tag) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);
659
660
661
662
663
664
665
666
667
668
669
670
671
672

/**Initializes an #OpusPictureTag structure.
   This should be called on a freshly allocated #OpusPictureTag structure
    before attempting to use it.
   \param _pic The #OpusPictureTag structure to initialize.*/
void opus_picture_tag_init(OpusPictureTag *_pic) OP_ARG_NONNULL(1);

/**Clears the #OpusPictureTag structure.
   This should be called on an #OpusPictureTag structure after it is no longer
    needed.
   It will free all memory used by the structure members.
   \param _pic The #OpusPictureTag structure to clear.*/
void opus_picture_tag_clear(OpusPictureTag *_pic) OP_ARG_NONNULL(1);

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
673
674
/*@}*/

675
676
/*@}*/

677
/**\defgroup url_options URL Reading Options*/
678
/*@{*/
679
680
681
682
683
684
685
686
/**\name URL reading options
   Options for op_url_stream_create() and associated functions.
   These allow you to provide proxy configuration parameters, skip SSL
    certificate checks, etc.
   Options are processed in order, and if the same option is passed multiple
    times, only the value specified by the last occurrence has an effect
    (unless otherwise specified).
   They may be expanded in the future.*/
687
688
/*@{*/

689
/**@cond PRIVATE*/
690

691
692
693
694
695
696
697
/*These are the raw numbers used to define the request codes.
  They should not be used directly.*/
#define OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST (6464)
#define OP_HTTP_PROXY_HOST_REQUEST            (6528)
#define OP_HTTP_PROXY_PORT_REQUEST            (6592)
#define OP_HTTP_PROXY_USER_REQUEST            (6656)
#define OP_HTTP_PROXY_PASS_REQUEST            (6720)
698
#define OP_GET_SERVER_INFO_REQUEST            (6784)
699
700
701
702
703
704
705

#define OP_URL_OPT(_request) ((_request)+(char *)0)

/*These macros trigger compilation errors or warnings if the wrong types are
   provided to one of the URL options.*/
#define OP_CHECK_INT(_x) ((void)((_x)==(opus_int32)0),(opus_int32)(_x))
#define OP_CHECK_CONST_CHAR_PTR(_x) ((_x)+((_x)-(const char *)(_x)))
706
707
#define OP_CHECK_SERVER_INFO_PTR(_x) ((_x)+((_x)-(OpusServerInfo *)(_x)))

708
709
/**@endcond*/

710
711
712
713
714
715
716
717
718
719
720
/**HTTP/Shoutcast/Icecast server information associated with a URL.*/
struct OpusServerInfo{
  /**The name of the server (icy-name/ice-name).
     This is <code>NULL</code> if there was no <code>icy-name</code> or
      <code>ice-name</code> header.*/
  char        *name;
  /**A short description of the server (icy-description/ice-description).
     This is <code>NULL</code> if there was no <code>icy-description</code> or
      <code>ice-description</code> header.*/
  char        *description;
  /**The genre the server falls under (icy-genre/ice-genre).
721
722
     This is <code>NULL</code> if there was no <code>icy-genre</code> or
      <code>ice-genre</code> header.*/
723
724
  char        *genre;
  /**The homepage for the server (icy-url/ice-url).
725
726
     This is <code>NULL</code> if there was no <code>icy-url</code> or
      <code>ice-url</code> header.*/
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
  char        *url;
  /**The software used by the origin server (Server).
     This is <code>NULL</code> if there was no <code>Server</code> header.*/
  char        *server;
  /**The media type of the entity sent to the recepient (Content-Type).
     This is <code>NULL</code> if there was no <code>Content-Type</code>
      header.*/
  char        *content_type;
  /**The nominal stream bitrate in kbps (icy-br/ice-bitrate).
     This is <code>-1</code> if there was no <code>icy-br</code> or
      <code>ice-bitrate</code> header.*/
  opus_int32   bitrate_kbps;
  /**Flag indicating whether the server is public (<code>1</code>) or not
      (<code>0</code>) (icy-pub/ice-public).
     This is <code>-1</code> if there was no <code>icy-pub</code> or
      <code>ice-public</code> header.*/
  int          is_public;
  /**Flag indicating whether the server is using HTTPS instead of HTTP.
     This is <code>0</code> unless HTTPS is being used.
     This may not match the protocol used in the original URL if there were
      redirections.*/
  int          is_ssl;
};

/**Initializes an #OpusServerInfo structure.
752
753
754
   All fields are set as if the corresponding header was not available.
   \param _info The #OpusServerInfo structure to initialize.
   \note If you use this function, you must link against <tt>libopusurl</tt>.*/
755
756
757
758
759
760
void opus_server_info_init(OpusServerInfo *_info) OP_ARG_NONNULL(1);

/**Clears the #OpusServerInfo structure.
   This should be called on an #OpusServerInfo structure after it is no longer
    needed.
   It will free all memory used by the structure members.
761
762
   \param _info The #OpusServerInfo structure to clear.
   \note If you use this function, you must link against <tt>libopusurl</tt>.*/
763
void opus_server_info_clear(OpusServerInfo *_info) OP_ARG_NONNULL(1);
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808

/**Skip the certificate check when connecting via TLS/SSL (https).
   \param _b <code>opus_int32</code>: Whether or not to skip the certificate
              check.
             The check will be skipped if \a _b is non-zero, and will not be
              skipped if \a _b is zero.
   \hideinitializer*/
#define OP_SSL_SKIP_CERTIFICATE_CHECK(_b) \
 OP_URL_OPT(OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST),OP_CHECK_INT(_b)

/**Proxy connections through the given host.
   If no port is specified via #OP_HTTP_PROXY_PORT, the port number defaults
    to 8080 (http-alt).
   All proxy parameters are ignored for non-http and non-https URLs.
   \param _host <code>const char *</code>: The proxy server hostname.
                This may be <code>NULL</code> to disable the use of a proxy
                 server.
   \hideinitializer*/
#define OP_HTTP_PROXY_HOST(_host) \
 OP_URL_OPT(OP_HTTP_PROXY_HOST_REQUEST),OP_CHECK_CONST_CHAR_PTR(_host)

/**Use the given port when proxying connections.
   This option only has an effect if #OP_HTTP_PROXY_HOST is specified with a
    non-<code>NULL</code> \a _host.
   If this option is not provided, the proxy port number defaults to 8080
    (http-alt).
   All proxy parameters are ignored for non-http and non-https URLs.
   \param _port <code>opus_int32</code>: The proxy server port.
                This must be in the range 0...65535 (inclusive), or the
                 URL function this is passed to will fail.
   \hideinitializer*/
#define OP_HTTP_PROXY_PORT(_port) \
 OP_URL_OPT(OP_HTTP_PROXY_PORT_REQUEST),OP_CHECK_INT(_port)

/**Use the given user name for authentication when proxying connections.
   All proxy parameters are ignored for non-http and non-https URLs.
   \param _user const char *: The proxy server user name.
                              This may be <code>NULL</code> to disable proxy
                               authentication.
                              A non-<code>NULL</code> value only has an effect
                               if #OP_HTTP_PROXY_HOST and #OP_HTTP_PROXY_PASS
                               are also specified with non-<code>NULL</code>
                               arguments.
   \hideinitializer*/
#define OP_HTTP_PROXY_USER(_user) \
809
 OP_URL_OPT(OP_HTTP_PROXY_USER_REQUEST),OP_CHECK_CONST_CHAR_PTR(_user)
810
811
812
813
814
815
816
817
818
819
820
821

/**Use the given password for authentication when proxying connections.
   All proxy parameters are ignored for non-http and non-https URLs.
   \param _pass const char *: The proxy server password.
                              This may be <code>NULL</code> to disable proxy
                               authentication.
                              A non-<code>NULL</code> value only has an effect
                               if #OP_HTTP_PROXY_HOST and #OP_HTTP_PROXY_USER
                               are also specified with non-<code>NULL</code>
                               arguments.
   \hideinitializer*/
#define OP_HTTP_PROXY_PASS(_pass) \
822
 OP_URL_OPT(OP_HTTP_PROXY_PASS_REQUEST),OP_CHECK_CONST_CHAR_PTR(_pass)
823

824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
/**Parse information about the streaming server (if any) and return it.
   Very little validation is done.
   In particular, OpusServerInfo::url may not be a valid URL,
    OpusServerInfo::bitrate_kbps may not really be in kbps, and
    OpusServerInfo::content_type may not be a valid MIME type.
   The character set of the string fields is not specified anywhere, and should
    not be assumed to be valid UTF-8.
   \param _info OpusServerInfo *: Returns information about the server.
                                  If there is any error opening the stream, the
                                   contents of this structure remain
                                   unmodified.
                                  On success, fills in the structure with the
                                   server information that was available, if
                                   any.
                                  After a successful return, the contents of
                                   this structure should be freed by calling
                                   opus_server_info_clear().
   \hideinitializer*/
#define OP_GET_SERVER_INFO(_info) \
 OP_URL_OPT(OP_GET_SERVER_INFO_REQUEST),OP_CHECK_SERVER_INFO_PTR(_info)

845
846
847
/*@}*/
/*@}*/

848
/**\defgroup stream_callbacks Abstract Stream Reading Interface*/
849
/*@{*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
850
851
852
853
854
855
/**\name Functions for reading from streams
   These functions define the interface used to read from and seek in a stream
    of data.
   A stream does not need to implement seeking, but the decoder will not be
    able to seek if it does not do so.
   These functions also include some convenience routines for working with
856
857
    standard <code>FILE</code> pointers, complete streams stored in a single
    block of memory, or URLs.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
858
859
/*@{*/

860
861
862
863
864
865
866
867
868
/**Reads up to \a _nbytes bytes of data from \a _stream.
   \param      _stream The stream to read from.
   \param[out] _ptr    The buffer to store the data in.
   \param      _nbytes The maximum number of bytes to read.
                       This function may return fewer, though it will not
                        return zero unless it reaches end-of-file.
   \return The number of bytes successfully read, or a negative value on
            error.*/
typedef int (*op_read_func)(void *_stream,unsigned char *_ptr,int _nbytes);
869

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
870
871
872
873
874
875
876
877
878
879
/**Sets the position indicator for \a _stream.
   The new position, measured in bytes, is obtained by adding \a _offset
    bytes to the position specified by \a _whence.
   If \a _whence is set to <code>SEEK_SET</code>, <code>SEEK_CUR</code>, or
    <code>SEEK_END</code>, the offset is relative to the start of the stream,
    the current position indicator, or end-of-file, respectively.
   \retval 0  Success.
   \retval -1 Seeking is not supported or an error occurred.
              <code>errno</code> need not be set.*/
typedef int (*op_seek_func)(void *_stream,opus_int64 _offset,int _whence);
880

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
881
882
883
/**Obtains the current value of the position indicator for \a _stream.
   \return The current position indicator.*/
typedef opus_int64 (*op_tell_func)(void *_stream);
884

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
885
886
887
888
889
890
/**Closes the underlying stream.
   \retval 0   Success.
   \retval EOF An error occurred.
               <code>errno</code> need not be set.*/
typedef int (*op_close_func)(void *_stream);

891
/**The callbacks used to access non-<code>FILE</code> stream resources.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
892
893
894
895
896
   The function prototypes are basically the same as for the stdio functions
    <code>fread()</code>, <code>fseek()</code>, <code>ftell()</code>, and
    <code>fclose()</code>.
   The differences are that the <code>FILE *</code> arguments have been
    replaced with a <code>void *</code>, which is to be used as a pointer to
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
897
898
899
    whatever internal data these functions might need, that #seek and #tell
    take and return 64-bit offsets, and that #seek <em>must</em> return -1 if
    the stream is unseekable.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
struct OpusFileCallbacks{
  /**Used to read data from the stream.
     This must not be <code>NULL</code>.*/
  op_read_func  read;
  /**Used to seek in the stream.
     This may be <code>NULL</code> if seeking is not implemented.*/
  op_seek_func  seek;
  /**Used to return the current read position in the stream.
     This may be <code>NULL</code> if seeking is not implemented.*/
  op_tell_func  tell;
  /**Used to close the stream when the decoder is freed.
     This may be <code>NULL</code> to leave the stream open.*/
  op_close_func close;
};

/**Opens a stream with <code>fopen()</code> and fills in a set of callbacks
    that can be used to access it.
   This is useful to avoid writing your own portable 64-bit seeking wrappers,
    and also avoids cross-module linking issues on Windows, where a
    <code>FILE *</code> must be accessed by routines defined in the same module
    that opened it.
   \param[out] _cb   The callbacks to use for this file.
                     If there is an error opening the file, nothing will be
                      filled in here.
   \param      _path The path to the file to open.
925
926
927
928
                     On Windows, this string must be UTF-8 (to allow access to
                      files whose names cannot be represented in the current
                      MBCS code page).
                     All other systems use the native character encoding.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
929
   \param      _mode The mode to open the file in.
930
931
   \return A stream handle to use with the callbacks, or <code>NULL</code> on
            error.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
932
933
934
OP_WARN_UNUSED_RESULT void *op_fopen(OpusFileCallbacks *_cb,
 const char *_path,const char *_mode) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2)
 OP_ARG_NONNULL(3);
935

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
936
937
938
939
940
941
942
943
944
945
946
/**Opens a stream with <code>fdopen()</code> and fills in a set of callbacks
    that can be used to access it.
   This is useful to avoid writing your own portable 64-bit seeking wrappers,
    and also avoids cross-module linking issues on Windows, where a
    <code>FILE *</code> must be accessed by routines defined in the same module
    that opened it.
   \param[out] _cb   The callbacks to use for this file.
                     If there is an error opening the file, nothing will be
                      filled in here.
   \param      _fd   The file descriptor to open.
   \param      _mode The mode to open the file in.
947
948
   \return A stream handle to use with the callbacks, or <code>NULL</code> on
            error.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
949
950
OP_WARN_UNUSED_RESULT void *op_fdopen(OpusFileCallbacks *_cb,
 int _fd,const char *_mode) OP_ARG_NONNULL(1) OP_ARG_NONNULL(3);
951

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
952
953
954
955
956
957
958
959
960
961
/**Opens a stream with <code>freopen()</code> and fills in a set of callbacks
    that can be used to access it.
   This is useful to avoid writing your own portable 64-bit seeking wrappers,
    and also avoids cross-module linking issues on Windows, where a
    <code>FILE *</code> must be accessed by routines defined in the same module
    that opened it.
   \param[out] _cb     The callbacks to use for this file.
                       If there is an error opening the file, nothing will be
                        filled in here.
   \param      _path   The path to the file to open.
962
963
964
965
                       On Windows, this string must be UTF-8 (to allow access
                        to files whose names cannot be represented in the
                        current MBCS code page).
                       All other systems use the native character encoding.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
966
967
968
   \param      _mode   The mode to open the file in.
   \param      _stream A stream previously returned by op_fopen(), op_fdopen(),
                        or op_freopen().
969
970
   \return A stream handle to use with the callbacks, or <code>NULL</code> on
            error.*/
971
972
973
OP_WARN_UNUSED_RESULT void *op_freopen(OpusFileCallbacks *_cb,
 const char *_path,const char *_mode,void *_stream) OP_ARG_NONNULL(1)
 OP_ARG_NONNULL(2) OP_ARG_NONNULL(3) OP_ARG_NONNULL(4);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
974
975

/**Creates a stream that reads from the given block of memory.
976
977
   This block of memory must contain the complete stream to decode.
   This is useful for caching small streams (e.g., sound effects) in RAM.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
978
979
980
981
982
   \param[out] _cb   The callbacks to use for this stream.
                     If there is an error creating the stream, nothing will be
                      filled in here.
   \param      _data The block of memory to read from.
   \param      _size The size of the block of memory.
983
984
   \return A stream handle to use with the callbacks, or <code>NULL</code> on
            error.*/
985
OP_WARN_UNUSED_RESULT void *op_mem_stream_create(OpusFileCallbacks *_cb,
986
987
988
 const unsigned char *_data,size_t _size) OP_ARG_NONNULL(1);

/**Creates a stream that reads from the given URL.
989
990
991
992
   This function behaves identically to op_url_stream_create(), except that it
    takes a va_list instead of a variable number of arguments.
   It does not call the <code>va_end</code> macro, and because it invokes the
    <code>va_arg</code> macro, the value of \a _ap is undefined after the call.
993
   \note If you use this function, you must link against <tt>libopusurl</tt>.
994
995
996
997
998
999
1000
1001
   \param[out]    _cb  The callbacks to use for this stream.
                       If there is an error creating the stream, nothing will
                        be filled in here.
   \param         _url The URL to read from.
                       Currently only the <file:>, <http:>, and <https:>
                        schemes are supported.
                       Both <http:> and <https:> may be disabled at compile
                        time, in which case opening such URLs will always fail.
1002
1003
1004
1005
                       Currently this only supports URIs.
                       IRIs should be converted to UTF-8 and URL-escaped, with
                        internationalized domain names encoded in punycode,
                        before passing them to this function.
1006
1007
1008
   \param[in,out] _ap  A list of the \ref url_options "optional flags" to use.
                       This is a variable-length list of options terminated
                        with <code>NULL</code>.
1009
1010
   \return A stream handle to use with the callbacks, or <code>NULL</code> on
            error.*/
1011
1012
OP_WARN_UNUSED_RESULT void *op_url_stream_vcreate(OpusFileCallbacks *_cb,
 const char *_url,va_list _ap) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);
1013

1014
1015
/**Creates a stream that reads from the given URL.
   \note If you use this function, you must link against <tt>libopusurl</tt>.
1016
1017
1018
1019
1020
1021
1022
1023
   \param[out] _cb  The callbacks to use for this stream.
                    If there is an error creating the stream, nothing will be
                     filled in here.
   \param      _url The URL to read from.
                    Currently only the <file:>, <http:>, and <https:> schemes
                     are supported.
                    Both <http:> and <https:> may be disabled at compile time,
                     in which case opening such URLs will always fail.
1024
1025
1026
1027
                    Currently this only supports URIs.
                    IRIs should be converted to UTF-8 and URL-escaped, with
                     internationalized domain names encoded in punycode, before
                     passing them to this function.
1028
1029
1030
   \param      ...  The \ref url_options "optional flags" to use.
                    This is a variable-length list of options terminated with
                     <code>NULL</code>.
1031
1032
   \return A stream handle to use with the callbacks, or <code>NULL</code> on
            error.*/
1033
1034
OP_WARN_UNUSED_RESULT void *op_url_stream_create(OpusFileCallbacks *_cb,
 const char *_url,...) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2);
1035
1036

/*@}*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1037
1038
/*@}*/

1039
/**\defgroup stream_open_close Opening and Closing*/
1040
1041
1042
1043
1044
1045
1046
1047
1048
/*@{*/
/**\name Functions for opening and closing streams

   These functions allow you to test a stream to see if it is Opus, open it,
    and close it.
   Several flavors are provided for each of the built-in stream types, plus a
    more general version which takes a set of application-provided callbacks.*/
/*@{*/

1049
/**Test to see if this is an Opus stream.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1050
   For good results, you will need at least 57 bytes (for a pure Opus-only
1051
    stream).
1052
1053
   Something like 512 bytes will give more reliable results for multiplexed
    streams.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1054
1055
   This function is meant to be a quick-rejection filter.
   Its purpose is not to guarantee that a stream is a valid Opus stream, but to
1056
1057
1058
    ensure that it looks enough like Opus that it isn't going to be recognized
    as some other format (except possibly an Opus stream that is also
    multiplexed with other codecs, such as video).
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
   \param[out] _head     The parsed ID header contents.
                         You may pass <code>NULL</code> if you do not need
                          this information.
                         If the function fails, the contents of this structure
                          remain untouched.
   \param _initial_data  An initial buffer of data from the start of the
                          stream.
   \param _initial_bytes The number of bytes in \a _initial_data.
   \return 0 if the data appears to be Opus, or a negative value on error.
   \retval #OP_FALSE      There was not enough data to tell if this was an Opus
                           stream or not.
   \retval #OP_EFAULT     An internal memory allocation failed.
   \retval #OP_EIMPL      The stream used a feature that is not implemented,
                           such as an unsupported channel family.
   \retval #OP_ENOTFORMAT If the data did not contain a recognizable ID
                           header for an Opus stream.
   \retval #OP_EVERSION   If the version field signaled a version this library
                           does not know how to parse.
1077
1078
   \retval #OP_EBADHEADER The ID header was not properly formatted or contained
                           illegal values.*/
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1079
1080
1081
1082
1083
1084
int op_test(OpusHead *_head,
 const unsigned char *_initial_data,size_t _initial_bytes);

/**Open a stream from the given file path.
   \param      _path  The path to the file to open.
   \param[out] _error Returns 0 on success, or a failure code on error.
1085
1086
                      You may pass in <code>NULL</code> if you don't want the
                       failure code.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1087
1088
1089
                      The failure code will be #OP_EFAULT if the file could not
                       be opened, or one of the other failure codes from
                       op_open_callbacks() otherwise.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1090
   \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/
1091
1092
OP_WARN_UNUSED_RESULT OggOpusFile *op_open_file(const char *_path,int *_error)
 OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1093
1094
1095
1096
1097

/**Open a stream from a memory buffer.
   \param      _data  The memory buffer to open.
   \param      _size  The number of bytes in the buffer.
   \param[out] _error Returns 0 on success, or a failure code on error.
1098
1099
                      You may pass in <code>NULL</code> if you don't want the
                       failure code.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1100
                      See op_open_callbacks() for a full list of failure codes.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1101
   \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/
1102
1103
OP_WARN_UNUSED_RESULT OggOpusFile *op_open_memory(const unsigned char *_data,
 size_t _size,int *_error);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1104

1105
/**Open a stream from a URL.
1106
1107
1108
1109
   This function behaves identically to op_open_url(), except that it
    takes a va_list instead of a variable number of arguments.
   It does not call the <code>va_end</code> macro, and because it invokes the
    <code>va_arg</code> macro, the value of \a _ap is undefined after the call.
1110
   \note If you use this function, you must link against <tt>libopusurl</tt>.
1111
1112
1113
1114
1115
1116
   \param         _url   The URL to open.
                         Currently only the <file:>, <http:>, and <https:>
                          schemes are supported.
                         Both <http:> and <https:> may be disabled at compile
                          time, in which case opening such URLs will always
                          fail.
1117
1118
1119
1120
                         Currently this only supports URIs.
                         IRIs should be converted to UTF-8 and URL-escaped,
                          with internationalized domain names encoded in
                          punycode, before passing them to this function.
1121
1122
1123
1124
1125
1126
1127
1128
1129
   \param[out]    _error Returns 0 on success, or a failure code on error.
                         You may pass in <code>NULL</code> if you don't want
                          the failure code.
                         See op_open_callbacks() for a full list of failure
                          codes.
   \param[in,out] _ap    A list of the \ref url_options "optional flags" to
                          use.
                         This is a variable-length list of options terminated
                          with <code>NULL</code>.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1130
   \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/
1131
1132
OP_WARN_UNUSED_RESULT OggOpusFile *op_vopen_url(const char *_url,
 int *_error,va_list _ap) OP_ARG_NONNULL(1);
1133

1134
/**Open a stream from a URL.
1135
   \note If you use this function, you must link against <tt>libopusurl</tt>.
1136
1137
1138
1139
1140
   \param      _url   The URL to open.
                      Currently only the <file:>, <http:>, and <https:> schemes
                       are supported.
                      Both <http:> and <https:> may be disabled at compile
                       time, in which case opening such URLs will always fail.
1141
1142
1143
1144
                      Currently this only supports URIs.
                      IRIs should be converted to UTF-8 and URL-escaped, with
                       internationalized domain names encoded in punycode,
                       before passing them to this function.
1145
1146
1147
1148
1149
1150
1151
   \param[out] _error Returns 0 on success, or a failure code on error.
                      You may pass in <code>NULL</code> if you don't want the
                       failure code.
                      See op_open_callbacks() for a full list of failure codes.
   \param      ...    The \ref url_options "optional flags" to use.
                      This is a variable-length list of options terminated with
                       <code>NULL</code>.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1152
   \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/
1153
1154
OP_WARN_UNUSED_RESULT OggOpusFile *op_open_url(const char *_url,
 int *_error,...) OP_ARG_NONNULL(1);
1155

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
/**Open a stream using the given set of callbacks to access it.
   \param _source        The stream to read from (e.g., a <code>FILE *</code>).
   \param _cb            The callbacks with which to access the stream.
                         <code><a href="#op_read_func">read()</a></code> must
                          be implemented.
                         <code><a href="#op_seek_func">seek()</a></code> and
                          <code><a href="#op_tell_func">tell()</a></code> may
                          be <code>NULL</code>, or may always return -1 to
                          indicate a source is unseekable, but if
                          <code><a href="#op_seek_func">seek()</a></code> is
                          implemented and succeeds on a particular source, then
                          <code><a href="#op_tell_func">tell()</a></code> must
                          also.
                         <code><a href="#op_close_func">close()</a></code> may
                          be <code>NULL</code>, but if it is not, it will be
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1171
                          called when the \c OggOpusFile is destroyed by
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
                          op_free().
                         It will not be called if op_open_callbacks() fails
                          with an error.
   \param _initial_data  An initial buffer of data from the start of the
                          stream.
                         Applications can read some number of bytes from the
                          start of the stream to help identify this as an Opus
                          stream, and then provide them here to allow the
                          stream to be opened, even if it is unseekable.
   \param _initial_bytes The number of bytes in \a _initial_data.
                         If the stream is seekable, its current position (as
                          reported by
                          <code><a href="#opus_tell_func">tell()</a></code>
                          at the start of this function) must be equal to
                          \a _initial_bytes.
                         Otherwise, seeking to absolute positions will
                          generate inconsistent results.
   \param[out] _error    Returns 0 on success, or a failure code on error.
1190
1191
                         You may pass in <code>NULL</code> if you don't want
                          the failure code.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
                         The failure code will be one of
                         <dl>
                           <dt>#OP_EREAD</dt>
                           <dd>An underlying read, seek, or tell operation
                            failed when it should have succeeded, or we failed
                            to find data in the stream we had seen before.</dd>
                           <dt>#OP_EFAULT</dt>
                           <dd>There was a memory allocation failure, or an
                            internal library error.</dd>
                           <dt>#OP_EIMPL</dt>
                           <dd>The stream used a feature that is not
                            implemented, such as an unsupported channel
                            family.</dd>
                           <dt>#OP_EINVAL</dt>
                           <dd><code><a href="#op_seek_func">seek()</a></code>
                            was implemented and succeeded on this source, but
                            <code><a href="#op_tell_func">tell()</a></code>
                            did not, or the starting position indicator was
                            not equal to \a _initial_bytes.</dd>
                           <dt>#OP_ENOTFORMAT</dt>
                           <dd>The stream contained a link that did not have
                            any logical Opus streams in it.</dd>
                           <dt>#OP_EBADHEADER</dt>
                           <dd>A required header packet was not properly
                            formatted, contained illegal values, or was missing
                            altogether.</dd>
                           <dt>#OP_EVERSION</dt>
                           <dd>An ID header contained an unrecognized version
                            number.</dd>
                           <dt>#OP_EBADLINK</dt>
                           <dd>We failed to find data we had seen before after
                            seeking.</dd>
                           <dt>#OP_EBADTIMESTAMP</dt>
                           <dd>The first or last timestamp in a link failed
                            basic validity checks.</dd>
                         </dl>
1228
1229
1230
1231
1232
   \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.
           <tt>libopusfile</tt> does <em>not</em> take ownership of the source
            if the call fails.
           The calling application is responsible for closing the source if
            this call returns an error.*/
1233
1234
1235
OP_WARN_UNUSED_RESULT OggOpusFile *op_open_callbacks(void *_source,
 const OpusFileCallbacks *_cb,const unsigned char *_initial_data,
 size_t _initial_bytes,int *_error) OP_ARG_NONNULL(2);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1236
1237

/**Partially open a stream from the given file path.
1238
   \see op_test_callbacks
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1239
1240
   \param      _path  The path to the file to open.
   \param[out] _error Returns 0 on success, or a failure code on error.
1241
1242
                      You may pass in <code>NULL</code> if you don't want the
                       failure code.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1243
1244
1245
                      The failure code will be #OP_EFAULT if the file could not
                       be opened, or one of the other failure codes from
                       op_open_callbacks() otherwise.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1246
   \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/
1247
1248
OP_WARN_UNUSED_RESULT OggOpusFile *op_test_file(const char *_path,int *_error)
 OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1249
1250

/**Partially open a stream from a memory buffer.
1251
   \see op_test_callbacks
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1252
1253
1254
   \param      _data  The memory buffer to open.
   \param      _size  The number of bytes in the buffer.
   \param[out] _error Returns 0 on success, or a failure code on error.
1255
1256
                      You may pass in <code>NULL</code> if you don't want the
                       failure code.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1257
                      See op_open_callbacks() for a full list of failure codes.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1258
   \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/
1259
1260
OP_WARN_UNUSED_RESULT OggOpusFile *op_test_memory(const unsigned char *_data,
 size_t _size,int *_error);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1261

1262
/**Partially open a stream from a URL.
1263
1264
1265
1266
   This function behaves identically to op_test_url(), except that it
    takes a va_list instead of a variable number of arguments.
   It does not call the <code>va_end</code> macro, and because it invokes the
    <code>va_arg</code> macro, the value of \a _ap is undefined after the call.
1267
   \note If you use this function, you must link against <tt>libopusurl</tt>.
1268
   \see op_test_url
1269
   \see op_test_callbacks
1270
1271
1272
1273
1274
1275
   \param         _url    The URL to open.
                          Currently only the <file:>, <http:>, and <https:>
                           schemes are supported.
                          Both <http:> and <https:> may be disabled at compile
                           time, in which case opening such URLs will always
                           fail.
1276
1277
1278
1279
                          Currently this only supports URIs.
                          IRIs should be converted to UTF-8 and URL-escaped,
                           with internationalized domain names encoded in
                           punycode, before passing them to this function.
1280
1281
1282
1283
1284
1285
1286
1287
1288
   \param[out]    _error  Returns 0 on success, or a failure code on error.
                          You may pass in <code>NULL</code> if you don't want
                           the failure code.
                          See op_open_callbacks() for a full list of failure
                           codes.
   \param[in,out] _ap     A list of the \ref url_options "optional flags" to
                           use.
                          This is a variable-length list of options terminated
                           with <code>NULL</code>.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1289
   \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/
1290
1291
OP_WARN_UNUSED_RESULT OggOpusFile *op_vtest_url(const char *_url,
 int *_error,va_list _ap) OP_ARG_NONNULL(1);
1292

1293
/**Partially open a stream from a URL.
1294
   \note If you use this function, you must link against <tt>libopusurl</tt>.
1295
   \see op_test_callbacks
1296
1297
1298
1299
1300
   \param      _url    The URL to open.
                       Currently only the <file:>, <http:>, and <https:>
                        schemes are supported.
                       Both <http:> and <https:> may be disabled at compile
                        time, in which case opening such URLs will always fail.
1301
1302
1303
1304
                       Currently this only supports URIs.
                       IRIs should be converted to UTF-8 and URL-escaped, with
                        internationalized domain names encoded in punycode,
                        before passing them to this function.
1305
1306
1307
1308
1309
1310
1311
1312
   \param[out] _error  Returns 0 on success, or a failure code on error.
                       You may pass in <code>NULL</code> if you don't want the
                        failure code.
                       See op_open_callbacks() for a full list of failure
                        codes.
   \param      ...     The \ref url_options "optional flags" to use.
                       This is a variable-length list of options terminated
                        with <code>NULL</code>.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1313
   \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/
1314
1315
OP_WARN_UNUSED_RESULT OggOpusFile *op_test_url(const char *_url,
 int *_error,...) OP_ARG_NONNULL(1);
1316

1317
/**Partially open a stream using the given set of callbacks to access it.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1318
1319
   This tests for Opusness and loads the headers for the first link.
   It does not seek (although it tests for seekability).
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
   You can query a partially open stream for the few pieces of basic
    information returned by op_serialno(), op_channel_count(), op_head(), and
    op_tags() (but only for the first link).
   You may also determine if it is seekable via a call to op_seekable().
   You cannot read audio from the stream, seek, get the size or duration,
    get information from links other than the first one, or even get the total
    number of links until you finish opening the stream with op_test_open().
   If you do not need to do any of these things, you can dispose of it with
    op_free() instead.

   This function is provided mostly to simplify porting existing code that used
    <tt>libvorbisfile</tt>.
   For new code, you are likely better off using op_test() instead, which
    is less resource-intensive, requires less data to succeed, and imposes a
    hard limit on the amount of data it examines (important for unseekable
    sources, where all such data must be buffered until you are sure of the
    stream type).
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
   \param _source        The stream to read from (e.g., a <code>FILE *</code>).
   \param _cb            The callbacks with which to access the stream.
                         <code><a href="#op_read_func">read()</a></code> must
                          be implemented.
                         <code><a href="#op_seek_func">seek()</a></code> and
                          <code><a href="#op_tell_func">tell()</a></code> may
                          be <code>NULL</code>, or may always return -1 to
                          indicate a source is unseekable, but if
                          <code><a href="#op_seek_func">seek()</a></code> is
                          implemented and succeeds on a particular source, then
                          <code><a href="#op_tell_func">tell()</a></code> must
                          also.
                         <code><a href="#op_close_func">close()</a></code> may
                          be <code>NULL</code>, but if it is not, it will be
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1351
                          called when the \c OggOpusFile is destroyed by
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
                          op_free().
                         It will not be called if op_open_callbacks() fails
                          with an error.
   \param _initial_data  An initial buffer of data from the start of the
                          stream.
                         Applications can read some number of bytes from the
                          start of the stream to help identify this as an Opus
                          stream, and then provide them here to allow the
                          stream to be tested more thoroughly, even if it is
                          unseekable.
   \param _initial_bytes The number of bytes in \a _initial_data.
                         If the stream is seekable, its current position (as
                          reported by
                          <code><a href="#opus_tell_func">tell()</a></code>
                          at the start of this function) must be equal to
                          \a _initial_bytes.
                         Otherwise, seeking to absolute positions will
                          generate inconsistent results.
   \param[out] _error    Returns 0 on success, or a failure code on error.
1371
1372
                         You may pass in <code>NULL</code> if you don't want
                          the failure code.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1373
1374
                         See op_open_callbacks() for a full list of failure
                          codes.
1375
1376
1377
1378
1379
   \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.
           <tt>libopusfile</tt> does <em>not</em> take ownership of the source
            if the call fails.
           The calling application is responsible for closing the source if
            this call returns an error.*/
1380
1381
1382
OP_WARN_UNUSED_RESULT OggOpusFile *op_test_callbacks(void *_source,
 const OpusFileCallbacks *_cb,const unsigned char *_initial_data,
 size_t _initial_bytes,int *_error) OP_ARG_NONNULL(2);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1383
1384
1385
1386

/**Finish opening a stream partially opened with op_test_callbacks() or one of
    the associated convenience functions.
   If this function fails, you are still responsible for freeing the
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1387
1388
    \c OggOpusFile with op_free().
   \param _of The \c OggOpusFile to finish opening.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
   \return 0 on success, or a negative value on error.
   \retval #OP_EREAD         An underlying read, seek, or tell operation failed
                              when it should have succeeded.
   \retval #OP_EFAULT        There was a memory allocation failure, or an
                              internal library error.
   \retval #OP_EIMPL         The stream used a feature that is not implemented,
                              such as an unsupported channel family.
   \retval #OP_EINVAL        The stream was not partially opened with
                              op_test_callbacks() or one of the associated
                              convenience functions.
   \retval #OP_ENOTFORMAT    The stream contained a link that did not have any
                              logical Opus streams in it.
   \retval #OP_EBADHEADER    A required header packet was not properly
                              formatted, contained illegal values, or was
                              missing altogether.
   \retval #OP_EVERSION      An ID header contained an unrecognized version
                              number.
   \retval #OP_EBADLINK      We failed to find data we had seen before after
                              seeking.
   \retval #OP_EBADTIMESTAMP The first or last timestamp in a link failed basic
                              validity checks.*/
1410
int op_test_open(OggOpusFile *_of) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1411

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1412
1413
/**Release all memory used by an \c OggOpusFile.
   \param _of The \c OggOpusFile to free.*/
1414
1415
void op_free(OggOpusFile *_of);

1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
/*@}*/
/*@}*/

/**\defgroup stream_info Stream Information*/
/*@{*/
/**\name Functions for obtaining information about streams

   These functions allow you to get basic information about a stream, including
    seekability, the number of links (for chained streams), plus the size,
    duration, bitrate, header parameters, and meta information for each link
    (or, where available, the stream as a whole).
   Some of these (size, duration) are only available for seekable streams.
   You can also query the current stream position, link, and playback time,
    and instantaneous bitrate during playback.

   Some of these functions may be used successfully on the partially open
1432
1433
    streams returned by op_test_callbacks() or one of the associated
    convenience functions.
1434
1435
1436
   Their documention will indicate so explicitly.*/
/*@{*/

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1437
1438
/**Returns whether or not the data source being read is seekable.
   This is true if
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
   <ol>
   <li>The <code><a href="#op_seek_func">seek()</a></code> and
    <code><a href="#op_tell_func">tell()</a></code> callbacks are both
    non-<code>NULL</code>,</li>
   <li>The <code><a href="#op_seek_func">seek()</a></code> callback was
    successfully executed at least once, and</li>
   <li>The <code><a href="#op_tell_func">tell()</a></code> callback was
    successfully able to report the position indicator afterwards.</li>
   </ol>
   This function may be called on partially-opened streams.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1449
   \param _of The \c OggOpusFile whose seekable status is to be returned.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1450
   \return A non-zero value if seekable, and 0 if unseekable.*/
1451
int op_seekable(const OggOpusFile *_of) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1452

1453
1454
1455
1456
1457
1458
/**Returns the number of links in this chained stream.
   This function may be called on partially-opened streams, but it will always
    return 1.
   The actual number of links is not known until the stream is fully opened.
   \param _of The \c OggOpusFile from which to retrieve the link count.
   \return For fully-open seekable sources, this returns the total number of
1459
            links in the whole stream, which will be at least 1.
1460
           For partially-open or unseekable sources, this always returns 1.*/
1461
int op_link_count(const OggOpusFile *_of) OP_ARG_NONNULL(1);
1462

Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1463
1464
/**Get the serial number of the given link in a (possibly-chained) Ogg Opus
    stream.
1465
1466
   This function may be called on partially-opened streams, but it will always
    return the serial number of the Opus stream in the first link.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1467
   \param _of The \c OggOpusFile from which to retrieve the serial number.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1468
1469
1470
1471
1472
1473
1474
1475
   \param _li The index of the link whose serial number should be retrieved.
              Use a negative number to get the serial number of the current
               link.
   \return The serial number of the given link.
           If \a _li is greater than the total number of links, this returns
            the serial number of the last link.
           If the source is not seekable, this always returns the serial number
            of the current link.*/
1476
opus_uint32 op_serialno(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1477

1478
/**Get the channel count of the given link in a (possibly-chained) Ogg Opus
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1479
1480
1481
    stream.
   This is equivalent to <code>op_head(_of,_li)->channel_count</code>, but
    is provided for convenience.
1482
   This function may be called on partially-opened streams, but it will always
1483
    return the channel count of the Opus stream in the first link.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1484
   \param _of The \c OggOpusFile from which to retrieve the channel count.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1485
1486
1487
1488
1489
1490
1491
1492
   \param _li The index of the link whose channel count should be retrieved.
              Use a negative number to get the channel count of the current
               link.
   \return The channel count of the given link.
           If \a _li is greater than the total number of links, this returns
            the channel count of the last link.
           If the source is not seekable, this always returns the channel count
            of the current link.*/
1493
int op_channel_count(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1494
1495

/**Get the total (compressed) size of the stream, or of an individual link in
1496
1497
    a (possibly-chained) Ogg Opus stream, including all headers and Ogg muxing
    overhead.
1498
1499
1500
1501
   \warning If the Opus stream (or link) is concurrently multiplexed with other
    logical streams (e.g., video), this returns the size of the entire stream
    (or link), not just the number of bytes in the first logical Opus stream.
   Returning the latter would require scanning the entire file.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1502
   \param _of The \c OggOpusFile from which to retrieve the compressed size.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1503
1504
1505
1506
1507
1508
   \param _li The index of the link whose compressed size should be computed.
              Use a negative number to get the compressed size of the entire
               stream.
   \return The compressed size of the entire stream if \a _li is negative, the
            compressed size of link \a _li if it is non-negative, or a negative
            value on error.
1509
1510
1511
           The compressed size of the entire stream may be smaller than that
            of the underlying source if trailing garbage was detected in the
            file.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1512
1513
1514
   \retval #OP_EINVAL The source is not seekable (so we can't know the length),
                       \a _li wasn't less than the total number of links in
                       the stream, or the stream was only partially open.*/
1515
opus_int64 op_raw_total(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1516
1517

/**Get the total PCM length (number of samples at 48 kHz) of the stream, or of
1518
    an individual link in a (possibly-chained) Ogg Opus stream.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1519
1520
1521
1522
1523
   Users looking for <code>op_time_total()</code> should use op_pcm_total()
    instead.
   Because timestamps in Opus are fixed at 48 kHz, there is no need for a
    separate function to convert this to seconds (and leaving it out avoids
    introducing floating point to the API, for those that wish to avoid it).
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1524
   \param _of The \c OggOpusFile from which to retrieve the PCM offset.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1525
1526
1527
1528
1529
1530
1531
1532
   \param _li The index of the link whose PCM length should be computed.
              Use a negative number to get the PCM length of the entire stream.
   \return The PCM length of the entire stream if \a _li is negative, the PCM
            length of link \a _li if it is non-negative, or a negative value on
            error.
   \retval #OP_EINVAL The source is not seekable (so we can't know the length),
                       \a _li wasn't less than the total number of links in
                       the stream, or the stream was only partially open.*/
1533
ogg_int64_t op_pcm_total(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1534
1535
1536

/**Get the ID header information for the given link in a (possibly chained) Ogg
    Opus stream.
1537
1538
   This function may be called on partially-opened streams, but it will always
    return the ID header information of the Opus stream in the first link.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1539
   \param _of The \c OggOpusFile from which to retrieve the ID header
1540
               information.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1541
1542
1543
1544
1545
1546
1547
   \param _li The index of the link whose ID header information should be
               retrieved.
              Use a negative number to get the ID header information of the
               current link.
              For an unseekable stream, \a _li is ignored, and the ID header
               information for the current link is always returned, if
               available.
1548
   \return The contents of the ID header for the given link.*/
1549
const OpusHead *op_head(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1550
1551
1552

/**Get the comment header information for the given link in a (possibly
    chained) Ogg Opus stream.
1553
1554
   This function may be called on partially-opened streams, but it will always
    return the tags from the Opus stream in the first link.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1555
   \param _of The \c OggOpusFile from which to retrieve the comment header
1556
               information.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1557
1558
1559
1560
1561
1562
1563
1564
   \param _li The index of the link whose comment header information should be
               retrieved.
              Use a negative number to get the comment header information of
               the current link.
              For an unseekable stream, \a _li is ignored, and the comment
               header information for the current link is always returned, if
               available.
   \return The contents of the comment header for the given link, or
1565
1566
            <code>NULL</code> if this is an unseekable stream that encountered
            an invalid link.*/
1567
const OpusTags *op_tags(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1568

1569
1570
1571
1572
1573
1574
/**Retrieve the index of the current link.
   This is the link that produced the data most recently read by
    op_read_float() or its associated functions, or, after a seek, the link
    that the seek target landed in.
   Reading more data may advance the link index (even on the first read after a
    seek).
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1575
   \param _of The \c OggOpusFile from which to retrieve the current link index.
1576
   \return The index of the current link on success, or a negative value on
1577
            failure.
1578
1579
1580
1581
1582
           For seekable streams, this is a number between 0 and the value
            returned by op_link_count().
           For unseekable streams, this value starts at 0 and increments by one
            each time a new link is encountered (even though op_link_count()
            always returns 1).
1583
   \retval #OP_EINVAL The stream was only partially open.*/
1584
int op_current_link(const OggOpusFile *_of) OP_ARG_NONNULL(1);
1585

1586
1587
/**Computes the bitrate of the stream, or of an individual link in a
    (possibly-chained) Ogg Opus stream.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1588
1589
   The stream must be seekable to compute the bitrate.
   For unseekable streams, use op_bitrate_instant() to get periodic estimates.
1590
1591
1592
1593
1594
1595
1596
1597
1598
   \warning If the Opus stream (or link) is concurrently multiplexed with other
    logical streams (e.g., video), this uses the size of the entire stream (or
    link) to compute the bitrate, not just the number of bytes in the first
    logical Opus stream.
   Returning the latter requires scanning the entire file, but this may be done
    by decoding the whole file and calling op_bitrate_instant() once at the
    end.
   Install a trivial decoding callback with op_set_decode_callback() if you
    wish to skip actual decoding during this process.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1599
   \param _of The \c OggOpusFile from which to retrieve the bitrate.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1600
   \param _li The index of the link whose bitrate should be computed.
1601
              Use a negative number to get the bitrate of the whole stream.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1602
   \return The bitrate on success, or a negative value on error.
1603
   \retval #OP_EINVAL The stream was only partially open, the stream was not
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1604
1605
                       seekable, or \a _li was larger than the number of
                       links.*/
1606
opus_int32 op_bitrate(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1607
1608

/**Compute the instantaneous bitrate, measured as the ratio of bits to playable
1609
    samples decoded since a) the last call to op_bitrate_instant(), b) the last
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1610
1611
1612
1613
    seek, or c) the start of playback, whichever was most recent.
   This will spike somewhat after a seek or at the start/end of a chain
    boundary, as pre-skip, pre-roll, and end-trimming causes samples to be
    decoded but not played.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1614
   \param _of The \c OggOpusFile from which to retrieve the bitrate.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1615
   \return The bitrate, in bits per second, or a negative value on error.
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1616
   \retval #OP_FALSE  No data has been decoded since any of the events
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1617
                       described above.
1618
   \retval #OP_EINVAL The stream was only partially open.*/
1619
opus_int32 op_bitrate_instant(OggOpusFile *_of) OP_ARG_NONNULL(1);
Timothy B. Terriberry's avatar
Timothy B. Terriberry committed
1620