| 6 | * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * |
| 7 | * * |
| 8 | * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012 * |
| 9 | * by the Xiph.Org Foundation and contributors http://www.xiph.org/ * |
| 10 | * * |
| 11 | ******************************************************************** |
| 12 |
| 13 | function: stdio-based convenience library for opening/seeking/decoding |
| 14 | last mod: $Id: vorbisfile.c 17573 2010-10-27 14:53:59Z xiphmont $ |
| 15 |
| 16 | ********************************************************************/ |
| 17 | #ifdef HAVE_CONFIG_H |
| 18 | #include "config.h" |
| 19 | #endif |
| 20 |
| 21 | #include "internal.h" |
| 22 | #include <stdio.h> |
| 23 | #include <stdlib.h> |
| 24 | #include <errno.h> |
| 25 | #include <limits.h> |
| 26 | #include <string.h> |
| 27 | #include <math.h> |
| 28 |
| 29 | #include "opusfile.h" |
| 30 |
| 31 | /*This implementation is largely based off of libvorbisfile. |
| 32 | All of the Ogg bits work roughly the same, though I have made some |
| 33 | "improvements" that have not been folded back there, yet.*/ |
| 34 |
| 35 | /*A 'chained bitstream' is an Ogg Opus bitstream that contains more than one |
| 36 | logical bitstream arranged end to end (the only form of Ogg multiplexing |
| 37 | supported by this library. |
| 38 | Grouping (parallel multiplexing) is not supported, except to the extent that |
| 39 | if there are multiple logical Ogg streams in a single link of the chain, we |
| 40 | will ignore all but the first Opus stream we find.*/ |
| 41 |
| 42 | /*An Ogg Opus file can be played beginning to end (streamed) without worrying |
| 43 | ahead of time about chaining (see opusdec from the opus-tools package). |
| 44 | If we have the whole file, however, and want random access |
| 45 | (seeking/scrubbing) or desire to know the total length/time of a file, we |
| 46 | need to account for the possibility of chaining.*/ |
| 47 |
| 48 | /*We can handle things a number of ways. |
| 49 | We can determine the entire bitstream structure right off the bat, or find |
| 50 | pieces on demand. |
| 51 | This library determines and caches structure for the entire bitstream, but |
| 52 | builds a virtual decoder on the fly when moving between links in the chain.*/ |
| 53 |
| 54 | /*There are also different ways to implement seeking. |
| 55 | Enough information exists in an Ogg bitstream to seek to sample-granularity |
| 56 | positions in the output. |
| 57 | Or, one can seek by picking some portion of the stream roughly in the desired |
| 58 | area if we only want coarse navigation through the stream. |
| 59 | We implement and expose both strategies.*/ |
| 60 |
| 61 | /*The maximum number of bytes in a page (including the page headers).*/ |
| 62 | #define OP_PAGE_SIZE_MAX (65307) |
| 63 | /*The default amount to seek backwards per step when trying to find the |
| 64 | previous page. |
| 65 | This must be at least as large as the maximum size of a page.*/ |
| 66 | #define OP_CHUNK_SIZE (65536) |
| 67 | /*The maximum amount to seek backwards per step when trying to find the |
| 68 | previous page.*/ |
| 69 | #define OP_CHUNK_SIZE_MAX (1024*(opus_int32)1024) |
| 70 | /*A smaller read size is needed for low-rate streaming.*/ |
| 71 | #define OP_READ_SIZE (2048) |
| 72 |
| 73 | int op_test(OpusHead *_head, |
| 74 | const unsigned char *_initial_data,size_t _initial_bytes){ |
| 75 | ogg_sync_state oy; |
| 76 | char *data; |
| 77 | int err; |
| 78 | /*The first page of a normal Opus file will be at most 57 bytes (27 Ogg |
| 79 | page header bytes + 1 lacing value + 21 Opus header bytes + 8 channel |
| 80 | mapping bytes). |
| 81 | It will be at least 47 bytes (27 Ogg page header bytes + 1 lacing value + |
| 82 | 19 Opus header bytes using channel mapping family 0). |
| 83 | If we don't have at least that much data, give up now.*/ |
| 84 | if(_initial_bytes<47)return OP_FALSE; |
| 85 | /*Only proceed if we start with the magic OggS string. |
| 86 | This is to prevent us spending a lot of time allocating memory and looking |
| 87 | for Ogg pages in non-Ogg files.*/ |
| 88 | if(memcmp(_initial_data,"OggS",4)!=0)return OP_ENOTFORMAT; |
| 89 | ogg_sync_init(&oy); |
| 90 | data=ogg_sync_buffer(&oy,_initial_bytes); |
| 91 | if(data!=NULL){ |
| 92 | ogg_stream_state os; |
| 93 | ogg_page og; |
| 94 | int ret; |
| 95 | memcpy(data,_initial_data,_initial_bytes); |
| 96 | ogg_sync_wrote(&oy,_initial_bytes); |
| 97 | ogg_stream_init(&os,-1); |
| 98 | err=OP_FALSE; |
| 99 | do{ |
| 100 | ogg_packet op; |
| 101 | ret=ogg_sync_pageout(&oy,&og); |
| 102 | /*Ignore holes.*/ |
| 103 | if(ret<0)continue; |
| 104 | /*Stop if we run out of data.*/ |
| 105 | if(!ret)break; |
| 106 | ogg_stream_reset_serialno(&os,ogg_page_serialno(&og)); |
| 107 | ogg_stream_pagein(&os,&og); |
| 108 | /*Only process the first packet on this page (if it's a BOS packet, |
| 109 | it's required to be the only one).*/ |
| 110 | if(ogg_stream_packetout(&os,&op)==1){ |
| 111 | if(op.b_o_s){ |
| 112 | ret=opus_head_parse(_head,op.packet,op.bytes); |
| 113 | /*If this didn't look like Opus, keep going.*/ |
| 114 | if(ret==OP_ENOTFORMAT)continue; |
| 115 | /*Otherwise we're done, one way or another.*/ |
| 116 | err=ret; |
| 117 | } |
| 118 | /*We finished parsing the headers. |
| 119 | There is no Opus to be found.*/ |
| 120 | else err=OP_ENOTFORMAT; |
| 121 | } |
| 122 | } |
| 123 | while(err==OP_FALSE); |
| 124 | ogg_stream_clear(&os); |
| 125 | } |
| 126 | else err=OP_EFAULT; |
| 127 | ogg_sync_clear(&oy); |
| 128 | return err; |
| 129 | } |
| 130 |
| 131 | /*Many, many internal helpers. |
| 132 | The intention is not to be confusing. |
| 133 | Rampant duplication and monolithic function implementation (though we do have |
| 134 | some large, omnibus functions still) would be harder to understand anyway. |
| 135 | The high level functions are last. |
| 136 | Begin grokking near the end of the file if you prefer to read things |
| 137 | top-down.*/ |
| 138 |
| 139 | /*The read/seek functions track absolute position within the stream.*/ |
| 140 |
| 141 | /*Read a little more data from the file/pipe into the ogg_sync framer. |
| 142 | _nbytes: The maximum number of bytes to read. |
| 143 | Return: A positive number of bytes read on success, 0 on end-of-file, or a |
| 144 | negative value on failure.*/ |
| 145 | static int op_get_data(OggOpusFile *_of,int _nbytes){ |
| 146 | unsigned char *buffer; |
| 147 | int nbytes; |
| 148 | OP_ASSERT(_nbytes>0); |
| 149 | buffer=(unsigned char *)ogg_sync_buffer(&_of->oy,_nbytes); |
| 150 | nbytes=(int)(*_of->callbacks.read)(_of->source,buffer,_nbytes); |
| 151 | OP_ASSERT(nbytes<=_nbytes); |
| 152 | if(OP_LIKELY(nbytes>0))ogg_sync_wrote(&_of->oy,nbytes); |
| 153 | return nbytes; |
| 154 | } |
| 155 |
| 156 | /*Save a tiny smidge of verbosity to make the code more readable.*/ |
| 157 | static int op_seek_helper(OggOpusFile *_of,opus_int64 _offset){ |
| 158 | if(_offset==_of->offset)return 0; |
| 159 | if(_of->callbacks.seek==NULL|| |
| 160 | (*_of->callbacks.seek)(_of->source,_offset,SEEK_SET)){ |
| 161 | return OP_EREAD; |
| 162 | } |
| 163 | _of->offset=_offset; |
| 164 | ogg_sync_reset(&_of->oy); |
| 165 | return 0; |
| 166 | } |
| 167 |
| 168 | /*Get the current position indicator of the underlying source. |
| 169 | This should be the same as the value reported by tell().*/ |
| 170 | static opus_int64 op_position(const OggOpusFile *_of){ |
| 171 | /*The current position indicator is _not_ simply offset. |
| 172 | We may also have unprocessed, buffered data in the sync state.*/ |
| 173 | return _of->offset+_of->oy.fill-_of->oy.returned; |
| 174 | } |
| 175 |
| 176 | /*From the head of the stream, get the next page. |
| 177 | _boundary specifies if the function is allowed to fetch more data from the |
| 178 | stream (and how much) or only use internally buffered data. |
| 179 | _boundary: -1: Unbounded search. |
| 180 | 0: Read no additional data. |
| 181 | Use only cached data. |
| 182 | n: Search for the start of a new page up to file position n. |
| 183 | Return: n>=0: Found a page at absolute offset n. |
| 184 | OP_FALSE: Hit the _boundary limit. |
| 185 | OP_EREAD: An underlying read operation failed. |
| 186 | OP_BADLINK: We hit end-of-file before reaching _boundary.*/ |
| 187 | static opus_int64 op_get_next_page(OggOpusFile *_of,ogg_page *_og, |
| 188 | opus_int64 _boundary){ |
| 189 | while(_boundary<=0||_of->offset<_boundary){ |
| 190 | int more; |
| 191 | more=ogg_sync_pageseek(&_of->oy,_og); |
| 192 | /*Skipped (-more) bytes.*/ |
| 193 | if(OP_UNLIKELY(more<0))_of->offset-=more; |
| 194 | else if(more==0){ |
| 195 | int read_nbytes; |
| 196 | int ret; |
| 197 | /*Send more paramedics.*/ |
| 198 | if(!_boundary)return OP_FALSE; |
| 199 | if(_boundary<0)read_nbytes=OP_READ_SIZE; |
| 200 | else{ |
| 201 | opus_int64 position; |
| 202 | position=op_position(_of); |
| 203 | if(position>=_boundary)return OP_FALSE; |
| 204 | read_nbytes=(int)OP_MIN(_boundary-position,OP_READ_SIZE); |
| 205 | } |
| 206 | ret=op_get_data(_of,read_nbytes); |
| 207 | if(OP_UNLIKELY(ret<0))return OP_EREAD; |
| 208 | if(OP_UNLIKELY(ret==0)){ |
| 209 | /*Only fail cleanly on EOF if we didn't have a known boundary. |
| 210 | Otherwise, we should have been able to reach that boundary, and this |
| 211 | is a fatal error.*/ |
| 212 | return OP_UNLIKELY(_boundary<0)?OP_FALSE:OP_EBADLINK; |
| 213 | } |
| 214 | } |
| 215 | else{ |
| 216 | /*Got a page. |
| 217 | Return the page start offset and advance the internal offset past the |
| 218 | page end.*/ |
| 219 | opus_int64 page_offset; |
| 220 | page_offset=_of->offset; |
| 221 | _of->offset+=more; |
| 222 | OP_ASSERT(page_offset>=0); |
| 223 | return page_offset; |
| 224 | } |
| 225 | } |
| 226 | return OP_FALSE; |
| 227 | } |
| 228 |
| 229 | static int op_add_serialno(const ogg_page *_og, |
| 230 | ogg_uint32_t **_serialnos,int *_nserialnos,int *_cserialnos){ |
| 231 | ogg_uint32_t *serialnos; |
| 232 | int nserialnos; |
| 233 | int cserialnos; |
| 234 | ogg_uint32_t s; |
| 235 | s=ogg_page_serialno(_og); |
| 236 | serialnos=*_serialnos; |
| 237 | nserialnos=*_nserialnos; |
| 238 | cserialnos=*_cserialnos; |
| 239 | if(OP_UNLIKELY(nserialnos>=cserialnos)){ |
| 240 | if(OP_UNLIKELY(cserialnos>INT_MAX-1>>1))return OP_EFAULT; |
| 241 | cserialnos=2*cserialnos+1; |
| 242 | OP_ASSERT(nserialnos<cserialnos); |
| 243 | serialnos=(ogg_uint32_t *)_ogg_realloc(serialnos, |
| 244 | sizeof(*serialnos)*cserialnos); |
| 245 | if(OP_UNLIKELY(serialnos==NULL))return OP_EFAULT; |
| 246 | } |
| 247 | serialnos[nserialnos++]=s; |
| 248 | *_serialnos=serialnos; |
| 249 | *_nserialnos=nserialnos; |
| 250 | *_cserialnos=cserialnos; |
| 251 | return 0; |
| 252 | } |
| 253 |
| 254 | /*Returns nonzero if found.*/ |
| 255 | static int op_lookup_serialno(ogg_uint32_t _s, |
| 256 | const ogg_uint32_t *_serialnos,int _nserialnos){ |
| 257 | int i; |
| 258 | for(i=0;i<_nserialnos&&_serialnos[i]!=_s;i++); |
| 259 | return i<_nserialnos; |
| 260 | } |
| 261 |
| 262 | static int op_lookup_page_serialno(const ogg_page *_og, |
| 263 | const ogg_uint32_t *_serialnos,int _nserialnos){ |
| 264 | return op_lookup_serialno(ogg_page_serialno(_og),_serialnos,_nserialnos); |
| 265 | } |
| 266 |
| 267 | typedef struct OpusSeekRecord OpusSeekRecord; |
| 268 |
| 269 | /*We use this to remember the pages we found while enumerating the links of a |
| 270 | chained stream. |
| 271 | We keep track of the starting and ending offsets, as well as the point we |
| 272 | started searching from, so we know where to bisect. |
| 273 | We also keep the serial number, so we can tell if the page belonged to the |
| 274 | current link or not, as well as the granule position, to aid in estimating |
| 275 | the start of the link.*/ |
| 276 | struct OpusSeekRecord{ |
| 277 | /*The earliest byte we know of such that reading forward from it causes |
| 278 | capture to be regained at this page.*/ |
| 279 | opus_int64 search_start; |
| 280 | /*The offset of this page.*/ |
| 281 | opus_int64 offset; |
| 282 | /*The size of this page.*/ |
| 283 | opus_int32 size; |
| 284 | /*The serial number of this page.*/ |
| 285 | ogg_uint32_t serialno; |
| 286 | /*The granule position of this page.*/ |
| 287 | ogg_int64_t gp; |
| 288 | }; |
| 289 |
| 290 | /*Find the last page beginning before _offset with a valid granule position. |
| 291 | There is no '_boundary' parameter as it will always have to read more data. |
| 292 | This is much dirtier than the above, as Ogg doesn't have any backward search |
| 293 | linkage. |
| 294 | This search prefers pages of the specified serial number. |
| 295 | If a page of the specified serial number is spotted during the |
| 296 | seek-back-and-read-forward, it will return the info of last page of the |
| 297 | matching serial number, instead of the very last page, unless the very last |
| 298 | page belongs to a different link than preferred serial number. |
| 299 | If no page of the specified serial number is seen, it will return the info of |
| 300 | the last page. |
| 301 | [out] _sr: Returns information about the page that was found on success. |
| 302 | _offset: The _offset before which to find a page. |
| 303 | Any page returned will consist of data entirely before _offset. |
| 304 | _serialno: The preferred serial number. |
| 305 | If a page with this serial number is found, it will be returned |
| 306 | even if another page in the same link is found closer to |
| 307 | _offset. |
| 308 | This is purely opportunistic: there is no guarantee such a page |
| 309 | will be found if it exists. |
| 310 | _serialnos: The list of serial numbers in the link that contains the |
| 311 | preferred serial number. |
| 312 | _nserialnos: The number of serial numbers in the current link. |
| 313 | Return: 0 on success, or a negative value on failure. |
| 314 | OP_EREAD: Failed to read more data (error or EOF). |
| 315 | OP_EBADLINK: We couldn't find a page even after seeking back to the |
| 316 | start of the stream.*/ |
| 317 | static int op_get_prev_page_serial(OggOpusFile *_of,OpusSeekRecord *_sr, |
| 318 | opus_int64 _offset,ogg_uint32_t _serialno, |
| 319 | const ogg_uint32_t *_serialnos,int _nserialnos){ |
| 320 | OpusSeekRecord preferred_sr; |
| 321 | ogg_page og; |
| 322 | opus_int64 begin; |
| 323 | opus_int64 end; |
| 324 | opus_int64 original_end; |
| 325 | opus_int32 chunk_size; |
| 326 | int preferred_found; |
| 327 | original_end=end=begin=_offset; |
| 328 | preferred_found=0; |
| 329 | _offset=-1; |
| 330 | chunk_size=OP_CHUNK_SIZE; |
| 331 | do{ |
| 332 | opus_int64 search_start; |
| 333 | int ret; |
| 334 | OP_ASSERT(chunk_size>=OP_PAGE_SIZE_MAX); |
| 335 | begin=OP_MAX(begin-chunk_size,0); |
| 336 | ret=op_seek_helper(_of,begin); |
| 337 | if(OP_UNLIKELY(ret<0))return ret; |
| 338 | search_start=begin; |
| 339 | while(_of->offset<end){ |
| 340 | opus_int64 llret; |
| 341 | ogg_uint32_t serialno; |
| 342 | llret=op_get_next_page(_of,&og,end); |
| 343 | if(OP_UNLIKELY(llret<OP_FALSE))return (int)llret; |
| 344 | else if(llret==OP_FALSE)break; |
| 345 | serialno=ogg_page_serialno(&og); |
| 346 | /*Save the information for this page. |
| 347 | We're not interested in the page itself... just the serial number, byte |
| 348 | offset, page size, and granule position.*/ |
| 349 | _sr->search_start=search_start; |
| 350 | _sr->offset=_offset=llret; |
| 351 | _sr->serialno=serialno; |
| 352 | OP_ASSERT(_of->offset-_offset>=0); |
| 353 | OP_ASSERT(_of->offset-_offset<=OP_PAGE_SIZE_MAX); |
| 354 | _sr->size=(opus_int32)(_of->offset-_offset); |
| 355 | _sr->gp=ogg_page_granulepos(&og); |
| 356 | /*If this page is from the stream we're looking for, remember it.*/ |
| 357 | if(serialno==_serialno){ |
| 358 | preferred_found=1; |
| 359 | *&preferred_sr=*_sr; |
| 360 | } |
| 361 | if(!op_lookup_serialno(serialno,_serialnos,_nserialnos)){ |
| 362 | /*We fell off the end of the link, which means we seeked back too far |
| 363 | and shouldn't have been looking in that link to begin with. |
| 364 | If we found the preferred serial number, forget that we saw it.*/ |
| 365 | preferred_found=0; |
| 366 | } |
| 367 | search_start=llret+1; |
| 368 | } |
| 369 | /*We started from the beginning of the stream and found nothing. |
| 370 | This should be impossible unless the contents of the source changed out |
| 371 | from under us after we read from it.*/ |
| 372 | if(OP_UNLIKELY(!begin)&&OP_UNLIKELY(_offset<0))return OP_EBADLINK; |
| 373 | /*Bump up the chunk size. |
| 374 | This is mildly helpful when seeks are very expensive (http).*/ |
| 375 | chunk_size=OP_MIN(2*chunk_size,OP_CHUNK_SIZE_MAX); |
| 376 | /*Avoid quadratic complexity if we hit an invalid patch of the file.*/ |
| 377 | end=OP_MIN(begin+OP_PAGE_SIZE_MAX-1,original_end); |
| 378 | } |
| 379 | while(_offset<0); |
| 380 | if(preferred_found)*_sr=*&preferred_sr; |
| 381 | return 0; |
| 382 | } |
| 383 |
| 384 | /*Find the last page beginning before _offset with the given serial number and |
| 385 | a valid granule position. |
| 386 | Unlike the above search, this continues until it finds such a page, but does |
| 387 | not stray outside the current link. |
| 388 | We could implement it (inefficiently) by calling op_get_prev_page_serial() |
| 389 | repeatedly until it returned a page that had both our preferred serial |
| 390 | number and a valid granule position, but doing it with a separate function |
| 391 | allows us to avoid repeatedly re-scanning valid pages from other streams as |
| 392 | we seek-back-and-read-forward. |
| 393 | [out] _gp: Returns the granule position of the page that was found on |
| 394 | success. |
| 395 | _offset: The _offset before which to find a page. |
| 396 | Any page returned will consist of data entirely before _offset. |
| 397 | _serialno: The target serial number. |
| 398 | _serialnos: The list of serial numbers in the link that contains the |
| 399 | preferred serial number. |
| 400 | _nserialnos: The number of serial numbers in the current link. |
| 401 | Return: The offset of the page on success, or a negative value on failure. |
| 402 | OP_EREAD: Failed to read more data (error or EOF). |
| 403 | OP_EBADLINK: We couldn't find a page even after seeking back past the |
| 404 | beginning of the link.*/ |
| 405 | static opus_int64 op_get_last_page(OggOpusFile *_of,ogg_int64_t *_gp, |
| 406 | opus_int64 _offset,ogg_uint32_t _serialno, |
| 407 | const ogg_uint32_t *_serialnos,int _nserialnos){ |
| 408 | ogg_page og; |
| 409 | ogg_int64_t gp; |
| 410 | opus_int64 begin; |
| 411 | opus_int64 end; |
| 412 | opus_int64 original_end; |
| 413 | opus_int32 chunk_size; |
| 414 | /*The target serial number must belong to the current link.*/ |
| 415 | OP_ASSERT(op_lookup_serialno(_serialno,_serialnos,_nserialnos)); |
| 416 | original_end=end=begin=_offset; |
| 417 | _offset=-1; |
| 418 | /*We shouldn't have to initialize gp, but gcc is too dumb to figure out that |
| 419 | ret>=0 implies we entered the if(page_gp!=-1) block at least once.*/ |
| 420 | gp=-1; |
| 421 | chunk_size=OP_CHUNK_SIZE; |
| 422 | do{ |
| 423 | int left_link; |
| 424 | int ret; |
| 425 | OP_ASSERT(chunk_size>=OP_PAGE_SIZE_MAX); |
| 426 | begin=OP_MAX(begin-chunk_size,0); |
| 427 | ret=op_seek_helper(_of,begin); |
| 428 | if(OP_UNLIKELY(ret<0))return ret; |
| 429 | left_link=0; |
| 430 | while(_of->offset<end){ |
| 431 | opus_int64 llret; |
| 432 | ogg_uint32_t serialno; |
| 433 | llret=op_get_next_page(_of,&og,end); |
| 434 | if(OP_UNLIKELY(llret<OP_FALSE))return llret; |
| 435 | else if(llret==OP_FALSE)break; |
| 436 | serialno=ogg_page_serialno(&og); |
| 437 | if(serialno==_serialno){ |
| 438 | ogg_int64_t page_gp; |
| 439 | /*The page is from the right stream...*/ |
| 440 | page_gp=ogg_page_granulepos(&og); |
| 441 | if(page_gp!=-1){ |
| 442 | /*And has a valid granule position. |
| 443 | Let's remember it.*/ |
| 444 | _offset=llret; |
| 445 | gp=page_gp; |
| 446 | } |
| 447 | } |
| 448 | else if(OP_UNLIKELY(!op_lookup_serialno(serialno, |
| 449 | _serialnos,_nserialnos))){ |
| 450 | /*We fell off the start of the link, which means we don't need to keep |
| 451 | seeking any farther back.*/ |
| 452 | left_link=1; |
| 453 | } |
| 454 | } |
| 455 | /*We started from at or before the beginning of the link and found nothing. |
| 456 | This should be impossible unless the contents of the source changed out |
| 457 | from under us after we read from it.*/ |
| 458 | if((OP_UNLIKELY(left_link)||OP_UNLIKELY(!begin))&&OP_UNLIKELY(_offset<0)){ |
| 459 | return OP_EBADLINK; |
| 460 | } |
| 461 | /*Bump up the chunk size. |
| 462 | This is mildly helpful when seeks are very expensive (http).*/ |
| 463 | chunk_size=OP_MIN(2*chunk_size,OP_CHUNK_SIZE_MAX); |
| 464 | /*Avoid quadratic complexity if we hit an invalid patch of the file.*/ |
| 465 | end=OP_MIN(begin+OP_PAGE_SIZE_MAX-1,original_end); |
| 466 | } |
| 467 | while(_offset<0); |
| 468 | *_gp=gp; |
| 469 | return _offset; |
| 470 | } |
| 471 |
| 472 | /*Uses the local ogg_stream storage in _of. |
| 473 | This is important for non-streaming input sources.*/ |
| 474 | static int op_fetch_headers_impl(OggOpusFile *_of,OpusHead *_head, |
| 475 | OpusTags *_tags,ogg_uint32_t **_serialnos,int *_nserialnos, |
| 476 | int *_cserialnos,ogg_page *_og){ |
| 477 | ogg_packet op; |
| 478 | int ret; |
| 479 | if(_serialnos!=NULL)*_nserialnos=0; |
| 480 | /*Extract the serialnos of all BOS pages plus the first set of Opus headers |
| 481 | we see in the link.*/ |
| 482 | while(ogg_page_bos(_og)){ |
| 483 | if(_serialnos!=NULL){ |
| 484 | if(OP_UNLIKELY(op_lookup_page_serialno(_og,*_serialnos,*_nserialnos))){ |
| 485 | /*A dupe serialnumber in an initial header packet set==invalid stream.*/ |
| 486 | return OP_EBADHEADER; |
| 487 | } |
| 488 | ret=op_add_serialno(_og,_serialnos,_nserialnos,_cserialnos); |
| 489 | if(OP_UNLIKELY(ret<0))return ret; |
| 490 | } |
| 491 | if(_of->ready_state<OP_STREAMSET){ |
| 492 | /*We don't have an Opus stream in this link yet, so begin prospective |
| 493 | stream setup. |
| 494 | We need a stream to get packets.*/ |
| 495 | ogg_stream_reset_serialno(&_of->os,ogg_page_serialno(_og)); |
| 496 | ogg_stream_pagein(&_of->os,_og); |
| 497 | if(OP_LIKELY(ogg_stream_packetout(&_of->os,&op)>0)){ |
| 498 | ret=opus_head_parse(_head,op.packet,op.bytes); |
| 499 | /*If it's just a stream type we don't recognize, ignore it.*/ |
| 500 | if(ret==OP_ENOTFORMAT)continue; |
| 501 | /*Everything else is fatal.*/ |
| 502 | if(OP_UNLIKELY(ret<0))return ret; |
| 503 | /*Found a valid Opus header. |
| 504 | Continue setup.*/ |
| 505 | _of->ready_state=OP_STREAMSET; |
| 506 | } |
| 507 | } |
| 508 | /*Get the next page. |
| 509 | No need to clamp the boundary offset against _of->end, as all errors |
| 510 | become OP_ENOTFORMAT.*/ |
| 511 | if(OP_UNLIKELY(op_get_next_page(_of,_og, |
| 512 | OP_ADV_OFFSET(_of->offset,OP_CHUNK_SIZE))<0)){ |
| 513 | return OP_ENOTFORMAT; |
| 514 | } |
| 515 | /*If this page also belongs to our Opus stream, submit it and break.*/ |
| 516 | if(_of->ready_state==OP_STREAMSET |
| 517 | &&_of->os.serialno==ogg_page_serialno(_og)){ |
| 518 | ogg_stream_pagein(&_of->os,_og); |
| 519 | break; |
| 520 | } |
| 521 | } |
| 522 | if(OP_UNLIKELY(_of->ready_state!=OP_STREAMSET))return OP_ENOTFORMAT; |
| 523 | /*Loop getting packets.*/ |
| 524 | for(;;){ |
| 525 | switch(ogg_stream_packetout(&_of->os,&op)){ |
| 526 | case 0:{ |
| 527 | /*Loop getting pages.*/ |
| 528 | for(;;){ |
| 529 | /*No need to clamp the boundary offset against _of->end, as all |
| 530 | errors become OP_EBADHEADER.*/ |
| 531 | if(OP_UNLIKELY(op_get_next_page(_of,_og, |
| 532 | OP_ADV_OFFSET(_of->offset,OP_CHUNK_SIZE))<0)){ |
| 533 | return OP_EBADHEADER; |
| 534 | } |
| 535 | /*If this page belongs to the correct stream, go parse it.*/ |
| 536 | if(_of->os.serialno==ogg_page_serialno(_og)){ |
| 537 | ogg_stream_pagein(&_of->os,_og); |
| 538 | break; |
| 539 | } |
| 540 | /*If the link ends before we see the Opus comment header, abort.*/ |
| 541 | if(OP_UNLIKELY(ogg_page_bos(_og)))return OP_EBADHEADER; |
| 542 | /*Otherwise, keep looking.*/ |
| 543 | } |
| 544 | }break; |
| 545 | /*We shouldn't get a hole in the headers!*/ |
| 546 | case -1:return OP_EBADHEADER; |
| 547 | default:{ |
| 548 | /*Got a packet. |
| 549 | It should be the comment header.*/ |
| 550 | ret=opus_tags_parse(_tags,op.packet,op.bytes); |
| 551 | if(OP_UNLIKELY(ret<0))return ret; |
| 552 | /*Make sure the page terminated at the end of the comment header. |
| 553 | If there is another packet on the page, or part of a packet, then |
| 554 | reject the stream. |
| 555 | Otherwise seekable sources won't be able to seek back to the start |
| 556 | properly.*/ |
| 557 | ret=ogg_stream_packetout(&_of->os,&op); |
| 558 | if(OP_UNLIKELY(ret!=0) |
| 559 | ||OP_UNLIKELY(_og->header[_og->header_len-1]==255)){ |
| 560 | /*If we fail, the caller assumes our tags are uninitialized.*/ |
| 561 | opus_tags_clear(_tags); |
| 562 | return OP_EBADHEADER; |
| 563 | } |
| 564 | return 0; |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 |
| 570 | static int op_fetch_headers(OggOpusFile *_of,OpusHead *_head, |
| 571 | OpusTags *_tags,ogg_uint32_t **_serialnos,int *_nserialnos, |
| 572 | int *_cserialnos,ogg_page *_og){ |
| 573 | ogg_page og; |
| 574 | int ret; |
| 575 | if(!_og){ |
| 576 | /*No need to clamp the boundary offset against _of->end, as all errors |
| 577 | become OP_ENOTFORMAT.*/ |
| 578 | if(OP_UNLIKELY(op_get_next_page(_of,&og, |
| 579 | OP_ADV_OFFSET(_of->offset,OP_CHUNK_SIZE))<0)){ |
| 580 | return OP_ENOTFORMAT; |
| 581 | } |
| 582 | _og=&og; |
| 583 | } |
| 584 | _of->ready_state=OP_OPENED; |
| 585 | ret=op_fetch_headers_impl(_of,_head,_tags,_serialnos,_nserialnos, |
| 586 | _cserialnos,_og); |
| 587 | /*Revert back from OP_STREAMSET to OP_OPENED on failure, to prevent |
| 588 | double-free of the tags in an unseekable stream.*/ |
| 589 | if(OP_UNLIKELY(ret<0))_of->ready_state=OP_OPENED; |
| 590 | return ret; |
| 591 | } |
| 592 |
| 593 | /*Granule position manipulation routines. |
| 594 | A granule position is defined to be an unsigned 64-bit integer, with the |
| 595 | special value -1 in two's complement indicating an unset or invalid granule |
| 596 | position. |
| 597 | We are not guaranteed to have an unsigned 64-bit type, so we construct the |
| 598 | following routines that |
| 599 | a) Properly order negative numbers as larger than positive numbers, and |
| 600 | b) Check for underflow or overflow past the special -1 value. |
| 601 | This lets us operate on the full, valid range of granule positions in a |
| 602 | consistent and safe manner. |
| 603 | This full range is organized into distinct regions: |
| 604 | [ -1 (invalid) ][ 0 ... OP_INT64_MAX ][ OP_INT64_MIN ... -2 ][-1 (invalid) ] |
| 605 |
| 606 | No one should actually use granule positions so large that they're negative, |
| 607 | even if they are technically valid, as very little software handles them |
| 608 | correctly (including most of Xiph.Org's). |
| 609 | This library also refuses to support durations so large they won't fit in a |
| 610 | signed 64-bit integer (to avoid exposing this mess to the application, and |
| 611 | to simplify a good deal of internal arithmetic), so the only way to use them |
| 612 | successfully is if pcm_start is very large. |
| 613 | This means there isn't anything you can do with negative granule positions |
| 614 | that you couldn't have done with purely non-negative ones. |
| 615 | The main purpose of these routines is to allow us to think very explicitly |
| 616 | about the possible failure cases of all granule position manipulations.*/ |
| 617 |
| 618 | /*Safely adds a small signed integer to a valid (not -1) granule position. |
| 619 | The result can use the full 64-bit range of values (both positive and |
| 620 | negative), but will fail on overflow (wrapping past -1; wrapping past |
| 621 | OP_INT64_MAX is explicitly okay). |
| 622 | [out] _dst_gp: The resulting granule position. |
| 623 | Only modified on success. |
| 624 | _src_gp: The granule position to add to. |
| 625 | This must not be -1. |
| 626 | _delta: The amount to add. |
| 627 | This is allowed to be up to 32 bits to support the maximum |
| 628 | duration of a single Ogg page (255 packets * 120 ms per |
| 629 | packet == 1,468,800 samples at 48 kHz). |
| 630 | Return: 0 on success, or OP_EINVAL if the result would wrap around past -1.*/ |
| 631 | static int op_granpos_add(ogg_int64_t *_dst_gp,ogg_int64_t _src_gp, |
| 632 | opus_int32 _delta){ |
| 633 | /*The code below handles this case correctly, but there's no reason we |
| 634 | should ever be called with these values, so make sure we aren't.*/ |
| 635 | OP_ASSERT(_src_gp!=-1); |
| 636 | if(_delta>0){ |
| 637 | /*Adding this amount to the granule position would overflow its 64-bit |
| 638 | range.*/ |
| 639 | if(OP_UNLIKELY(_src_gp<0)&&OP_UNLIKELY(_src_gp>=-1-_delta))return OP_EINVAL; |
| 640 | if(OP_UNLIKELY(_src_gp>OP_INT64_MAX-_delta)){ |
| 641 | /*Adding this amount to the granule position would overflow the positive |
| 642 | half of its 64-bit range. |
| 643 | Since signed overflow is undefined in C, do it in a way the compiler |
| 644 | isn't allowed to screw up.*/ |
| 645 | _delta-=(opus_int32)(OP_INT64_MAX-_src_gp)+1; |
| 646 | _src_gp=OP_INT64_MIN; |
| 647 | } |
| 648 | } |
| 649 | else if(_delta<0){ |
| 650 | /*Subtracting this amount from the granule position would underflow its |
| 651 | 64-bit range.*/ |
| 652 | if(_src_gp>=0&&OP_UNLIKELY(_src_gp<-_delta))return OP_EINVAL; |
| 653 | if(OP_UNLIKELY(_src_gp<OP_INT64_MIN-_delta)){ |
| 654 | /*Subtracting this amount from the granule position would underflow the |
| 655 | negative half of its 64-bit range. |
| 656 | Since signed underflow is undefined in C, do it in a way the compiler |
| 657 | isn't allowed to screw up.*/ |
| 658 | _delta+=(opus_int32)(_src_gp-OP_INT64_MIN)+1; |
| 659 | _src_gp=OP_INT64_MAX; |
| 660 | } |
| 661 | } |
| 662 | *_dst_gp=_src_gp+_delta; |
| 663 | return 0; |
| 664 | } |
| 665 |
| 666 | /*Safely computes the difference between two granule positions. |
| 667 | The difference must fit in a signed 64-bit integer, or the function fails. |
| 668 | It correctly handles the case where the granule position has wrapped around |
| 669 | from positive values to negative ones. |
| 670 | [out] _delta: The difference between the granule positions. |
| 671 | Only modified on success. |
| 672 | _gp_a: The granule position to subtract from. |
| 673 | This must not be -1. |
| 674 | _gp_b: The granule position to subtract. |
| 675 | This must not be -1. |
| 676 | Return: 0 on success, or OP_EINVAL if the result would not fit in a signed |
| 677 | 64-bit integer.*/ |
| 678 | static int op_granpos_diff(ogg_int64_t *_delta, |
| 679 | ogg_int64_t _gp_a,ogg_int64_t _gp_b){ |
| 680 | int gp_a_negative; |
| 681 | int gp_b_negative; |
| 682 | /*The code below handles these cases correctly, but there's no reason we |
| 683 | should ever be called with these values, so make sure we aren't.*/ |
| 684 | OP_ASSERT(_gp_a!=-1); |
| 685 | OP_ASSERT(_gp_b!=-1); |
| 686 | gp_a_negative=OP_UNLIKELY(_gp_a<0); |
| 687 | gp_b_negative=OP_UNLIKELY(_gp_b<0); |
| 688 | if(OP_UNLIKELY(gp_a_negative^gp_b_negative)){ |
| 689 | ogg_int64_t da; |
| 690 | ogg_int64_t db; |
| 691 | if(gp_a_negative){ |
| 692 | /*_gp_a has wrapped to a negative value but _gp_b hasn't: the difference |
| 693 | should be positive.*/ |
| 694 | /*Step 1: Handle wrapping.*/ |
| 695 | /*_gp_a < 0 => da < 0.*/ |
| 696 | da=(OP_INT64_MIN-_gp_a)-1; |
| 697 | /*_gp_b >= 0 => db >= 0.*/ |
| 698 | db=OP_INT64_MAX-_gp_b; |
| 699 | /*Step 2: Check for overflow.*/ |
| 700 | if(OP_UNLIKELY(OP_INT64_MAX+da<db))return OP_EINVAL; |
| 701 | *_delta=db-da; |
| 702 | } |
| 703 | else{ |
| 704 | /*_gp_b has wrapped to a negative value but _gp_a hasn't: the difference |
| 705 | should be negative.*/ |
| 706 | /*Step 1: Handle wrapping.*/ |
| 707 | /*_gp_a >= 0 => da <= 0*/ |
| 708 | da=_gp_a+OP_INT64_MIN; |
| 709 | /*_gp_b < 0 => db <= 0*/ |
| 710 | db=OP_INT64_MIN-_gp_b; |
| 711 | /*Step 2: Check for overflow.*/ |
| 712 | if(OP_UNLIKELY(da<OP_INT64_MIN-db))return OP_EINVAL; |
| 713 | *_delta=da+db; |
| 714 | } |
| 715 | } |
| 716 | else *_delta=_gp_a-_gp_b; |
| 717 | return 0; |
| 718 | } |
| 719 |
| 720 | static int op_granpos_cmp(ogg_int64_t _gp_a,ogg_int64_t _gp_b){ |
| 721 | /*The invalid granule position -1 should behave like NaN: neither greater |
| 722 | than nor less than any other granule position, nor equal to any other |
| 723 | granule position, including itself. |
| 724 | However, that means there isn't anything we could sensibly return from this |
| 725 | function for it.*/ |
| 726 | OP_ASSERT(_gp_a!=-1); |
| 727 | OP_ASSERT(_gp_b!=-1); |
| 728 | /*Handle the wrapping cases.*/ |
| 729 | if(OP_UNLIKELY(_gp_a<0)){ |
| 730 | if(_gp_b>=0)return 1; |
| 731 | /*Else fall through.*/ |
| 732 | } |
| 733 | else if(OP_UNLIKELY(_gp_b<0))return -1; |
| 734 | /*No wrapping case.*/ |
| 735 | return (_gp_a>_gp_b)-(_gp_b>_gp_a); |
| 736 | } |
| 737 |
| 738 | /*Returns the duration of the packet (in samples at 48 kHz), or a negative |
| 739 | value on error.*/ |
| 740 | static int op_get_packet_duration(const unsigned char *_data,int _len){ |
| 741 | int nframes; |
| 742 | int frame_size; |
| 743 | int nsamples; |
| 744 | nframes=opus_packet_get_nb_frames(_data,_len); |
| 745 | if(OP_UNLIKELY(nframes<0))return OP_EBADPACKET; |
| 746 | frame_size=opus_packet_get_samples_per_frame(_data,48000); |
| 747 | nsamples=nframes*frame_size; |
| 748 | if(OP_UNLIKELY(nsamples>120*48))return OP_EBADPACKET; |
| 749 | return nsamples; |
| 750 | } |
| 751 |
| 752 | /*This function more properly belongs in info.c, but we define it here to allow |
| 753 | the static granule position manipulation functions to remain static.*/ |
| 754 | ogg_int64_t opus_granule_sample(const OpusHead *_head,ogg_int64_t _gp){ |
| 755 | opus_int32 pre_skip; |
| 756 | pre_skip=_head->pre_skip; |
| 757 | if(_gp!=-1&&op_granpos_add(&_gp,_gp,-pre_skip))_gp=-1; |
| 758 | return _gp; |
| 759 | } |
| 760 |
| 761 | /*Grab all the packets currently in the stream state, and compute their |
| 762 | durations. |
| 763 | _of->op_count is set to the number of packets collected. |
| 764 | [out] _durations: Returns the durations of the individual packets. |
| 765 | Return: The total duration of all packets, or OP_HOLE if there was a hole.*/ |
| 766 | static opus_int32 op_collect_audio_packets(OggOpusFile *_of, |
| 767 | int _durations[255]){ |
| 768 | opus_int32 total_duration; |
| 769 | int op_count; |
| 770 | /*Count the durations of all packets in the page.*/ |
| 771 | op_count=0; |
| 772 | total_duration=0; |
| 773 | for(;;){ |
| 774 | int ret; |
| 775 | /*This takes advantage of undocumented libogg behavior that returned |
| 776 | ogg_packet buffers are valid at least until the next page is |
| 777 | submitted. |
| 778 | Relying on this is not too terrible, as _none_ of the Ogg memory |
| 779 | ownership/lifetime rules are well-documented. |
| 780 | But I can read its code and know this will work.*/ |
| 781 | ret=ogg_stream_packetout(&_of->os,_of->op+op_count); |
| 782 | if(!ret)break; |
| 783 | if(OP_UNLIKELY(ret<0)){ |
| 784 | /*We shouldn't get holes in the middle of pages.*/ |
| 785 | OP_ASSERT(op_count==0); |
| 786 | /*Set the return value and break out of the loop. |
| 787 | We want to make sure op_count gets set to 0, because we've ingested a |
| 788 | page, so any previously loaded packets are now invalid.*/ |
| 789 | total_duration=OP_HOLE; |
| 790 | break; |
| 791 | } |
| 792 | /*Unless libogg is broken, we can't get more than 255 packets from a |
| 793 | single page.*/ |
| 794 | OP_ASSERT(op_count<255); |
| 795 | _durations[op_count]=op_get_packet_duration(_of->op[op_count].packet, |
| 796 | _of->op[op_count].bytes); |
| 797 | if(OP_LIKELY(_durations[op_count]>0)){ |
| 798 | /*With at most 255 packets on a page, this can't overflow.*/ |
| 799 | total_duration+=_durations[op_count++]; |
| 800 | } |
| 801 | /*Ignore packets with an invalid TOC sequence.*/ |
| 802 | else if(op_count>0){ |
| 803 | /*But save the granule position, if there was one.*/ |
| 804 | _of->op[op_count-1].granulepos=_of->op[op_count].granulepos; |
| 805 | } |
| 806 | } |
| 807 | _of->op_pos=0; |
| 808 | _of->op_count=op_count; |
| 809 | return total_duration; |
| 810 | } |
| 811 |
| 812 | /*Starting from current cursor position, get the initial PCM offset of the next |
| 813 | page. |
| 814 | This also validates the granule position on the first page with a completed |
| 815 | audio data packet, as required by the spec. |
| 816 | If this link is completely empty (no pages with completed packets), then this |
| 817 | function sets pcm_start=pcm_end=0 and returns the BOS page of the next link |
| 818 | (if any). |
| 819 | In the seekable case, we initialize pcm_end=-1 before calling this function, |
| 820 | so that later we can detect that the link was empty before calling |
| 821 | op_find_final_pcm_offset(). |
| 822 | [inout] _link: The link for which to find pcm_start. |
| 823 | [out] _og: Returns the BOS page of the next link if this link was empty. |
| 824 | In the unseekable case, we can then feed this to |
| 825 | op_fetch_headers() to start the next link. |
| 826 | The caller may pass NULL (e.g., for seekable streams), in |
| 827 | which case this page will be discarded. |
| 828 | Return: 0 on success, 1 if there is a buffered BOS page available, or a |
| 829 | negative value on unrecoverable error.*/ |
| 830 | static int op_find_initial_pcm_offset(OggOpusFile *_of, |
| 831 | OggOpusLink *_link,ogg_page *_og){ |
| 832 | ogg_page og; |
| 833 | ogg_int64_t pcm_start; |
| 834 | ogg_int64_t prev_packet_gp; |
| 835 | ogg_int64_t cur_page_gp; |
| 836 | ogg_uint32_t serialno; |
| 837 | opus_int32 total_duration; |
| 838 | int durations[255]; |
| 839 | int cur_page_eos; |
| 840 | int op_count; |
| 841 | int pi; |
| 842 | if(_og==NULL)_og=&og; |
| 843 | serialno=_of->os.serialno; |
| 844 | op_count=0; |
| 845 | /*We shouldn't have to initialize total_duration, but gcc is too dumb to |
| 846 | figure out that op_count>0 implies we've been through the whole loop at |
| 847 | least once.*/ |
| 848 | total_duration=0; |
| 849 | do{ |
| 850 | opus_int64 llret; |
| 851 | llret=op_get_next_page(_of,_og,_of->end); |
| 852 | /*We should get a page unless the file is truncated or mangled. |
| 853 | Otherwise there are no audio data packets in the whole logical stream.*/ |
| 854 | if(OP_UNLIKELY(llret<0)){ |
| 855 | /*Fail if there was a read error.*/ |
| 856 | if(llret<OP_FALSE)return (int)llret; |
| 857 | /*Fail if the pre-skip is non-zero, since it's asking us to skip more |
| 858 | samples than exist.*/ |
| 859 | if(_link->head.pre_skip>0)return OP_EBADTIMESTAMP; |
| 860 | /*Set pcm_end and end_offset so we can skip the call to |
| 861 | op_find_final_pcm_offset().*/ |
| 862 | _link->pcm_start=_link->pcm_end=0; |
| 863 | _link->end_offset=_link->data_offset; |
| 864 | return 0; |
| 865 | } |
| 866 | /*Similarly, if we hit the next link in the chain, we've gone too far.*/ |
| 867 | if(OP_UNLIKELY(ogg_page_bos(_og))){ |
| 868 | if(_link->head.pre_skip>0)return OP_EBADTIMESTAMP; |
| 869 | /*Set pcm_end and end_offset so we can skip the call to |
| 870 | op_find_final_pcm_offset().*/ |
| 871 | _link->pcm_end=_link->pcm_start=0; |
| 872 | _link->end_offset=_link->data_offset; |
| 873 | /*Tell the caller we've got a buffered page for them.*/ |
| 874 | return 1; |
| 875 | } |
| 876 | /*Ignore pages from other streams (not strictly necessary, because of the |
| 877 | checks in ogg_stream_pagein(), but saves some work).*/ |
| 878 | if(serialno!=(ogg_uint32_t)ogg_page_serialno(_og))continue; |
| 879 | ogg_stream_pagein(&_of->os,_og); |
| 880 | /*Bitrate tracking: add the header's bytes here. |
| 881 | The body bytes are counted when we consume the packets.*/ |
| 882 | _of->bytes_tracked+=_og->header_len; |
| 883 | /*Count the durations of all packets in the page.*/ |
| 884 | do total_duration=op_collect_audio_packets(_of,durations); |
| 885 | /*Ignore holes.*/ |
| 886 | while(OP_UNLIKELY(total_duration<0)); |
| 887 | op_count=_of->op_count; |
| 888 | } |
| 889 | while(op_count<=0); |
| 890 | /*We found the first page with a completed audio data packet: actually look |
| 891 | at the granule position. |
| 892 | RFC 3533 says, "A special value of -1 (in two's complement) indicates that |
| 893 | no packets finish on this page," which does not say that a granule |
| 894 | position that is NOT -1 indicates that some packets DO finish on that page |
| 895 | (even though this was the intention, libogg itself violated this intention |
| 896 | for years before we fixed it). |
| 897 | The Ogg Opus specification only imposes its start-time requirements |
| 898 | on the granule position of the first page with completed packets, |
| 899 | so we ignore any set granule positions until then.*/ |
| 900 | cur_page_gp=_of->op[op_count-1].granulepos; |
| 901 | /*But getting a packet without a valid granule position on the page is not |
| 902 | okay.*/ |
| 903 | if(cur_page_gp==-1)return OP_EBADTIMESTAMP; |
| 904 | cur_page_eos=_of->op[op_count-1].e_o_s; |
| 905 | if(OP_LIKELY(!cur_page_eos)){ |
| 906 | /*The EOS flag wasn't set. |
| 907 | Work backwards from the provided granule position to get the starting PCM |
| 908 | offset.*/ |
| 909 | if(OP_UNLIKELY(op_granpos_add(&pcm_start,cur_page_gp,-total_duration)<0)){ |
| 910 | /*The starting granule position MUST not be smaller than the amount of |
| 911 | audio on the first page with completed packets.*/ |
| 912 | return OP_EBADTIMESTAMP; |
| 913 | } |
| 914 | } |
| 915 | else{ |
| 916 | /*The first page with completed packets was also the last.*/ |
| 917 | if(OP_LIKELY(op_granpos_add(&pcm_start,cur_page_gp,-total_duration)<0)){ |
| 918 | /*If there's less audio on the page than indicated by the granule |
| 919 | position, then we're doing end-trimming, and the starting PCM offset |
| 920 | is zero by spec mandate.*/ |
| 921 | pcm_start=0; |
| 922 | /*However, the end-trimming MUST not ask us to trim more samples than |
| 923 | exist after applying the pre-skip.*/ |
| 924 | if(OP_UNLIKELY(op_granpos_cmp(cur_page_gp,_link->head.pre_skip)<0)){ |
| 925 | return OP_EBADTIMESTAMP; |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | /*Timestamp the individual packets.*/ |
| 930 | prev_packet_gp=pcm_start; |
| 931 | for(pi=0;pi<op_count;pi++){ |
| 932 | if(cur_page_eos){ |
| 933 | ogg_int64_t diff; |
| 934 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff,cur_page_gp,prev_packet_gp)); |
| 935 | diff=durations[pi]-diff; |
| 936 | /*If we have samples to trim...*/ |
| 937 | if(diff>0){ |
| 938 | /*If we trimmed the entire packet, stop (the spec says encoders |
| 939 | shouldn't do this, but we support it anyway).*/ |
| 940 | if(OP_UNLIKELY(diff>durations[pi]))break; |
| 941 | _of->op[pi].granulepos=prev_packet_gp=cur_page_gp; |
| 942 | /*Move the EOS flag to this packet, if necessary, so we'll trim the |
| 943 | samples.*/ |
| 944 | _of->op[pi].e_o_s=1; |
| 945 | continue; |
| 946 | } |
| 947 | } |
| 948 | /*Update the granule position as normal.*/ |
| 949 | OP_ALWAYS_TRUE(!op_granpos_add(&_of->op[pi].granulepos, |
| 950 | prev_packet_gp,durations[pi])); |
| 951 | prev_packet_gp=_of->op[pi].granulepos; |
| 952 | } |
| 953 | /*Update the packet count after end-trimming.*/ |
| 954 | _of->op_count=pi; |
| 955 | _of->cur_discard_count=_link->head.pre_skip; |
| 956 | _of->prev_packet_gp=_link->pcm_start=pcm_start; |
| 957 | return 0; |
| 958 | } |
| 959 |
| 960 | /*Starting from current cursor position, get the final PCM offset of the |
| 961 | previous page. |
| 962 | This also validates the duration of the link, which, while not strictly |
| 963 | required by the spec, we need to ensure duration calculations don't |
| 964 | overflow. |
| 965 | This is only done for seekable sources. |
| 966 | We must validate that op_find_initial_pcm_offset() succeeded for this link |
| 967 | before calling this function, otherwise it will scan the entire stream |
| 968 | backwards until it reaches the start, and then fail.*/ |
| 969 | static int op_find_final_pcm_offset(OggOpusFile *_of, |
| 970 | const ogg_uint32_t *_serialnos,int _nserialnos,OggOpusLink *_link, |
| 971 | opus_int64 _offset,ogg_uint32_t _end_serialno,ogg_int64_t _end_gp, |
| 972 | ogg_int64_t *_total_duration){ |
| 973 | ogg_int64_t total_duration; |
| 974 | ogg_int64_t duration; |
| 975 | ogg_uint32_t cur_serialno; |
| 976 | /*For the time being, fetch end PCM offset the simple way.*/ |
| 977 | cur_serialno=_link->serialno; |
| 978 | if(_end_serialno!=cur_serialno||_end_gp==-1){ |
| 979 | _offset=op_get_last_page(_of,&_end_gp,_offset, |
| 980 | cur_serialno,_serialnos,_nserialnos); |
| 981 | if(OP_UNLIKELY(_offset<0))return (int)_offset; |
| 982 | } |
| 983 | /*At worst we should have found the first page with completed packets.*/ |
| 984 | if(OP_UNLIKELY(_offset<_link->data_offset))return OP_EBADLINK; |
| 985 | /*This implementation requires that the difference between the first and last |
| 986 | granule positions in each link be representable in a signed, 64-bit |
| 987 | number, and that each link also have at least as many samples as the |
| 988 | pre-skip requires.*/ |
| 989 | if(OP_UNLIKELY(op_granpos_diff(&duration,_end_gp,_link->pcm_start)<0) |
| 990 | ||OP_UNLIKELY(duration<_link->head.pre_skip)){ |
| 991 | return OP_EBADTIMESTAMP; |
| 992 | } |
| 993 | /*We also require that the total duration be representable in a signed, |
| 994 | 64-bit number.*/ |
| 995 | duration-=_link->head.pre_skip; |
| 996 | total_duration=*_total_duration; |
| 997 | if(OP_UNLIKELY(OP_INT64_MAX-duration<total_duration))return OP_EBADTIMESTAMP; |
| 998 | *_total_duration=total_duration+duration; |
| 999 | _link->pcm_end=_end_gp; |
| 1000 | _link->end_offset=_offset; |
| 1001 | return 0; |
| 1002 | } |
| 1003 |
| 1004 | /*Rescale the number _x from the range [0,_from] to [0,_to]. |
| 1005 | _from and _to must be positive.*/ |
| 1006 | static opus_int64 op_rescale64(opus_int64 _x,opus_int64 _from,opus_int64 _to){ |
| 1007 | opus_int64 frac; |
| 1008 | opus_int64 ret; |
| 1009 | int i; |
| 1010 | if(_x>=_from)return _to; |
| 1011 | if(_x<=0)return 0; |
| 1012 | frac=0; |
| 1013 | for(i=0;i<63;i++){ |
| 1014 | frac<<=1; |
| 1015 | OP_ASSERT(_x<=_from); |
| 1016 | if(_x>=_from>>1){ |
| 1017 | _x-=_from-_x; |
| 1018 | frac|=1; |
| 1019 | } |
| 1020 | else _x<<=1; |
| 1021 | } |
| 1022 | ret=0; |
| 1023 | for(i=0;i<63;i++){ |
| 1024 | if(frac&1)ret=(ret&_to&1)+(ret>>1)+(_to>>1); |
| 1025 | else ret>>=1; |
| 1026 | frac>>=1; |
| 1027 | } |
| 1028 | return ret; |
| 1029 | } |
| 1030 |
| 1031 | /*The minimum granule position spacing allowed for making predictions. |
| 1032 | This corresponds to about 1 second of audio at 48 kHz for both Opus and |
| 1033 | Vorbis, or one keyframe interval in Theora with the default keyframe spacing |
| 1034 | of 256.*/ |
| 1035 | #define OP_GP_SPACING_MIN (48000) |
| 1036 |
| 1037 | /*Try to estimate the location of the next link using the current seek |
| 1038 | records, assuming the initial granule position of any streams we've found is |
| 1039 | 0.*/ |
| 1040 | static opus_int64 op_predict_link_start(const OpusSeekRecord *_sr,int _nsr, |
| 1041 | opus_int64 _searched,opus_int64 _end_searched,opus_int32 _bias){ |
| 1042 | opus_int64 bisect; |
| 1043 | int sri; |
| 1044 | int srj; |
| 1045 | /*Require that we be at least OP_CHUNK_SIZE from the end. |
| 1046 | We don't require that we be at least OP_CHUNK_SIZE from the beginning, |
| 1047 | because if we are we'll just scan forward without seeking.*/ |
| 1048 | _end_searched-=OP_CHUNK_SIZE; |
| 1049 | if(_searched>=_end_searched)return -1; |
| 1050 | bisect=_end_searched; |
| 1051 | for(sri=0;sri<_nsr;sri++){ |
| 1052 | ogg_int64_t gp1; |
| 1053 | ogg_int64_t gp2_min; |
| 1054 | ogg_uint32_t serialno1; |
| 1055 | opus_int64 offset1; |
| 1056 | /*If the granule position is negative, either it's invalid or we'd cause |
| 1057 | overflow.*/ |
| 1058 | gp1=_sr[sri].gp; |
| 1059 | if(gp1<0)continue; |
| 1060 | /*We require some minimum distance between granule positions to make an |
| 1061 | estimate. |
| 1062 | We don't actually know what granule position scheme is being used, |
| 1063 | because we have no idea what kind of stream these came from. |
| 1064 | Therefore we require a minimum spacing between them, with the |
| 1065 | expectation that while bitrates and granule position increments might |
| 1066 | vary locally in quite complex ways, they are globally smooth.*/ |
| 1067 | if(OP_UNLIKELY(op_granpos_add(&gp2_min,gp1,OP_GP_SPACING_MIN)<0)){ |
| 1068 | /*No granule position would satisfy us.*/ |
| 1069 | continue; |
| 1070 | } |
| 1071 | offset1=_sr[sri].offset; |
| 1072 | serialno1=_sr[sri].serialno; |
| 1073 | for(srj=sri;srj-->0;){ |
| 1074 | ogg_int64_t gp2; |
| 1075 | opus_int64 offset2; |
| 1076 | opus_int64 num; |
| 1077 | ogg_int64_t den; |
| 1078 | ogg_int64_t ipart; |
| 1079 | gp2=_sr[srj].gp; |
| 1080 | if(gp2<gp2_min)continue; |
| 1081 | /*Oh, and also make sure these came from the same stream.*/ |
| 1082 | if(_sr[srj].serialno!=serialno1)continue; |
| 1083 | offset2=_sr[srj].offset; |
| 1084 | /*For once, we can subtract with impunity.*/ |
| 1085 | den=gp2-gp1; |
| 1086 | if (den == 0) { |
| 1087 | return -1; |
| 1088 | } |
| 1089 | ipart=gp2/den; |
| 1090 | num=offset2-offset1; |
| 1091 | OP_ASSERT(num>0); |
| 1092 | if(ipart>0&&(offset2-_searched)/ipart<num)continue; |
| 1093 | offset2-=ipart*num; |
| 1094 | gp2-=ipart*den; |
| 1095 | offset2-=op_rescale64(gp2,den,num)-_bias; |
| 1096 | if(offset2<_searched)continue; |
| 1097 | bisect=OP_MIN(bisect,offset2); |
| 1098 | break; |
| 1099 | } |
| 1100 | } |
| 1101 | return bisect>=_end_searched?-1:bisect; |
| 1102 | } |
| 1103 |
| 1104 | /*Finds each bitstream link, one at a time, using a bisection search. |
| 1105 | This has to begin by knowing the offset of the first link's initial page.*/ |
| 1106 | static int op_bisect_forward_serialno(OggOpusFile *_of, |
| 1107 | opus_int64 _searched,OpusSeekRecord *_sr,int _csr, |
| 1108 | ogg_uint32_t **_serialnos,int *_nserialnos,int *_cserialnos){ |
| 1109 | ogg_page og; |
| 1110 | OggOpusLink *links; |
| 1111 | int nlinks; |
| 1112 | int clinks; |
| 1113 | ogg_uint32_t *serialnos; |
| 1114 | int nserialnos; |
| 1115 | ogg_int64_t total_duration; |
| 1116 | int nsr; |
| 1117 | int ret; |
| 1118 | links=_of->links; |
| 1119 | nlinks=clinks=_of->nlinks; |
| 1120 | total_duration=0; |
| 1121 | /*We start with one seek record, for the last page in the file. |
| 1122 | We build up a list of records for places we seek to during link |
| 1123 | enumeration. |
| 1124 | This list is kept sorted in reverse order. |
| 1125 | We only care about seek locations that were _not_ in the current link, |
| 1126 | therefore we can add them one at a time to the end of the list as we |
| 1127 | improve the lower bound on the location where the next link starts.*/ |
| 1128 | nsr=1; |
| 1129 | for(;;){ |
| 1130 | opus_int64 end_searched; |
| 1131 | opus_int64 bisect; |
| 1132 | opus_int64 next; |
| 1133 | opus_int64 last; |
| 1134 | ogg_int64_t end_offset; |
| 1135 | ogg_int64_t end_gp; |
| 1136 | int sri; |
| 1137 | serialnos=*_serialnos; |
| 1138 | nserialnos=*_nserialnos; |
| 1139 | if(OP_UNLIKELY(nlinks>=clinks)){ |
| 1140 | if(OP_UNLIKELY(clinks>INT_MAX-1>>1))return OP_EFAULT; |
| 1141 | clinks=2*clinks+1; |
| 1142 | OP_ASSERT(nlinks<clinks); |
| 1143 | links=(OggOpusLink *)_ogg_realloc(links,sizeof(*links)*clinks); |
| 1144 | if(OP_UNLIKELY(links==NULL))return OP_EFAULT; |
| 1145 | _of->links=links; |
| 1146 | } |
| 1147 | /*Invariants: |
| 1148 | We have the headers and serial numbers for the link beginning at 'begin'. |
| 1149 | We have the offset and granule position of the last page in the file |
| 1150 | (potentially not a page we care about).*/ |
| 1151 | /*Scan the seek records we already have to save us some bisection.*/ |
| 1152 | for(sri=0;sri<nsr;sri++){ |
| 1153 | if(op_lookup_serialno(_sr[sri].serialno,serialnos,nserialnos))break; |
| 1154 | } |
| 1155 | /*Is the last page in our current list of serial numbers?*/ |
| 1156 | if(sri<=0)break; |
| 1157 | /*Last page wasn't found. |
| 1158 | We have at least one more link.*/ |
| 1159 | last=-1; |
| 1160 | end_searched=_sr[sri-1].search_start; |
| 1161 | next=_sr[sri-1].offset; |
| 1162 | end_gp=-1; |
| 1163 | if(sri<nsr){ |
| 1164 | _searched=_sr[sri].offset+_sr[sri].size; |
| 1165 | if(_sr[sri].serialno==links[nlinks-1].serialno){ |
| 1166 | end_gp=_sr[sri].gp; |
| 1167 | end_offset=_sr[sri].offset; |
| 1168 | } |
| 1169 | } |
| 1170 | nsr=sri; |
| 1171 | bisect=-1; |
| 1172 | /*If we've already found the end of at least one link, try to pick the |
| 1173 | first bisection point at twice the average link size. |
| 1174 | This is a good choice for files with lots of links that are all about the |
| 1175 | same size.*/ |
| 1176 | if(nlinks>1){ |
| 1177 | opus_int64 last_offset; |
| 1178 | opus_int64 avg_link_size; |
| 1179 | opus_int64 upper_limit; |
| 1180 | last_offset=links[nlinks-1].offset; |
| 1181 | avg_link_size=last_offset/(nlinks-1); |
| 1182 | upper_limit=end_searched-OP_CHUNK_SIZE-avg_link_size; |
| 1183 | if(OP_LIKELY(last_offset>_searched-avg_link_size) |
| 1184 | &&OP_LIKELY(last_offset<upper_limit)){ |
| 1185 | bisect=last_offset+avg_link_size; |
| 1186 | if(OP_LIKELY(bisect<upper_limit))bisect+=avg_link_size; |
| 1187 | } |
| 1188 | } |
| 1189 | /*We guard against garbage separating the last and first pages of two |
| 1190 | links below.*/ |
| 1191 | while(_searched<end_searched){ |
| 1192 | opus_int32 next_bias; |
| 1193 | /*If we don't have a better estimate, use simple bisection.*/ |
| 1194 | if(bisect==-1)bisect=_searched+(end_searched-_searched>>1); |
| 1195 | /*If we're within OP_CHUNK_SIZE of the start, scan forward.*/ |
| 1196 | if(bisect-_searched<OP_CHUNK_SIZE)bisect=_searched; |
| 1197 | /*Otherwise we're skipping data. |
| 1198 | Forget the end page, if we saw one, as we might miss a later one.*/ |
| 1199 | else end_gp=-1; |
| 1200 | ret=op_seek_helper(_of,bisect); |
| 1201 | if(OP_UNLIKELY(ret<0))return ret; |
| 1202 | last=op_get_next_page(_of,&og,_sr[nsr-1].offset); |
| 1203 | if(OP_UNLIKELY(last<OP_FALSE))return (int)last; |
| 1204 | next_bias=0; |
| 1205 | if(last==OP_FALSE)end_searched=bisect; |
| 1206 | else{ |
| 1207 | ogg_uint32_t serialno; |
| 1208 | ogg_int64_t gp; |
| 1209 | serialno=ogg_page_serialno(&og); |
| 1210 | gp=ogg_page_granulepos(&og); |
| 1211 | if(!op_lookup_serialno(serialno,serialnos,nserialnos)){ |
| 1212 | end_searched=bisect; |
| 1213 | next=last; |
| 1214 | /*In reality we should always have enough room, but be paranoid.*/ |
| 1215 | if(OP_LIKELY(nsr<_csr)){ |
| 1216 | _sr[nsr].search_start=bisect; |
| 1217 | _sr[nsr].offset=last; |
| 1218 | OP_ASSERT(_of->offset-last>=0); |
| 1219 | OP_ASSERT(_of->offset-last<=OP_PAGE_SIZE_MAX); |
| 1220 | _sr[nsr].size=(opus_int32)(_of->offset-last); |
| 1221 | _sr[nsr].serialno=serialno; |
| 1222 | _sr[nsr].gp=gp; |
| 1223 | nsr++; |
| 1224 | } |
| 1225 | } |
| 1226 | else{ |
| 1227 | _searched=_of->offset; |
| 1228 | next_bias=OP_CHUNK_SIZE; |
| 1229 | if(serialno==links[nlinks-1].serialno){ |
| 1230 | /*This page was from the stream we want, remember it. |
| 1231 | If it's the last such page in the link, we won't have to go back |
| 1232 | looking for it later.*/ |
| 1233 | end_gp=gp; |
| 1234 | end_offset=last; |
| 1235 | } |
| 1236 | } |
| 1237 | } |
| 1238 | bisect=op_predict_link_start(_sr,nsr,_searched,end_searched,next_bias); |
| 1239 | } |
| 1240 | /*Bisection point found. |
| 1241 | Get the final granule position of the previous link, assuming |
| 1242 | op_find_initial_pcm_offset() didn't already determine the link was |
| 1243 | empty.*/ |
| 1244 | if(OP_LIKELY(links[nlinks-1].pcm_end==-1)){ |
| 1245 | if(end_gp==-1){ |
| 1246 | /*If we don't know where the end page is, we'll have to seek back and |
| 1247 | look for it, starting from the end of the link.*/ |
| 1248 | end_offset=next; |
| 1249 | /*Also forget the last page we read. |
| 1250 | It won't be available after the seek.*/ |
| 1251 | last=-1; |
| 1252 | } |
| 1253 | ret=op_find_final_pcm_offset(_of,serialnos,nserialnos, |
| 1254 | links+nlinks-1,end_offset,links[nlinks-1].serialno,end_gp, |
| 1255 | &total_duration); |
| 1256 | if(OP_UNLIKELY(ret<0))return ret; |
| 1257 | } |
| 1258 | if(last!=next){ |
| 1259 | /*The last page we read was not the first page the next link. |
| 1260 | Move the cursor position to the offset of that first page. |
| 1261 | This only performs an actual seek if the first page of the next link |
| 1262 | does not start at the end of the last page from the current Opus |
| 1263 | stream with a valid granule position.*/ |
| 1264 | ret=op_seek_helper(_of,next); |
| 1265 | if(OP_UNLIKELY(ret<0))return ret; |
| 1266 | } |
| 1267 | ret=op_fetch_headers(_of,&links[nlinks].head,&links[nlinks].tags, |
| 1268 | _serialnos,_nserialnos,_cserialnos,last!=next?NULL:&og); |
| 1269 | if(OP_UNLIKELY(ret<0))return ret; |
| 1270 | links[nlinks].offset=next; |
| 1271 | links[nlinks].data_offset=_of->offset; |
| 1272 | links[nlinks].serialno=_of->os.serialno; |
| 1273 | links[nlinks].pcm_end=-1; |
| 1274 | /*This might consume a page from the next link, however the next bisection |
| 1275 | always starts with a seek.*/ |
| 1276 | ret=op_find_initial_pcm_offset(_of,links+nlinks,NULL); |
| 1277 | if(OP_UNLIKELY(ret<0))return ret; |
| 1278 | _searched=_of->offset; |
| 1279 | /*Mark the current link count so it can be cleaned up on error.*/ |
| 1280 | _of->nlinks=++nlinks; |
| 1281 | } |
| 1282 | /*Last page is in the starting serialno list, so we've reached the last link. |
| 1283 | Now find the last granule position for it (if we didn't the first time we |
| 1284 | looked at the end of the stream, and if op_find_initial_pcm_offset() |
| 1285 | didn't already determine the link was empty).*/ |
| 1286 | if(OP_LIKELY(links[nlinks-1].pcm_end==-1)){ |
| 1287 | ret=op_find_final_pcm_offset(_of,serialnos,nserialnos, |
| 1288 | links+nlinks-1,_sr[0].offset,_sr[0].serialno,_sr[0].gp,&total_duration); |
| 1289 | if(OP_UNLIKELY(ret<0))return ret; |
| 1290 | } |
| 1291 | /*Trim back the links array if necessary.*/ |
| 1292 | links=(OggOpusLink *)_ogg_realloc(links,sizeof(*links)*nlinks); |
| 1293 | if(OP_LIKELY(links!=NULL))_of->links=links; |
| 1294 | /*We also don't need these anymore.*/ |
| 1295 | _ogg_free(*_serialnos); |
| 1296 | *_serialnos=NULL; |
| 1297 | *_cserialnos=*_nserialnos=0; |
| 1298 | return 0; |
| 1299 | } |
| 1300 |
| 1301 | static void op_update_gain(OggOpusFile *_of){ |
| 1302 | OpusHead *head; |
| 1303 | opus_int32 gain_q8; |
| 1304 | int li; |
| 1305 | /*If decode isn't ready, then we'll apply the gain when we initialize the |
| 1306 | decoder.*/ |
| 1307 | if(_of->ready_state<OP_INITSET)return; |
| 1308 | gain_q8=_of->gain_offset_q8; |
| 1309 | li=_of->seekable?_of->cur_link:0; |
| 1310 | head=&_of->links[li].head; |
| 1311 | /*We don't have to worry about overflow here because the header gain and |
| 1312 | track gain must lie in the range [-32768,32767], and the user-supplied |
| 1313 | offset has been pre-clamped to [-98302,98303].*/ |
| 1314 | switch(_of->gain_type){ |
| 1315 | case OP_TRACK_GAIN:{ |
| 1316 | int track_gain_q8; |
| 1317 | track_gain_q8=0; |
| 1318 | opus_tags_get_track_gain(&_of->links[li].tags,&track_gain_q8); |
| 1319 | gain_q8+=track_gain_q8; |
| 1320 | } |
| 1321 | /*Fall through.*/ |
| 1322 | case OP_HEADER_GAIN:gain_q8+=head->output_gain;break; |
| 1323 | case OP_ABSOLUTE_GAIN:break; |
| 1324 | default:OP_ASSERT(0); |
| 1325 | } |
| 1326 | gain_q8=OP_CLAMP(-32768,gain_q8,32767); |
| 1327 | OP_ASSERT(_of->od!=NULL); |
| 1328 | #if defined(OPUS_SET_GAIN) |
| 1329 | opus_multistream_decoder_ctl(_of->od,OPUS_SET_GAIN(gain_q8)); |
| 1330 | #else |
| 1331 | /*A fallback that works with both float and fixed-point is a bunch of work, |
| 1332 | so just force people to use a sufficiently new version. |
| 1333 | This is deployed well enough at this point that this shouldn't be a burden.*/ |
| 1334 | # error "libopus 1.0.1 or later required" |
| 1335 | #endif |
| 1336 | } |
| 1337 |
| 1338 | static int op_make_decode_ready(OggOpusFile *_of){ |
| 1339 | const OpusHead *head; |
| 1340 | int li; |
| 1341 | int stream_count; |
| 1342 | int coupled_count; |
| 1343 | int channel_count; |
| 1344 | if(_of->ready_state>OP_STREAMSET)return 0; |
| 1345 | if(OP_UNLIKELY(_of->ready_state<OP_STREAMSET))return OP_EFAULT; |
| 1346 | li=_of->seekable?_of->cur_link:0; |
| 1347 | head=&_of->links[li].head; |
| 1348 | stream_count=head->stream_count; |
| 1349 | coupled_count=head->coupled_count; |
| 1350 | channel_count=head->channel_count; |
| 1351 | /*Check to see if the current decoder is compatible with the current link.*/ |
| 1352 | if(_of->od!=NULL&&_of->od_stream_count==stream_count |
| 1353 | &&_of->od_coupled_count==coupled_count&&_of->od_channel_count==channel_count |
| 1354 | &&memcmp(_of->od_mapping,head->mapping, |
| 1355 | sizeof(*head->mapping)*channel_count)==0){ |
| 1356 | opus_multistream_decoder_ctl(_of->od,OPUS_RESET_STATE); |
| 1357 | } |
| 1358 | else{ |
| 1359 | int err; |
| 1360 | opus_multistream_decoder_destroy(_of->od); |
| 1361 | _of->od=opus_multistream_decoder_create(48000,channel_count, |
| 1362 | stream_count,coupled_count,head->mapping,&err); |
| 1363 | if(_of->od==NULL)return OP_EFAULT; |
| 1364 | _of->od_stream_count=stream_count; |
| 1365 | _of->od_coupled_count=coupled_count; |
| 1366 | _of->od_channel_count=channel_count; |
| 1367 | memcpy(_of->od_mapping,head->mapping,sizeof(*head->mapping)*channel_count); |
| 1368 | } |
| 1369 | _of->ready_state=OP_INITSET; |
| 1370 | _of->bytes_tracked=0; |
| 1371 | _of->samples_tracked=0; |
| 1372 | #if !defined(OP_FIXED_POINT) |
| 1373 | _of->state_channel_count=0; |
| 1374 | /*Use the serial number for the PRNG seed to get repeatable output for |
| 1375 | straight play-throughs.*/ |
| 1376 | _of->dither_seed=_of->links[li].serialno; |
| 1377 | #endif |
| 1378 | op_update_gain(_of); |
| 1379 | return 0; |
| 1380 | } |
| 1381 |
| 1382 | static int op_open_seekable2_impl(OggOpusFile *_of){ |
| 1383 | /*64 seek records should be enough for anybody. |
| 1384 | Actually, with a bisection search in a 63-bit range down to OP_CHUNK_SIZE |
| 1385 | granularity, much more than enough.*/ |
| 1386 | OpusSeekRecord sr[64]; |
| 1387 | opus_int64 data_offset; |
| 1388 | int ret; |
| 1389 | /*We can seek, so set out learning all about this file.*/ |
| 1390 | (*_of->callbacks.seek)(_of->source,0,SEEK_END); |
| 1391 | _of->offset=_of->end=(*_of->callbacks.tell)(_of->source); |
| 1392 | if(OP_UNLIKELY(_of->end<0))return OP_EREAD; |
| 1393 | data_offset=_of->links[0].data_offset; |
| 1394 | if(OP_UNLIKELY(_of->end<data_offset))return OP_EBADLINK; |
| 1395 | /*Get the offset of the last page of the physical bitstream, or, if we're |
| 1396 | lucky, the last Opus page of the first link, as most Ogg Opus files will |
| 1397 | contain a single logical bitstream.*/ |
| 1398 | ret=op_get_prev_page_serial(_of,sr,_of->end, |
| 1399 | _of->links[0].serialno,_of->serialnos,_of->nserialnos); |
| 1400 | if(OP_UNLIKELY(ret<0))return ret; |
| 1401 | /*If there's any trailing junk, forget about it.*/ |
| 1402 | _of->end=sr[0].offset+sr[0].size; |
| 1403 | if(OP_UNLIKELY(_of->end<data_offset))return OP_EBADLINK; |
| 1404 | /*Now enumerate the bitstream structure.*/ |
| 1405 | return op_bisect_forward_serialno(_of,data_offset,sr,sizeof(sr)/sizeof(*sr), |
| 1406 | &_of->serialnos,&_of->nserialnos,&_of->cserialnos); |
| 1407 | } |
| 1408 |
| 1409 | static int op_open_seekable2(OggOpusFile *_of){ |
| 1410 | ogg_sync_state oy_start; |
| 1411 | ogg_stream_state os_start; |
| 1412 | ogg_packet *op_start; |
| 1413 | opus_int64 start_offset; |
| 1414 | int start_op_count; |
| 1415 | int ret; |
| 1416 | /*We're partially open and have a first link header state in storage in _of. |
| 1417 | Save off that stream state so we can come back to it. |
| 1418 | It would be simpler to just dump all this state and seek back to |
| 1419 | links[0].data_offset when we're done. |
| 1420 | But we do the extra work to allow us to seek back to _exactly_ the same |
| 1421 | stream position we're at now. |
| 1422 | This allows, e.g., the HTTP backend to continue reading from the original |
| 1423 | connection (if it's still available), instead of opening a new one. |
| 1424 | This means we can open and start playing a normal Opus file with a single |
| 1425 | link and reasonable packet sizes using only two HTTP requests.*/ |
| 1426 | start_op_count=_of->op_count; |
| 1427 | /*This is a bit too large to put on the stack unconditionally.*/ |
| 1428 | op_start=(ogg_packet *)_ogg_malloc(sizeof(*op_start)*start_op_count); |
| 1429 | if(op_start==NULL)return OP_EFAULT; |
| 1430 | *&oy_start=_of->oy; |
| 1431 | *&os_start=_of->os; |
| 1432 | start_offset=_of->offset; |
| 1433 | memcpy(op_start,_of->op,sizeof(*op_start)*start_op_count); |
| 1434 | OP_ASSERT((*_of->callbacks.tell)(_of->source)==op_position(_of)); |
| 1435 | ogg_sync_init(&_of->oy); |
| 1436 | ogg_stream_init(&_of->os,-1); |
| 1437 | ret=op_open_seekable2_impl(_of); |
| 1438 | /*Restore the old stream state.*/ |
| 1439 | ogg_stream_clear(&_of->os); |
| 1440 | ogg_sync_clear(&_of->oy); |
| 1441 | *&_of->oy=*&oy_start; |
| 1442 | *&_of->os=*&os_start; |
| 1443 | _of->offset=start_offset; |
| 1444 | _of->op_count=start_op_count; |
| 1445 | memcpy(_of->op,op_start,sizeof(*_of->op)*start_op_count); |
| 1446 | _ogg_free(op_start); |
| 1447 | _of->prev_packet_gp=_of->links[0].pcm_start; |
| 1448 | _of->cur_discard_count=_of->links[0].head.pre_skip; |
| 1449 | if(OP_UNLIKELY(ret<0))return ret; |
| 1450 | /*And restore the position indicator.*/ |
| 1451 | ret=(*_of->callbacks.seek)(_of->source,op_position(_of),SEEK_SET); |
| 1452 | return OP_UNLIKELY(ret<0)?OP_EREAD:0; |
| 1453 | } |
| 1454 |
| 1455 | /*Clear out the current logical bitstream decoder.*/ |
| 1456 | static void op_decode_clear(OggOpusFile *_of){ |
| 1457 | /*We don't actually free the decoder. |
| 1458 | We might be able to re-use it for the next link.*/ |
| 1459 | _of->op_count=0; |
| 1460 | _of->od_buffer_size=0; |
| 1461 | _of->prev_packet_gp=-1; |
| 1462 | if(!_of->seekable){ |
| 1463 | OP_ASSERT(_of->ready_state>=OP_INITSET); |
| 1464 | opus_tags_clear(&_of->links[0].tags); |
| 1465 | } |
| 1466 | _of->ready_state=OP_OPENED; |
| 1467 | } |
| 1468 |
| 1469 | static void op_clear(OggOpusFile *_of){ |
| 1470 | OggOpusLink *links; |
| 1471 | _ogg_free(_of->od_buffer); |
| 1472 | if(_of->od!=NULL)opus_multistream_decoder_destroy(_of->od); |
| 1473 | links=_of->links; |
| 1474 | if(!_of->seekable){ |
| 1475 | if(_of->ready_state>OP_OPENED||_of->ready_state==OP_PARTOPEN){ |
| 1476 | opus_tags_clear(&links[0].tags); |
| 1477 | } |
| 1478 | } |
| 1479 | else if(OP_LIKELY(links!=NULL)){ |
| 1480 | int nlinks; |
| 1481 | int link; |
| 1482 | nlinks=_of->nlinks; |
| 1483 | for(link=0;link<nlinks;link++)opus_tags_clear(&links[link].tags); |
| 1484 | } |
| 1485 | _ogg_free(links); |
| 1486 | _ogg_free(_of->serialnos); |
| 1487 | ogg_stream_clear(&_of->os); |
| 1488 | ogg_sync_clear(&_of->oy); |
| 1489 | if(_of->callbacks.close!=NULL)(*_of->callbacks.close)(_of->source); |
| 1490 | } |
| 1491 |
| 1492 | static int op_open1(OggOpusFile *_of, |
| 1493 | void *_source,const OpusFileCallbacks *_cb, |
| 1494 | const unsigned char *_initial_data,size_t _initial_bytes){ |
| 1495 | ogg_page og; |
| 1496 | ogg_page *pog; |
| 1497 | int seekable; |
| 1498 | int ret; |
| 1499 | memset(_of,0,sizeof(*_of)); |
| 1500 | _of->end=-1; |
| 1501 | _of->source=_source; |
| 1502 | *&_of->callbacks=*_cb; |
| 1503 | /*At a minimum, we need to be able to read data.*/ |
| 1504 | if(OP_UNLIKELY(_of->callbacks.read==NULL))return OP_EREAD; |
| 1505 | /*Initialize the framing state.*/ |
| 1506 | ogg_sync_init(&_of->oy); |
| 1507 | /*Perhaps some data was previously read into a buffer for testing against |
| 1508 | other stream types. |
| 1509 | Allow initialization from this previously read data (especially as we may |
| 1510 | be reading from a non-seekable stream). |
| 1511 | This requires copying it into a buffer allocated by ogg_sync_buffer() and |
| 1512 | doesn't support seeking, so this is not a good mechanism to use for |
| 1513 | decoding entire files from RAM.*/ |
| 1514 | if(_initial_bytes>0){ |
| 1515 | char *buffer; |
| 1516 | buffer=ogg_sync_buffer(&_of->oy,_initial_bytes); |
| 1517 | memcpy(buffer,_initial_data,_initial_bytes*sizeof(*buffer)); |
| 1518 | ogg_sync_wrote(&_of->oy,_initial_bytes); |
| 1519 | } |
| 1520 | /*Can we seek? |
| 1521 | Stevens suggests the seek test is portable.*/ |
| 1522 | seekable=_cb->seek!=NULL&&(*_cb->seek)(_source,0,SEEK_CUR)!=-1; |
| 1523 | /*If seek is implemented, tell must also be implemented.*/ |
| 1524 | if(seekable){ |
| 1525 | opus_int64 pos; |
| 1526 | if(OP_UNLIKELY(_of->callbacks.tell==NULL))return OP_EINVAL; |
| 1527 | pos=(*_of->callbacks.tell)(_of->source); |
| 1528 | /*If the current position is not equal to the initial bytes consumed, |
| 1529 | absolute seeking will not work.*/ |
| 1530 | if(OP_UNLIKELY(pos!=(opus_int64)_initial_bytes))return OP_EINVAL; |
| 1531 | } |
| 1532 | _of->seekable=seekable; |
| 1533 | /*Don't seek yet. |
| 1534 | Set up a 'single' (current) logical bitstream entry for partial open.*/ |
| 1535 | _of->links=(OggOpusLink *)_ogg_malloc(sizeof(*_of->links)); |
| 1536 | /*The serialno gets filled in later by op_fetch_headers().*/ |
| 1537 | ogg_stream_init(&_of->os,-1); |
| 1538 | pog=NULL; |
| 1539 | for(;;){ |
| 1540 | /*Fetch all BOS pages, store the Opus header and all seen serial numbers, |
| 1541 | and load subsequent Opus setup headers.*/ |
| 1542 | ret=op_fetch_headers(_of,&_of->links[0].head,&_of->links[0].tags, |
| 1543 | &_of->serialnos,&_of->nserialnos,&_of->cserialnos,pog); |
| 1544 | if(OP_UNLIKELY(ret<0))break; |
| 1545 | _of->nlinks=1; |
| 1546 | _of->links[0].offset=0; |
| 1547 | _of->links[0].data_offset=_of->offset; |
| 1548 | _of->links[0].pcm_end=-1; |
| 1549 | _of->links[0].serialno=_of->os.serialno; |
| 1550 | /*Fetch the initial PCM offset.*/ |
| 1551 | ret=op_find_initial_pcm_offset(_of,_of->links,&og); |
| 1552 | if(seekable||OP_LIKELY(ret<=0))break; |
| 1553 | /*This link was empty, but we already have the BOS page for the next one in |
| 1554 | og. |
| 1555 | We can't seek, so start processing the next link right now.*/ |
| 1556 | opus_tags_clear(&_of->links[0].tags); |
| 1557 | _of->nlinks=0; |
| 1558 | if(!seekable)_of->cur_link++; |
| 1559 | pog=&og; |
| 1560 | } |
| 1561 | if(OP_LIKELY(ret>=0))_of->ready_state=OP_PARTOPEN; |
| 1562 | return ret; |
| 1563 | } |
| 1564 |
| 1565 | static int op_open2(OggOpusFile *_of){ |
| 1566 | int ret; |
| 1567 | OP_ASSERT(_of->ready_state==OP_PARTOPEN); |
| 1568 | if(_of->seekable){ |
| 1569 | _of->ready_state=OP_OPENED; |
| 1570 | ret=op_open_seekable2(_of); |
| 1571 | } |
| 1572 | else ret=0; |
| 1573 | if(OP_LIKELY(ret>=0)){ |
| 1574 | /*We have buffered packets from op_find_initial_pcm_offset(). |
| 1575 | Move to OP_INITSET so we can use them.*/ |
| 1576 | _of->ready_state=OP_STREAMSET; |
| 1577 | ret=op_make_decode_ready(_of); |
| 1578 | if(OP_LIKELY(ret>=0))return 0; |
| 1579 | } |
| 1580 | /*Don't auto-close the stream on failure.*/ |
| 1581 | _of->callbacks.close=NULL; |
| 1582 | op_clear(_of); |
| 1583 | return ret; |
| 1584 | } |
| 1585 |
| 1586 | OggOpusFile *op_test_callbacks(void *_source,const OpusFileCallbacks *_cb, |
| 1587 | const unsigned char *_initial_data,size_t _initial_bytes,int *_error){ |
| 1588 | OggOpusFile *of; |
| 1589 | int ret; |
| 1590 | of=(OggOpusFile *)_ogg_malloc(sizeof(*of)); |
| 1591 | ret=OP_EFAULT; |
| 1592 | if(OP_LIKELY(of!=NULL)){ |
| 1593 | ret=op_open1(of,_source,_cb,_initial_data,_initial_bytes); |
| 1594 | if(OP_LIKELY(ret>=0)){ |
| 1595 | if(_error!=NULL)*_error=0; |
| 1596 | return of; |
| 1597 | } |
| 1598 | /*Don't auto-close the stream on failure.*/ |
| 1599 | of->callbacks.close=NULL; |
| 1600 | op_clear(of); |
| 1601 | _ogg_free(of); |
| 1602 | } |
| 1603 | if(_error!=NULL)*_error=ret; |
| 1604 | return NULL; |
| 1605 | } |
| 1606 |
| 1607 | OggOpusFile *op_open_callbacks(void *_source,const OpusFileCallbacks *_cb, |
| 1608 | const unsigned char *_initial_data,size_t _initial_bytes,int *_error){ |
| 1609 | OggOpusFile *of; |
| 1610 | of=op_test_callbacks(_source,_cb,_initial_data,_initial_bytes,_error); |
| 1611 | if(OP_LIKELY(of!=NULL)){ |
| 1612 | int ret; |
| 1613 | ret=op_open2(of); |
| 1614 | if(OP_LIKELY(ret>=0))return of; |
| 1615 | if(_error!=NULL)*_error=ret; |
| 1616 | _ogg_free(of); |
| 1617 | } |
| 1618 | return NULL; |
| 1619 | } |
| 1620 |
| 1621 | /*Convenience routine to clean up from failure for the open functions that |
| 1622 | create their own streams.*/ |
| 1623 | static OggOpusFile *op_open_close_on_failure(void *_source, |
| 1624 | const OpusFileCallbacks *_cb,int *_error){ |
| 1625 | OggOpusFile *of; |
| 1626 | if(OP_UNLIKELY(_source==NULL)){ |
| 1627 | if(_error!=NULL)*_error=OP_EFAULT; |
| 1628 | return NULL; |
| 1629 | } |
| 1630 | of=op_open_callbacks(_source,_cb,NULL,0,_error); |
| 1631 | if(OP_UNLIKELY(of==NULL))(*_cb->close)(_source); |
| 1632 | return of; |
| 1633 | } |
| 1634 |
| 1635 | OggOpusFile *op_open_file(const char *_path,int *_error){ |
| 1636 | OpusFileCallbacks cb; |
| 1637 | return op_open_close_on_failure(op_fopen(&cb,_path,"rb"),&cb,_error); |
| 1638 | } |
| 1639 |
| 1640 | OggOpusFile *op_open_memory(const unsigned char *_data,size_t _size, |
| 1641 | int *_error){ |
| 1642 | OpusFileCallbacks cb; |
| 1643 | return op_open_close_on_failure(op_mem_stream_create(&cb,_data,_size),&cb, |
| 1644 | _error); |
| 1645 | } |
| 1646 |
| 1647 | /*Convenience routine to clean up from failure for the open functions that |
| 1648 | create their own streams.*/ |
| 1649 | static OggOpusFile *op_test_close_on_failure(void *_source, |
| 1650 | const OpusFileCallbacks *_cb,int *_error){ |
| 1651 | OggOpusFile *of; |
| 1652 | if(OP_UNLIKELY(_source==NULL)){ |
| 1653 | if(_error!=NULL)*_error=OP_EFAULT; |
| 1654 | return NULL; |
| 1655 | } |
| 1656 | of=op_test_callbacks(_source,_cb,NULL,0,_error); |
| 1657 | if(OP_UNLIKELY(of==NULL))(*_cb->close)(_source); |
| 1658 | return of; |
| 1659 | } |
| 1660 |
| 1661 | OggOpusFile *op_test_file(const char *_path,int *_error){ |
| 1662 | OpusFileCallbacks cb; |
| 1663 | return op_test_close_on_failure(op_fopen(&cb,_path,"rb"),&cb,_error); |
| 1664 | } |
| 1665 |
| 1666 | OggOpusFile *op_test_memory(const unsigned char *_data,size_t _size, |
| 1667 | int *_error){ |
| 1668 | OpusFileCallbacks cb; |
| 1669 | return op_test_close_on_failure(op_mem_stream_create(&cb,_data,_size),&cb, |
| 1670 | _error); |
| 1671 | } |
| 1672 |
| 1673 | int op_test_open(OggOpusFile *_of){ |
| 1674 | int ret; |
| 1675 | if(OP_UNLIKELY(_of->ready_state!=OP_PARTOPEN))return OP_EINVAL; |
| 1676 | ret=op_open2(_of); |
| 1677 | /*op_open2() will clear this structure on failure. |
| 1678 | Reset its contents to prevent double-frees in op_free().*/ |
| 1679 | if(OP_UNLIKELY(ret<0))memset(_of,0,sizeof(*_of)); |
| 1680 | return ret; |
| 1681 | } |
| 1682 |
| 1683 | void op_free(OggOpusFile *_of){ |
| 1684 | if(OP_LIKELY(_of!=NULL)){ |
| 1685 | op_clear(_of); |
| 1686 | _ogg_free(_of); |
| 1687 | } |
| 1688 | } |
| 1689 |
| 1690 | int op_seekable(const OggOpusFile *_of){ |
| 1691 | return _of->seekable; |
| 1692 | } |
| 1693 |
| 1694 | int op_link_count(const OggOpusFile *_of){ |
| 1695 | return _of->nlinks; |
| 1696 | } |
| 1697 |
| 1698 | ogg_uint32_t op_serialno(const OggOpusFile *_of,int _li){ |
| 1699 | if(OP_UNLIKELY(_li>=_of->nlinks))_li=_of->nlinks-1; |
| 1700 | if(!_of->seekable)_li=0; |
| 1701 | return _of->links[_li<0?_of->cur_link:_li].serialno; |
| 1702 | } |
| 1703 |
| 1704 | int op_channel_count(const OggOpusFile *_of,int _li){ |
| 1705 | return op_head(_of,_li)->channel_count; |
| 1706 | } |
| 1707 |
| 1708 | opus_int64 op_raw_total(const OggOpusFile *_of,int _li){ |
| 1709 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED) |
| 1710 | ||OP_UNLIKELY(!_of->seekable) |
| 1711 | ||OP_UNLIKELY(_li>=_of->nlinks)){ |
| 1712 | return OP_EINVAL; |
| 1713 | } |
| 1714 | if(_li<0)return _of->end-_of->links[0].offset; |
| 1715 | return (_li+1>=_of->nlinks?_of->end:_of->links[_li+1].offset) |
| 1716 | -_of->links[_li].offset; |
| 1717 | } |
| 1718 |
| 1719 | ogg_int64_t op_pcm_total(const OggOpusFile *_of,int _li){ |
| 1720 | OggOpusLink *links; |
| 1721 | ogg_int64_t diff; |
| 1722 | int nlinks; |
| 1723 | nlinks=_of->nlinks; |
| 1724 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED) |
| 1725 | ||OP_UNLIKELY(!_of->seekable) |
| 1726 | ||OP_UNLIKELY(_li>=nlinks)){ |
| 1727 | return OP_EINVAL; |
| 1728 | } |
| 1729 | links=_of->links; |
| 1730 | /*We verify that the granule position differences are larger than the |
| 1731 | pre-skip and that the total duration does not overflow during link |
| 1732 | enumeration, so we don't have to check here.*/ |
| 1733 | if(_li<0){ |
| 1734 | ogg_int64_t pcm_total; |
| 1735 | int li; |
| 1736 | pcm_total=0; |
| 1737 | for(li=0;li<nlinks;li++){ |
| 1738 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff, |
| 1739 | links[li].pcm_end,links[li].pcm_start)); |
| 1740 | pcm_total+=diff-links[li].head.pre_skip; |
| 1741 | } |
| 1742 | return pcm_total; |
| 1743 | } |
| 1744 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff, |
| 1745 | links[_li].pcm_end,links[_li].pcm_start)); |
| 1746 | return diff-links[_li].head.pre_skip; |
| 1747 | } |
| 1748 |
| 1749 | const OpusHead *op_head(const OggOpusFile *_of,int _li){ |
| 1750 | if(OP_UNLIKELY(_li>=_of->nlinks))_li=_of->nlinks-1; |
| 1751 | if(!_of->seekable)_li=0; |
| 1752 | return &_of->links[_li<0?_of->cur_link:_li].head; |
| 1753 | } |
| 1754 |
| 1755 | const OpusTags *op_tags(const OggOpusFile *_of,int _li){ |
| 1756 | if(OP_UNLIKELY(_li>=_of->nlinks))_li=_of->nlinks-1; |
| 1757 | if(!_of->seekable){ |
| 1758 | if(_of->ready_state<OP_STREAMSET&&_of->ready_state!=OP_PARTOPEN){ |
| 1759 | return NULL; |
| 1760 | } |
| 1761 | _li=0; |
| 1762 | } |
| 1763 | else if(_li<0)_li=_of->ready_state>=OP_STREAMSET?_of->cur_link:0; |
| 1764 | return &_of->links[_li].tags; |
| 1765 | } |
| 1766 |
| 1767 | int op_current_link(const OggOpusFile *_of){ |
| 1768 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 1769 | return _of->cur_link; |
| 1770 | } |
| 1771 |
| 1772 | /*Compute an average bitrate given a byte and sample count. |
| 1773 | Return: The bitrate in bits per second.*/ |
| 1774 | static opus_int32 op_calc_bitrate(opus_int64 _bytes,ogg_int64_t _samples){ |
| 1775 | /*These rates are absurd, but let's handle them anyway.*/ |
| 1776 | if(OP_UNLIKELY(_bytes>(OP_INT64_MAX-(_samples>>1))/(48000*8))){ |
| 1777 | ogg_int64_t den; |
| 1778 | if(OP_UNLIKELY(_bytes/(OP_INT32_MAX/(48000*8))>=_samples)){ |
| 1779 | return OP_INT32_MAX; |
| 1780 | } |
| 1781 | den=_samples/(48000*8); |
| 1782 | return (opus_int32)((_bytes+(den>>1))/den); |
| 1783 | } |
| 1784 | if(OP_UNLIKELY(_samples<=0))return OP_INT32_MAX; |
| 1785 | /*This can't actually overflow in normal operation: even with a pre-skip of |
| 1786 | 545 2.5 ms frames with 8 streams running at 1282*8+1 bytes per packet |
| 1787 | (1275 byte frames + Opus framing overhead + Ogg lacing values), that all |
| 1788 | produce a single sample of decoded output, we still don't top 45 Mbps. |
| 1789 | The only way to get bitrates larger than that is with excessive Opus |
| 1790 | padding, more encoded streams than output channels, or lots and lots of |
| 1791 | Ogg pages with no packets on them.*/ |
| 1792 | return (opus_int32)OP_MIN((_bytes*48000*8+(_samples>>1))/_samples, |
| 1793 | OP_INT32_MAX); |
| 1794 | } |
| 1795 |
| 1796 | opus_int32 op_bitrate(const OggOpusFile *_of,int _li){ |
| 1797 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED)||OP_UNLIKELY(!_of->seekable) |
| 1798 | ||OP_UNLIKELY(_li>=_of->nlinks)){ |
| 1799 | return OP_EINVAL; |
| 1800 | } |
| 1801 | return op_calc_bitrate(op_raw_total(_of,_li),op_pcm_total(_of,_li)); |
| 1802 | } |
| 1803 |
| 1804 | opus_int32 op_bitrate_instant(OggOpusFile *_of){ |
| 1805 | ogg_int64_t samples_tracked; |
| 1806 | opus_int32 ret; |
| 1807 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 1808 | samples_tracked=_of->samples_tracked; |
| 1809 | if(OP_UNLIKELY(samples_tracked==0))return OP_FALSE; |
| 1810 | ret=op_calc_bitrate(_of->bytes_tracked,samples_tracked); |
| 1811 | _of->bytes_tracked=0; |
| 1812 | _of->samples_tracked=0; |
| 1813 | return ret; |
| 1814 | } |
| 1815 |
| 1816 | /*Fetch and process a page. |
| 1817 | This handles the case where we're at a bitstream boundary and dumps the |
| 1818 | decoding machine. |
| 1819 | If the decoding machine is unloaded, it loads it. |
| 1820 | It also keeps prev_packet_gp up to date (seek and read both use this; seek |
| 1821 | uses a special hack with _readp). |
| 1822 | Return: <0) Error, OP_HOLE (lost packet), or OP_EOF. |
| 1823 | 0) Need more data (only if _readp==0). |
| 1824 | 1) Got at least one audio data packet.*/ |
| 1825 | static int op_fetch_and_process_page(OggOpusFile *_of, |
| 1826 | ogg_page *_og,opus_int64 _page_pos,int _readp,int _spanp,int _ignore_holes){ |
| 1827 | OggOpusLink *links; |
| 1828 | ogg_uint32_t cur_serialno; |
| 1829 | int seekable; |
| 1830 | int cur_link; |
| 1831 | int ret; |
| 1832 | /*We shouldn't get here if we have unprocessed packets.*/ |
| 1833 | OP_ASSERT(_of->ready_state<OP_INITSET||_of->op_pos>=_of->op_count); |
| 1834 | if(!_readp)return 0; |
| 1835 | seekable=_of->seekable; |
| 1836 | links=_of->links; |
| 1837 | cur_link=seekable?_of->cur_link:0; |
| 1838 | cur_serialno=links[cur_link].serialno; |
| 1839 | /*Handle one page.*/ |
| 1840 | for(;;){ |
| 1841 | ogg_page og; |
| 1842 | OP_ASSERT(_of->ready_state>=OP_OPENED); |
| 1843 | /*This loop is not strictly necessary, but there's no sense in doing the |
| 1844 | extra checks of the larger loop for the common case in a multiplexed |
| 1845 | bistream where the page is simply part of a different logical |
| 1846 | bitstream.*/ |
| 1847 | do{ |
| 1848 | /*If we were given a page to use, use it.*/ |
| 1849 | if(_og!=NULL){ |
| 1850 | *&og=*_og; |
| 1851 | _og=NULL; |
| 1852 | } |
| 1853 | /*Keep reading until we get a page with the correct serialno.*/ |
| 1854 | else _page_pos=op_get_next_page(_of,&og,_of->end); |
| 1855 | /*EOF: Leave uninitialized.*/ |
| 1856 | if(_page_pos<0)return _page_pos<OP_FALSE?(int)_page_pos:OP_EOF; |
| 1857 | if(OP_LIKELY(_of->ready_state>=OP_STREAMSET)){ |
| 1858 | if(cur_serialno!=(ogg_uint32_t)ogg_page_serialno(&og)){ |
| 1859 | /*Two possibilities: |
| 1860 | 1) Another stream is multiplexed into this logical section, or*/ |
| 1861 | if(OP_LIKELY(!ogg_page_bos(&og)))continue; |
| 1862 | /* 2) Our decoding just traversed a bitstream boundary.*/ |
| 1863 | if(!_spanp)return OP_EOF; |
| 1864 | if(OP_LIKELY(_of->ready_state>=OP_INITSET))op_decode_clear(_of); |
| 1865 | break; |
| 1866 | } |
| 1867 | } |
| 1868 | /*Bitrate tracking: add the header's bytes here. |
| 1869 | The body bytes are counted when we consume the packets.*/ |
| 1870 | _of->bytes_tracked+=og.header_len; |
| 1871 | } |
| 1872 | while(0); |
| 1873 | /*Do we need to load a new machine before submitting the page? |
| 1874 | This is different in the seekable and non-seekable cases. |
| 1875 | In the seekable case, we already have all the header information loaded |
| 1876 | and cached. |
| 1877 | We just initialize the machine with it and continue on our merry way. |
| 1878 | In the non-seekable (streaming) case, we'll only be at a boundary if we |
| 1879 | just left the previous logical bitstream, and we're now nominally at the |
| 1880 | header of the next bitstream.*/ |
| 1881 | if(OP_UNLIKELY(_of->ready_state<OP_STREAMSET)){ |
| 1882 | if(seekable){ |
| 1883 | ogg_uint32_t serialno; |
| 1884 | int nlinks; |
| 1885 | int li; |
| 1886 | serialno=ogg_page_serialno(&og); |
| 1887 | /*Match the serialno to bitstream section. |
| 1888 | We use this rather than offset positions to avoid problems near |
| 1889 | logical bitstream boundaries.*/ |
| 1890 | nlinks=_of->nlinks; |
| 1891 | for(li=0;li<nlinks&&links[li].serialno!=serialno;li++); |
| 1892 | /*Not a desired Opus bitstream section. |
| 1893 | Keep trying.*/ |
| 1894 | if(li>=nlinks)continue; |
| 1895 | cur_serialno=serialno; |
| 1896 | _of->cur_link=cur_link=li; |
| 1897 | ogg_stream_reset_serialno(&_of->os,serialno); |
| 1898 | _of->ready_state=OP_STREAMSET; |
| 1899 | /*If we're at the start of this link, initialize the granule position |
| 1900 | and pre-skip tracking.*/ |
| 1901 | if(_page_pos<=links[cur_link].data_offset){ |
| 1902 | _of->prev_packet_gp=links[cur_link].pcm_start; |
| 1903 | _of->cur_discard_count=links[cur_link].head.pre_skip; |
| 1904 | /*Ignore a hole at the start of a new link (this is common for |
| 1905 | streams joined in the middle) or after seeking.*/ |
| 1906 | _ignore_holes=1; |
| 1907 | } |
| 1908 | } |
| 1909 | else{ |
| 1910 | do{ |
| 1911 | /*We're streaming. |
| 1912 | Fetch the two header packets, build the info struct.*/ |
| 1913 | ret=op_fetch_headers(_of,&links[0].head,&links[0].tags, |
| 1914 | NULL,NULL,NULL,&og); |
| 1915 | if(OP_UNLIKELY(ret<0))return ret; |
| 1916 | /*op_find_initial_pcm_offset() will suppress any initial hole for us, |
| 1917 | so no need to set _ignore_holes.*/ |
| 1918 | ret=op_find_initial_pcm_offset(_of,links,&og); |
| 1919 | if(OP_UNLIKELY(ret<0))return ret; |
| 1920 | _of->links[0].serialno=cur_serialno=_of->os.serialno; |
| 1921 | _of->cur_link++; |
| 1922 | } |
| 1923 | /*If the link was empty, keep going, because we already have the |
| 1924 | BOS page of the next one in og.*/ |
| 1925 | while(OP_UNLIKELY(ret>0)); |
| 1926 | /*If we didn't get any packets out of op_find_initial_pcm_offset(), |
| 1927 | keep going (this is possible if end-trimming trimmed them all).*/ |
| 1928 | if(_of->op_count<=0)continue; |
| 1929 | /*Otherwise, we're done.*/ |
| 1930 | ret=op_make_decode_ready(_of); |
| 1931 | if(OP_UNLIKELY(ret<0))return ret; |
| 1932 | return 1; |
| 1933 | } |
| 1934 | } |
| 1935 | /*The buffered page is the data we want, and we're ready for it. |
| 1936 | Add it to the stream state.*/ |
| 1937 | if(OP_UNLIKELY(_of->ready_state==OP_STREAMSET)){ |
| 1938 | ret=op_make_decode_ready(_of); |
| 1939 | if(OP_UNLIKELY(ret<0))return ret; |
| 1940 | } |
| 1941 | /*Extract all the packets from the current page.*/ |
| 1942 | ogg_stream_pagein(&_of->os,&og); |
| 1943 | if(OP_LIKELY(_of->ready_state>=OP_INITSET)){ |
| 1944 | opus_int32 total_duration; |
| 1945 | int durations[255]; |
| 1946 | int op_count; |
| 1947 | total_duration=op_collect_audio_packets(_of,durations); |
| 1948 | if(OP_UNLIKELY(total_duration<0)){ |
| 1949 | /*Drain the packets from the page anyway.*/ |
| 1950 | total_duration=op_collect_audio_packets(_of,durations); |
| 1951 | OP_ASSERT(total_duration>=0); |
| 1952 | /*Report holes to the caller.*/ |
| 1953 | if(!_ignore_holes)return OP_HOLE; |
| 1954 | } |
| 1955 | op_count=_of->op_count; |
| 1956 | /*If we found at least one audio data packet, compute per-packet granule |
| 1957 | positions for them.*/ |
| 1958 | if(op_count>0){ |
| 1959 | ogg_int64_t diff; |
| 1960 | ogg_int64_t prev_packet_gp; |
| 1961 | ogg_int64_t cur_packet_gp; |
| 1962 | ogg_int64_t cur_page_gp; |
| 1963 | int cur_page_eos; |
| 1964 | int pi; |
| 1965 | cur_page_gp=_of->op[op_count-1].granulepos; |
| 1966 | cur_page_eos=_of->op[op_count-1].e_o_s; |
| 1967 | prev_packet_gp=_of->prev_packet_gp; |
| 1968 | if(OP_UNLIKELY(prev_packet_gp==-1)){ |
| 1969 | opus_int32 cur_discard_count; |
| 1970 | /*This is the first call after a raw seek. |
| 1971 | Try to reconstruct prev_packet_gp from scratch.*/ |
| 1972 | OP_ASSERT(seekable); |
| 1973 | if(OP_UNLIKELY(cur_page_eos)){ |
| 1974 | /*If the first page we hit after our seek was the EOS page, and |
| 1975 | we didn't start from data_offset or before, we don't have |
| 1976 | enough information to do end-trimming. |
| 1977 | Proceed to the next link, rather than risk playing back some |
| 1978 | samples that shouldn't have been played.*/ |
| 1979 | _of->op_count=0; |
| 1980 | continue; |
| 1981 | } |
| 1982 | /*By default discard 80 ms of data after a seek, unless we seek |
| 1983 | into the pre-skip region.*/ |
| 1984 | cur_discard_count=80*48; |
| 1985 | cur_page_gp=_of->op[op_count-1].granulepos; |
| 1986 | /*Try to initialize prev_packet_gp. |
| 1987 | If the current page had packets but didn't have a granule |
| 1988 | position, or the granule position it had was too small (both |
| 1989 | illegal), just use the starting granule position for the link.*/ |
| 1990 | prev_packet_gp=links[cur_link].pcm_start; |
| 1991 | if(OP_LIKELY(cur_page_gp!=-1)){ |
| 1992 | op_granpos_add(&prev_packet_gp,cur_page_gp,-total_duration); |
| 1993 | } |
| 1994 | if(OP_LIKELY(!op_granpos_diff(&diff, |
| 1995 | prev_packet_gp,links[cur_link].pcm_start))){ |
| 1996 | opus_int32 pre_skip; |
| 1997 | /*If we start at the beginning of the pre-skip region, or we're |
| 1998 | at least 80 ms from the end of the pre-skip region, we discard |
| 1999 | to the end of the pre-skip region. |
| 2000 | Otherwise, we still use the 80 ms default, which will discard |
| 2001 | past the end of the pre-skip region.*/ |
| 2002 | pre_skip=links[cur_link].head.pre_skip; |
| 2003 | if(diff>=0&&diff<=OP_MAX(0,pre_skip-80*48)){ |
| 2004 | cur_discard_count=pre_skip-(int)diff; |
| 2005 | } |
| 2006 | } |
| 2007 | _of->cur_discard_count=cur_discard_count; |
| 2008 | } |
| 2009 | if(OP_UNLIKELY(cur_page_gp==-1)){ |
| 2010 | /*This page had completed packets but didn't have a valid granule |
| 2011 | position. |
| 2012 | This is illegal, but we'll try to handle it by continuing to count |
| 2013 | forwards from the previous page.*/ |
| 2014 | if(op_granpos_add(&cur_page_gp,prev_packet_gp,total_duration)<0){ |
| 2015 | /*The timestamp for this page overflowed.*/ |
| 2016 | cur_page_gp=links[cur_link].pcm_end; |
| 2017 | } |
| 2018 | } |
| 2019 | /*If we hit the last page, handle end-trimming.*/ |
| 2020 | if(OP_UNLIKELY(cur_page_eos) |
| 2021 | &&OP_LIKELY(!op_granpos_diff(&diff,cur_page_gp,prev_packet_gp)) |
| 2022 | &&OP_LIKELY(diff<total_duration)){ |
| 2023 | cur_packet_gp=prev_packet_gp; |
| 2024 | for(pi=0;pi<op_count;pi++){ |
| 2025 | diff=durations[pi]-diff; |
| 2026 | /*If we have samples to trim...*/ |
| 2027 | if(diff>0){ |
| 2028 | /*If we trimmed the entire packet, stop (the spec says encoders |
| 2029 | shouldn't do this, but we support it anyway).*/ |
| 2030 | if(OP_UNLIKELY(diff>durations[pi]))break; |
| 2031 | cur_packet_gp=cur_page_gp; |
| 2032 | /*Move the EOS flag to this packet, if necessary, so we'll trim |
| 2033 | the samples during decode.*/ |
| 2034 | _of->op[pi].e_o_s=1; |
| 2035 | } |
| 2036 | else{ |
| 2037 | /*Update the granule position as normal.*/ |
| 2038 | OP_ALWAYS_TRUE(!op_granpos_add(&cur_packet_gp, |
| 2039 | cur_packet_gp,durations[pi])); |
| 2040 | } |
| 2041 | _of->op[pi].granulepos=cur_packet_gp; |
| 2042 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff,cur_page_gp,cur_packet_gp)); |
| 2043 | } |
| 2044 | } |
| 2045 | else{ |
| 2046 | /*Propagate timestamps to earlier packets. |
| 2047 | op_granpos_add(&prev_packet_gp,prev_packet_gp,total_duration) |
| 2048 | should succeed and give prev_packet_gp==cur_page_gp. |
| 2049 | But we don't bother to check that, as there isn't much we can do |
| 2050 | if it's not true. |
| 2051 | The only thing we guarantee is that the start and end granule |
| 2052 | positions of the packets are valid, and that they are monotonic |
| 2053 | within a page. |
| 2054 | They might be completely out of range for this link (we'll check |
| 2055 | that elsewhere), or non-monotonic between pages.*/ |
| 2056 | if(OP_UNLIKELY(op_granpos_add(&prev_packet_gp, |
| 2057 | cur_page_gp,-total_duration)<0)){ |
| 2058 | /*The starting timestamp for the first packet on this page |
| 2059 | underflowed. |
| 2060 | This is illegal, but we ignore it.*/ |
| 2061 | prev_packet_gp=0; |
| 2062 | } |
| 2063 | for(pi=0;pi<op_count;pi++){ |
| 2064 | if(OP_UNLIKELY(op_granpos_add(&cur_packet_gp, |
| 2065 | cur_page_gp,-total_duration)<0)){ |
| 2066 | /*The start timestamp for this packet underflowed. |
| 2067 | This is illegal, but we ignore it.*/ |
| 2068 | cur_packet_gp=0; |
| 2069 | } |
| 2070 | total_duration-=durations[pi]; |
| 2071 | OP_ASSERT(total_duration>=0); |
| 2072 | OP_ALWAYS_TRUE(!op_granpos_add(&cur_packet_gp, |
| 2073 | cur_packet_gp,durations[pi])); |
| 2074 | _of->op[pi].granulepos=cur_packet_gp; |
| 2075 | } |
| 2076 | OP_ASSERT(total_duration==0); |
| 2077 | } |
| 2078 | _of->prev_packet_gp=prev_packet_gp; |
| 2079 | _of->op_count=pi; |
| 2080 | /*If end-trimming didn't trim all the packets, we're done.*/ |
| 2081 | if(OP_LIKELY(pi>0))return 1; |
| 2082 | } |
| 2083 | } |
| 2084 | } |
| 2085 | } |
| 2086 |
| 2087 | int op_raw_seek(OggOpusFile *_of,opus_int64 _pos){ |
| 2088 | int ret; |
| 2089 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 2090 | /*Don't dump the decoder state if we can't seek.*/ |
| 2091 | if(OP_UNLIKELY(!_of->seekable))return OP_ENOSEEK; |
| 2092 | if(OP_UNLIKELY(_pos<0)||OP_UNLIKELY(_pos>_of->end))return OP_EINVAL; |
| 2093 | /*Clear out any buffered, decoded data.*/ |
| 2094 | op_decode_clear(_of); |
| 2095 | _of->bytes_tracked=0; |
| 2096 | _of->samples_tracked=0; |
| 2097 | ret=op_seek_helper(_of,_pos); |
| 2098 | if(OP_UNLIKELY(ret<0))return OP_EREAD; |
| 2099 | ret=op_fetch_and_process_page(_of,NULL,-1,1,1,1); |
| 2100 | /*If we hit EOF, op_fetch_and_process_page() leaves us uninitialized. |
| 2101 | Instead, jump to the end.*/ |
| 2102 | if(ret==OP_EOF){ |
| 2103 | int cur_link; |
| 2104 | op_decode_clear(_of); |
| 2105 | cur_link=_of->nlinks-1; |
| 2106 | _of->cur_link=cur_link; |
| 2107 | _of->prev_packet_gp=_of->links[cur_link].pcm_end; |
| 2108 | _of->cur_discard_count=0; |
| 2109 | ret=0; |
| 2110 | } |
| 2111 | else if(ret>0)ret=0; |
| 2112 | return ret; |
| 2113 | } |
| 2114 |
| 2115 | /*Convert a PCM offset relative to the start of the whole stream to a granule |
| 2116 | position in an individual link.*/ |
| 2117 | static ogg_int64_t op_get_granulepos(const OggOpusFile *_of, |
| 2118 | ogg_int64_t _pcm_offset,int *_li){ |
| 2119 | const OggOpusLink *links; |
| 2120 | ogg_int64_t duration; |
| 2121 | int nlinks; |
| 2122 | int li; |
| 2123 | OP_ASSERT(_pcm_offset>=0); |
| 2124 | nlinks=_of->nlinks; |
| 2125 | links=_of->links; |
| 2126 | for(li=0;OP_LIKELY(li<nlinks);li++){ |
| 2127 | ogg_int64_t pcm_start; |
| 2128 | opus_int32 pre_skip; |
| 2129 | pcm_start=links[li].pcm_start; |
| 2130 | pre_skip=links[li].head.pre_skip; |
| 2131 | OP_ALWAYS_TRUE(!op_granpos_diff(&duration,links[li].pcm_end,pcm_start)); |
| 2132 | duration-=pre_skip; |
| 2133 | if(_pcm_offset<duration){ |
| 2134 | _pcm_offset+=pre_skip; |
| 2135 | if(OP_UNLIKELY(pcm_start>OP_INT64_MAX-_pcm_offset)){ |
| 2136 | /*Adding this amount to the granule position would overflow the positive |
| 2137 | half of its 64-bit range. |
| 2138 | Since signed overflow is undefined in C, do it in a way the compiler |
| 2139 | isn't allowed to screw up.*/ |
| 2140 | _pcm_offset-=OP_INT64_MAX-pcm_start+1; |
| 2141 | pcm_start=OP_INT64_MIN; |
| 2142 | } |
| 2143 | pcm_start+=_pcm_offset; |
| 2144 | *_li=li; |
| 2145 | return pcm_start; |
| 2146 | } |
| 2147 | _pcm_offset-=duration; |
| 2148 | } |
| 2149 | return -1; |
| 2150 | } |
| 2151 |
| 2152 | /*This controls how close the target has to be to use the current stream |
| 2153 | position to subdivide the initial range. |
| 2154 | Two minutes seems to be a good default.*/ |
| 2155 | #define OP_CUR_TIME_THRESH (120*48*(opus_int32)1000) |
| 2156 |
| 2157 | /*Note: The OP_SMALL_FOOTPRINT #define doesn't (currently) save much code size, |
| 2158 | but it's meant to serve as documentation for portions of the seeking |
| 2159 | algorithm that are purely optional, to aid others learning from/porting this |
| 2160 | code to other contexts.*/ |
| 2161 | /*#define OP_SMALL_FOOTPRINT (1)*/ |
| 2162 |
| 2163 | /*Search within link _li for the page with the highest granule position |
| 2164 | preceding (or equal to) _target_gp. |
| 2165 | There is a danger here: missing pages or incorrect frame number information |
| 2166 | in the bitstream could make our task impossible. |
| 2167 | Account for that (and report it as an error condition).*/ |
| 2168 | static int op_pcm_seek_page(OggOpusFile *_of, |
| 2169 | ogg_int64_t _target_gp,int _li){ |
| 2170 | const OggOpusLink *link; |
| 2171 | ogg_page og; |
| 2172 | ogg_int64_t pcm_pre_skip; |
| 2173 | ogg_int64_t pcm_start; |
| 2174 | ogg_int64_t pcm_end; |
| 2175 | ogg_int64_t best_gp; |
| 2176 | ogg_int64_t diff; |
| 2177 | ogg_uint32_t serialno; |
| 2178 | opus_int32 pre_skip; |
| 2179 | opus_int64 begin; |
| 2180 | opus_int64 end; |
| 2181 | opus_int64 boundary; |
| 2182 | opus_int64 best; |
| 2183 | opus_int64 page_offset; |
| 2184 | opus_int64 d0; |
| 2185 | opus_int64 d1; |
| 2186 | opus_int64 d2; |
| 2187 | int force_bisect; |
| 2188 | int ret; |
| 2189 | _of->bytes_tracked=0; |
| 2190 | _of->samples_tracked=0; |
| 2191 | link=_of->links+_li; |
| 2192 | best_gp=pcm_start=link->pcm_start; |
| 2193 | pcm_end=link->pcm_end; |
| 2194 | serialno=link->serialno; |
| 2195 | best=begin=link->data_offset; |
| 2196 | page_offset=-1; |
| 2197 | /*We discard the first 80 ms of data after a seek, so seek back that much |
| 2198 | farther. |
| 2199 | If we can't, simply seek to the beginning of the link.*/ |
| 2200 | if(OP_UNLIKELY(op_granpos_add(&_target_gp,_target_gp,-80*48)<0) |
| 2201 | ||OP_UNLIKELY(op_granpos_cmp(_target_gp,pcm_start)<0)){ |
| 2202 | _target_gp=pcm_start; |
| 2203 | } |
| 2204 | /*Special case seeking to the start of the link.*/ |
| 2205 | pre_skip=link->head.pre_skip; |
| 2206 | OP_ALWAYS_TRUE(!op_granpos_add(&pcm_pre_skip,pcm_start,pre_skip)); |
| 2207 | if(op_granpos_cmp(_target_gp,pcm_pre_skip)<0)end=boundary=begin; |
| 2208 | else{ |
| 2209 | end=boundary=link->end_offset; |
| 2210 | #if !defined(OP_SMALL_FOOTPRINT) |
| 2211 | /*If we were decoding from this link, we can narrow the range a bit.*/ |
| 2212 | if(_li==_of->cur_link&&_of->ready_state>=OP_INITSET){ |
| 2213 | opus_int64 offset; |
| 2214 | int op_count; |
| 2215 | op_count=_of->op_count; |
| 2216 | /*The only way the offset can be invalid _and_ we can fail the granule |
| 2217 | position checks below is if someone changed the contents of the last |
| 2218 | page since we read it. |
| 2219 | We'd be within our rights to just return OP_EBADLINK in that case, but |
| 2220 | we'll simply ignore the current position instead.*/ |
| 2221 | offset=_of->offset; |
| 2222 | if(op_count>0&&OP_LIKELY(offset<=end)){ |
| 2223 | ogg_int64_t gp; |
| 2224 | /*Make sure the timestamp is valid. |
| 2225 | The granule position might be -1 if we collected the packets from a |
| 2226 | page without a granule position after reporting a hole.*/ |
| 2227 | gp=_of->op[op_count-1].granulepos; |
| 2228 | if(OP_LIKELY(gp!=-1)&&OP_LIKELY(op_granpos_cmp(pcm_start,gp)<0) |
| 2229 | &&OP_LIKELY(op_granpos_cmp(pcm_end,gp)>0)){ |
| 2230 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff,gp,_target_gp)); |
| 2231 | /*We only actually use the current time if either |
| 2232 | a) We can cut off at least half the range, or |
| 2233 | b) We're seeking sufficiently close to the current position that |
| 2234 | it's likely to be informative. |
| 2235 | Otherwise it appears using the whole link range to estimate the |
| 2236 | first seek location gives better results, on average.*/ |
| 2237 | if(diff<0){ |
| 2238 | OP_ASSERT(offset>=begin); |
| 2239 | if(offset-begin>=end-begin>>1||diff>-OP_CUR_TIME_THRESH){ |
| 2240 | best=begin=offset; |
| 2241 | best_gp=pcm_start=gp; |
| 2242 | } |
| 2243 | } |
| 2244 | else{ |
| 2245 | ogg_int64_t prev_page_gp; |
| 2246 | /*We might get lucky and already have the packet with the target |
| 2247 | buffered. |
| 2248 | Worth checking. |
| 2249 | For very small files (with all of the data in a single page, |
| 2250 | generally 1 second or less), we can loop them continuously |
| 2251 | without seeking at all.*/ |
| 2252 | OP_ALWAYS_TRUE(!op_granpos_add(&prev_page_gp,_of->op[0].granulepos, |
| 2253 | op_get_packet_duration(_of->op[0].packet,_of->op[0].bytes))); |
| 2254 | if(op_granpos_cmp(prev_page_gp,_target_gp)<=0){ |
| 2255 | /*Don't call op_decode_clear(), because it will dump our |
| 2256 | packets.*/ |
| 2257 | _of->op_pos=0; |
| 2258 | _of->od_buffer_size=0; |
| 2259 | _of->prev_packet_gp=prev_page_gp; |
| 2260 | _of->ready_state=OP_STREAMSET; |
| 2261 | return op_make_decode_ready(_of); |
| 2262 | } |
| 2263 | /*No such luck. |
| 2264 | Check if we can cut off at least half the range, though.*/ |
| 2265 | if(offset-begin<=end-begin>>1||diff<OP_CUR_TIME_THRESH){ |
| 2266 | /*We really want the page start here, but this will do.*/ |
| 2267 | end=boundary=offset; |
| 2268 | pcm_end=gp; |
| 2269 | } |
| 2270 | } |
| 2271 | } |
| 2272 | } |
| 2273 | } |
| 2274 | #endif |
| 2275 | } |
| 2276 | /*This code was originally based on the "new search algorithm by HB (Nicholas |
| 2277 | Vinen)" from libvorbisfile. |
| 2278 | It has been modified substantially since.*/ |
| 2279 | op_decode_clear(_of); |
| 2280 | /*Initialize the interval size history.*/ |
| 2281 | d2=d1=d0=end-begin; |
| 2282 | force_bisect=0; |
| 2283 | while(begin<end){ |
| 2284 | opus_int64 bisect; |
| 2285 | opus_int64 next_boundary; |
| 2286 | opus_int32 chunk_size; |
| 2287 | if(end-begin<OP_CHUNK_SIZE)bisect=begin; |
| 2288 | else{ |
| 2289 | /*Update the interval size history.*/ |
| 2290 | d0=d1>>1; |
| 2291 | d1=d2>>1; |
| 2292 | d2=end-begin>>1; |
| 2293 | if(force_bisect)bisect=begin+(end-begin>>1); |
| 2294 | else{ |
| 2295 | ogg_int64_t diff2; |
| 2296 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff,_target_gp,pcm_start)); |
| 2297 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff2,pcm_end,pcm_start)); |
| 2298 | /*Take a (pretty decent) guess.*/ |
| 2299 | bisect=begin+op_rescale64(diff,diff2,end-begin)-OP_CHUNK_SIZE; |
| 2300 | } |
| 2301 | if(bisect-OP_CHUNK_SIZE<begin)bisect=begin; |
| 2302 | force_bisect=0; |
| 2303 | } |
| 2304 | if(bisect!=_of->offset){ |
| 2305 | page_offset=-1; |
| 2306 | ret=op_seek_helper(_of,bisect); |
| 2307 | if(OP_UNLIKELY(ret<0))return ret; |
| 2308 | } |
| 2309 | chunk_size=OP_CHUNK_SIZE; |
| 2310 | next_boundary=boundary; |
| 2311 | while(begin<end){ |
| 2312 | page_offset=op_get_next_page(_of,&og,boundary); |
| 2313 | if(page_offset<0){ |
| 2314 | if(page_offset<OP_FALSE)return (int)page_offset; |
| 2315 | /*There are no more pages in our interval from our stream with a valid |
| 2316 | timestamp that start at position bisect or later.*/ |
| 2317 | /*If we scanned the whole interval, we're done.*/ |
| 2318 | if(bisect<=begin+1)end=begin; |
| 2319 | else{ |
| 2320 | /*Otherwise, back up one chunk.*/ |
| 2321 | bisect=OP_MAX(bisect-chunk_size,begin); |
| 2322 | ret=op_seek_helper(_of,bisect); |
| 2323 | if(OP_UNLIKELY(ret<0))return ret; |
| 2324 | /*Bump up the chunk size.*/ |
| 2325 | chunk_size=OP_MIN(2*chunk_size,OP_CHUNK_SIZE_MAX); |
| 2326 | /*If we did find a page from another stream or without a timestamp, |
| 2327 | don't read past it.*/ |
| 2328 | boundary=next_boundary; |
| 2329 | } |
| 2330 | } |
| 2331 | else{ |
| 2332 | ogg_int64_t gp; |
| 2333 | /*Save the offset of the first page we found after the seek, regardless |
| 2334 | of the stream it came from or whether or not it has a timestamp.*/ |
| 2335 | next_boundary=OP_MIN(page_offset,next_boundary); |
| 2336 | if(serialno!=(ogg_uint32_t)ogg_page_serialno(&og))continue; |
| 2337 | gp=ogg_page_granulepos(&og); |
| 2338 | if(gp==-1)continue; |
| 2339 | if(op_granpos_cmp(gp,_target_gp)<0){ |
| 2340 | /*We found a page that ends before our target. |
| 2341 | Advance to the raw offset of the next page.*/ |
| 2342 | begin=_of->offset; |
| 2343 | if(OP_UNLIKELY(op_granpos_cmp(pcm_start,gp)>0) |
| 2344 | ||OP_UNLIKELY(op_granpos_cmp(pcm_end,gp)<0)){ |
| 2345 | /*Don't let pcm_start get out of range! |
| 2346 | That could happen with an invalid timestamp.*/ |
| 2347 | break; |
| 2348 | } |
| 2349 | /*Save the byte offset of the end of the page with this granule |
| 2350 | position.*/ |
| 2351 | best=begin; |
| 2352 | best_gp=pcm_start=gp; |
| 2353 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff,_target_gp,pcm_start)); |
| 2354 | /*If we're more than a second away from our target, break out and |
| 2355 | do another bisection.*/ |
| 2356 | if(diff>48000)break; |
| 2357 | /*Otherwise, keep scanning forward (do NOT use begin+1).*/ |
| 2358 | bisect=begin; |
| 2359 | } |
| 2360 | else{ |
| 2361 | /*We found a page that ends after our target.*/ |
| 2362 | /*If we scanned the whole interval before we found it, we're done.*/ |
| 2363 | if(bisect<=begin+1)end=begin; |
| 2364 | else{ |
| 2365 | end=bisect; |
| 2366 | /*In later iterations, don't read past the first page we found.*/ |
| 2367 | boundary=next_boundary; |
| 2368 | /*If we're not making much progress shrinking the interval size, |
| 2369 | start forcing straight bisection to limit the worst case.*/ |
| 2370 | force_bisect=end-begin>d0*2; |
| 2371 | /*Don't let pcm_end get out of range! |
| 2372 | That could happen with an invalid timestamp.*/ |
| 2373 | if(OP_LIKELY(op_granpos_cmp(pcm_end,gp)>0) |
| 2374 | &&OP_LIKELY(op_granpos_cmp(pcm_start,gp)<=0)){ |
| 2375 | pcm_end=gp; |
| 2376 | } |
| 2377 | break; |
| 2378 | } |
| 2379 | } |
| 2380 | } |
| 2381 | } |
| 2382 | } |
| 2383 | /*Found our page. |
| 2384 | Seek to the end of it and update prev_packet_gp. |
| 2385 | Our caller will set cur_discard_count. |
| 2386 | This is an easier case than op_raw_seek(), as we don't need to keep any |
| 2387 | packets from the page we found.*/ |
| 2388 | /*Seek, if necessary.*/ |
| 2389 | if(best!=page_offset){ |
| 2390 | page_offset=-1; |
| 2391 | ret=op_seek_helper(_of,best); |
| 2392 | if(OP_UNLIKELY(ret<0))return ret; |
| 2393 | } |
| 2394 | OP_ASSERT(op_granpos_cmp(best_gp,pcm_start)>=0); |
| 2395 | _of->cur_link=_li; |
| 2396 | _of->ready_state=OP_STREAMSET; |
| 2397 | _of->prev_packet_gp=best_gp; |
| 2398 | ogg_stream_reset_serialno(&_of->os,serialno); |
| 2399 | ret=op_fetch_and_process_page(_of,page_offset<0?NULL:&og,page_offset,1,0,1); |
| 2400 | if(OP_UNLIKELY(ret<=0))return OP_EBADLINK; |
| 2401 | /*Verify result.*/ |
| 2402 | if(OP_UNLIKELY(op_granpos_cmp(_of->prev_packet_gp,_target_gp)>0)){ |
| 2403 | return OP_EBADLINK; |
| 2404 | } |
| 2405 | return 0; |
| 2406 | } |
| 2407 |
| 2408 | int op_pcm_seek(OggOpusFile *_of,ogg_int64_t _pcm_offset){ |
| 2409 | const OggOpusLink *link; |
| 2410 | ogg_int64_t pcm_start; |
| 2411 | ogg_int64_t target_gp; |
| 2412 | ogg_int64_t prev_packet_gp; |
| 2413 | ogg_int64_t skip; |
| 2414 | ogg_int64_t diff; |
| 2415 | int op_count; |
| 2416 | int op_pos; |
| 2417 | int ret; |
| 2418 | int li; |
| 2419 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 2420 | if(OP_UNLIKELY(!_of->seekable))return OP_ENOSEEK; |
| 2421 | if(OP_UNLIKELY(_pcm_offset<0))return OP_EINVAL; |
| 2422 | target_gp=op_get_granulepos(_of,_pcm_offset,&li); |
| 2423 | if(OP_UNLIKELY(target_gp==-1))return OP_EINVAL; |
| 2424 | link=_of->links+li; |
| 2425 | pcm_start=link->pcm_start; |
| 2426 | OP_ALWAYS_TRUE(!op_granpos_diff(&_pcm_offset,target_gp,pcm_start)); |
| 2427 | #if !defined(OP_SMALL_FOOTPRINT) |
| 2428 | /*For small (90 ms or less) forward seeks within the same link, just decode |
| 2429 | forward. |
| 2430 | This also optimizes the case of seeking to the current position.*/ |
| 2431 | if(li==_of->cur_link&&_of->ready_state>=OP_INITSET){ |
| 2432 | ogg_int64_t gp; |
| 2433 | gp=_of->prev_packet_gp; |
| 2434 | if(OP_LIKELY(gp!=-1)){ |
| 2435 | int nbuffered; |
| 2436 | nbuffered=OP_MAX(_of->od_buffer_size-_of->od_buffer_pos,0); |
| 2437 | OP_ALWAYS_TRUE(!op_granpos_add(&gp,gp,-nbuffered)); |
| 2438 | /*We do _not_ add cur_discard_count to gp. |
| 2439 | Otherwise the total amount to discard could grow without bound, and it |
| 2440 | would be better just to do a full seek.*/ |
| 2441 | if(OP_LIKELY(!op_granpos_diff(&diff,gp,pcm_start))){ |
| 2442 | ogg_int64_t discard_count; |
| 2443 | discard_count=_pcm_offset-diff; |
| 2444 | /*We use a threshold of 90 ms instead of 80, since 80 ms is the |
| 2445 | _minimum_ we would have discarded after a full seek. |
| 2446 | Assuming 20 ms frames (the default), we'd discard 90 ms on average.*/ |
| 2447 | if(discard_count>=0&&OP_UNLIKELY(discard_count<90*48)){ |
| 2448 | _of->cur_discard_count=(opus_int32)discard_count; |
| 2449 | return 0; |
| 2450 | } |
| 2451 | } |
| 2452 | } |
| 2453 | } |
| 2454 | #endif |
| 2455 | ret=op_pcm_seek_page(_of,target_gp,li); |
| 2456 | if(OP_UNLIKELY(ret<0))return ret; |
| 2457 | /*Now skip samples until we actually get to our target.*/ |
| 2458 | /*Figure out where we should skip to.*/ |
| 2459 | if(_pcm_offset<=link->head.pre_skip)skip=0; |
| 2460 | else skip=OP_MAX(_pcm_offset-80*48,0); |
| 2461 | OP_ASSERT(_pcm_offset-skip>=0); |
| 2462 | OP_ASSERT(_pcm_offset-skip<OP_INT32_MAX-120*48); |
| 2463 | /*Skip packets until we find one with samples past our skip target.*/ |
| 2464 | for(;;){ |
| 2465 | op_count=_of->op_count; |
| 2466 | prev_packet_gp=_of->prev_packet_gp; |
| 2467 | for(op_pos=_of->op_pos;op_pos<op_count;op_pos++){ |
| 2468 | ogg_int64_t cur_packet_gp; |
| 2469 | cur_packet_gp=_of->op[op_pos].granulepos; |
| 2470 | if(OP_LIKELY(!op_granpos_diff(&diff,cur_packet_gp,pcm_start)) |
| 2471 | &&diff>skip){ |
| 2472 | break; |
| 2473 | } |
| 2474 | prev_packet_gp=cur_packet_gp; |
| 2475 | } |
| 2476 | _of->prev_packet_gp=prev_packet_gp; |
| 2477 | _of->op_pos=op_pos; |
| 2478 | if(op_pos<op_count)break; |
| 2479 | /*We skipped all the packets on this page. |
| 2480 | Fetch another.*/ |
| 2481 | ret=op_fetch_and_process_page(_of,NULL,-1,1,0,1); |
| 2482 | if(OP_UNLIKELY(ret<=0))return OP_EBADLINK; |
| 2483 | } |
| 2484 | OP_ALWAYS_TRUE(!op_granpos_diff(&diff,prev_packet_gp,pcm_start)); |
| 2485 | /*We skipped too far. |
| 2486 | Either the timestamps were illegal or there was a hole in the data.*/ |
| 2487 | if(diff>skip)return OP_EBADLINK; |
| 2488 | OP_ASSERT(_pcm_offset-diff<OP_INT32_MAX); |
| 2489 | /*TODO: If there are further holes/illegal timestamps, we still won't decode |
| 2490 | to the correct sample. |
| 2491 | However, at least op_pcm_tell() will report the correct value immediately |
| 2492 | after returning.*/ |
| 2493 | _of->cur_discard_count=(opus_int32)(_pcm_offset-diff); |
| 2494 | return 0; |
| 2495 | } |
| 2496 |
| 2497 | opus_int64 op_raw_tell(const OggOpusFile *_of){ |
| 2498 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 2499 | return _of->offset; |
| 2500 | } |
| 2501 |
| 2502 | /*Convert a granule position from a given link to a PCM offset relative to the |
| 2503 | start of the whole stream. |
| 2504 | For unseekable sources, this gets reset to 0 at the beginning of each link.*/ |
| 2505 | static ogg_int64_t op_get_pcm_offset(const OggOpusFile *_of, |
| 2506 | ogg_int64_t _gp,int _li){ |
| 2507 | const OggOpusLink *links; |
| 2508 | ogg_int64_t pcm_offset; |
| 2509 | ogg_int64_t delta; |
| 2510 | int li; |
| 2511 | links=_of->links; |
| 2512 | pcm_offset=0; |
| 2513 | OP_ASSERT(_li<_of->nlinks); |
| 2514 | for(li=0;li<_li;li++){ |
| 2515 | OP_ALWAYS_TRUE(!op_granpos_diff(&delta, |
| 2516 | links[li].pcm_end,links[li].pcm_start)); |
| 2517 | delta-=links[li].head.pre_skip; |
| 2518 | pcm_offset+=delta; |
| 2519 | } |
| 2520 | OP_ASSERT(_li>=0); |
| 2521 | if(_of->seekable&&OP_UNLIKELY(op_granpos_cmp(_gp,links[_li].pcm_end)>0)){ |
| 2522 | _gp=links[_li].pcm_end; |
| 2523 | } |
| 2524 | if(OP_LIKELY(op_granpos_cmp(_gp,links[_li].pcm_start)>0)){ |
| 2525 | if(OP_UNLIKELY(op_granpos_diff(&delta,_gp,links[_li].pcm_start)<0)){ |
| 2526 | /*This means an unseekable stream claimed to have a page from more than |
| 2527 | 2 billion days after we joined.*/ |
| 2528 | OP_ASSERT(!_of->seekable); |
| 2529 | return OP_INT64_MAX; |
| 2530 | } |
| 2531 | if(delta<links[_li].head.pre_skip)delta=0; |
| 2532 | else delta-=links[_li].head.pre_skip; |
| 2533 | /*In the seekable case, _gp was limited by pcm_end. |
| 2534 | In the unseekable case, pcm_offset should be 0.*/ |
| 2535 | OP_ASSERT(pcm_offset<=OP_INT64_MAX-delta); |
| 2536 | pcm_offset+=delta; |
| 2537 | } |
| 2538 | return pcm_offset; |
| 2539 | } |
| 2540 |
| 2541 | ogg_int64_t op_pcm_tell(const OggOpusFile *_of){ |
| 2542 | ogg_int64_t gp; |
| 2543 | int nbuffered; |
| 2544 | int li; |
| 2545 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 2546 | gp=_of->prev_packet_gp; |
| 2547 | if(gp==-1)return 0; |
| 2548 | nbuffered=OP_MAX(_of->od_buffer_size-_of->od_buffer_pos,0); |
| 2549 | OP_ALWAYS_TRUE(!op_granpos_add(&gp,gp,-nbuffered)); |
| 2550 | li=_of->seekable?_of->cur_link:0; |
| 2551 | if(op_granpos_add(&gp,gp,_of->cur_discard_count)<0){ |
| 2552 | gp=_of->links[li].pcm_end; |
| 2553 | } |
| 2554 | return op_get_pcm_offset(_of,gp,li); |
| 2555 | } |
| 2556 |
| 2557 | void op_set_decode_callback(OggOpusFile *_of, |
| 2558 | op_decode_cb_func _decode_cb,void *_ctx){ |
| 2559 | _of->decode_cb=_decode_cb; |
| 2560 | _of->decode_cb_ctx=_ctx; |
| 2561 | } |
| 2562 |
| 2563 | int op_set_gain_offset(OggOpusFile *_of, |
| 2564 | int _gain_type,opus_int32 _gain_offset_q8){ |
| 2565 | if(_gain_type!=OP_HEADER_GAIN&&_gain_type!=OP_TRACK_GAIN |
| 2566 | &&_gain_type!=OP_ABSOLUTE_GAIN){ |
| 2567 | return OP_EINVAL; |
| 2568 | } |
| 2569 | _of->gain_type=_gain_type; |
| 2570 | /*The sum of header gain and track gain lies in the range [-65536,65534]. |
| 2571 | These bounds allow the offset to set the final value to anywhere in the |
| 2572 | range [-32768,32767], which is what we'll clamp it to before applying.*/ |
| 2573 | _of->gain_offset_q8=OP_CLAMP(-98302,_gain_offset_q8,98303); |
| 2574 | op_update_gain(_of); |
| 2575 | return 0; |
| 2576 | } |
| 2577 |
| 2578 | void op_set_dither_enabled(OggOpusFile *_of,int _enabled){ |
| 2579 | #if !defined(OP_FIXED_POINT) |
| 2580 | _of->dither_disabled=!_enabled; |
| 2581 | if(!_enabled)_of->dither_mute=65; |
| 2582 | #endif |
| 2583 | } |
| 2584 |
| 2585 | /*Allocate the decoder scratch buffer. |
| 2586 | This is done lazily, since if the user provides large enough buffers, we'll |
| 2587 | never need it.*/ |
| 2588 | static int op_init_buffer(OggOpusFile *_of){ |
| 2589 | int nchannels_max; |
| 2590 | if(_of->seekable){ |
| 2591 | const OggOpusLink *links; |
| 2592 | int nlinks; |
| 2593 | int li; |
| 2594 | links=_of->links; |
| 2595 | nlinks=_of->nlinks; |
| 2596 | nchannels_max=1; |
| 2597 | for(li=0;li<nlinks;li++){ |
| 2598 | nchannels_max=OP_MAX(nchannels_max,links[li].head.channel_count); |
| 2599 | } |
| 2600 | } |
| 2601 | else nchannels_max=OP_NCHANNELS_MAX; |
| 2602 | _of->od_buffer=(op_sample *)_ogg_malloc( |
| 2603 | sizeof(*_of->od_buffer)*nchannels_max*120*48); |
| 2604 | if(_of->od_buffer==NULL)return OP_EFAULT; |
| 2605 | return 0; |
| 2606 | } |
| 2607 |
| 2608 | /*Decode a single packet into the target buffer.*/ |
| 2609 | static int op_decode(OggOpusFile *_of,op_sample *_pcm, |
| 2610 | const ogg_packet *_op,int _nsamples,int _nchannels){ |
| 2611 | int ret; |
| 2612 | /*First we try using the application-provided decode callback.*/ |
| 2613 | if(_of->decode_cb!=NULL){ |
| 2614 | #if defined(OP_FIXED_POINT) |
| 2615 | ret=(*_of->decode_cb)(_of->decode_cb_ctx,_of->od,_pcm,_op, |
| 2616 | _nsamples,_nchannels,OP_DEC_FORMAT_SHORT,_of->cur_link); |
| 2617 | #else |
| 2618 | ret=(*_of->decode_cb)(_of->decode_cb_ctx,_of->od,_pcm,_op, |
| 2619 | _nsamples,_nchannels,OP_DEC_FORMAT_FLOAT,_of->cur_link); |
| 2620 | #endif |
| 2621 | } |
| 2622 | else ret=OP_DEC_USE_DEFAULT; |
| 2623 | /*If the application didn't want to handle decoding, do it ourselves.*/ |
| 2624 | if(ret==OP_DEC_USE_DEFAULT){ |
| 2625 | #if defined(OP_FIXED_POINT) |
| 2626 | ret=opus_multistream_decode(_of->od, |
| 2627 | _op->packet,_op->bytes,_pcm,_nsamples,0); |
| 2628 | #else |
| 2629 | ret=opus_multistream_decode_float(_of->od, |
| 2630 | _op->packet,_op->bytes,_pcm,_nsamples,0); |
| 2631 | #endif |
| 2632 | OP_ASSERT(ret<0||ret==_nsamples); |
| 2633 | } |
| 2634 | /*If the application returned a positive value other than 0 or |
| 2635 | OP_DEC_USE_DEFAULT, fail.*/ |
| 2636 | else if(OP_UNLIKELY(ret>0))return OP_EBADPACKET; |
| 2637 | if(OP_UNLIKELY(ret<0))return OP_EBADPACKET; |
| 2638 | return ret; |
| 2639 | } |
| 2640 |
| 2641 | /*Read more samples from the stream, using the same API as op_read() or |
| 2642 | op_read_float().*/ |
| 2643 | static int op_read_native(OggOpusFile *_of, |
| 2644 | op_sample *_pcm,int _buf_size,int *_li){ |
| 2645 | if(OP_UNLIKELY(_of->ready_state<OP_OPENED))return OP_EINVAL; |
| 2646 | for(;;){ |
| 2647 | int ret; |
| 2648 | if(OP_LIKELY(_of->ready_state>=OP_INITSET)){ |
| 2649 | int nchannels; |
| 2650 | int od_buffer_pos; |
| 2651 | int nsamples; |
| 2652 | int op_pos; |
| 2653 | nchannels=_of->links[_of->seekable?_of->cur_link:0].head.channel_count; |
| 2654 | od_buffer_pos=_of->od_buffer_pos; |
| 2655 | nsamples=_of->od_buffer_size-od_buffer_pos; |
| 2656 | /*If we have buffered samples, return them.*/ |
| 2657 | if(nsamples>0){ |
| 2658 | if(nsamples*nchannels>_buf_size)nsamples=_buf_size/nchannels; |
| 2659 | memcpy(_pcm,_of->od_buffer+nchannels*od_buffer_pos, |
| 2660 | sizeof(*_pcm)*nchannels*nsamples); |
| 2661 | od_buffer_pos+=nsamples; |
| 2662 | _of->od_buffer_pos=od_buffer_pos; |
| 2663 | if(_li!=NULL)*_li=_of->cur_link; |
| 2664 | return nsamples; |
| 2665 | } |
| 2666 | /*If we have buffered packets, decode one.*/ |
| 2667 | op_pos=_of->op_pos; |
| 2668 | if(OP_LIKELY(op_pos<_of->op_count)){ |
| 2669 | const ogg_packet *pop; |
| 2670 | ogg_int64_t diff; |
| 2671 | opus_int32 cur_discard_count; |
| 2672 | int duration; |
| 2673 | int trimmed_duration; |
| 2674 | pop=_of->op+op_pos++; |
| 2675 | _of->op_pos=op_pos; |
| 2676 | cur_discard_count=_of->cur_discard_count; |
| 2677 | duration=op_get_packet_duration(pop->packet,pop->bytes); |
| 2678 | /*We don't buffer packets with an invalid TOC sequence.*/ |
| 2679 | OP_ASSERT(duration>0); |
| 2680 | trimmed_duration=duration; |
| 2681 | /*Perform end-trimming.*/ |
| 2682 | if(OP_UNLIKELY(pop->e_o_s)){ |
| 2683 | if(OP_UNLIKELY(op_granpos_cmp(pop->granulepos, |
| 2684 | _of->prev_packet_gp)<=0)){ |
| 2685 | trimmed_duration=0; |
| 2686 | } |
| 2687 | else if(OP_LIKELY(!op_granpos_diff(&diff, |
| 2688 | pop->granulepos,_of->prev_packet_gp))){ |
| 2689 | trimmed_duration=(int)OP_MIN(diff,trimmed_duration); |
| 2690 | } |
| 2691 | } |
| 2692 | _of->prev_packet_gp=pop->granulepos; |
| 2693 | if(OP_UNLIKELY(duration*nchannels>_buf_size)){ |
| 2694 | op_sample *buf; |
| 2695 | /*If the user's buffer is too small, decode into a scratch buffer.*/ |
| 2696 | buf=_of->od_buffer; |
| 2697 | if(OP_UNLIKELY(buf==NULL)){ |
| 2698 | ret=op_init_buffer(_of); |
| 2699 | if(OP_UNLIKELY(ret<0))return ret; |
| 2700 | buf=_of->od_buffer; |
| 2701 | } |
| 2702 | ret=op_decode(_of,buf,pop,duration,nchannels); |
| 2703 | if(OP_UNLIKELY(ret<0))return ret; |
| 2704 | /*Perform pre-skip/pre-roll.*/ |
| 2705 | od_buffer_pos=(int)OP_MIN(trimmed_duration,cur_discard_count); |
| 2706 | cur_discard_count-=od_buffer_pos; |
| 2707 | _of->cur_discard_count=cur_discard_count; |
| 2708 | _of->od_buffer_pos=od_buffer_pos; |
| 2709 | _of->od_buffer_size=trimmed_duration; |
| 2710 | /*Update bitrate tracking based on the actual samples we used from |
| 2711 | what was decoded.*/ |
| 2712 | _of->bytes_tracked+=pop->bytes; |
| 2713 | _of->samples_tracked+=trimmed_duration-od_buffer_pos; |
| 2714 | } |
| 2715 | else{ |
| 2716 | /*Otherwise decode directly into the user's buffer.*/ |
| 2717 | ret=op_decode(_of,_pcm,pop,duration,nchannels); |
| 2718 | if(OP_UNLIKELY(ret<0))return ret; |
| 2719 | if(OP_LIKELY(trimmed_duration>0)){ |
| 2720 | /*Perform pre-skip/pre-roll.*/ |
| 2721 | od_buffer_pos=(int)OP_MIN(trimmed_duration,cur_discard_count); |
| 2722 | cur_discard_count-=od_buffer_pos; |
| 2723 | _of->cur_discard_count=cur_discard_count; |
| 2724 | trimmed_duration-=od_buffer_pos; |
| 2725 | if(OP_LIKELY(trimmed_duration>0) |
| 2726 | &&OP_UNLIKELY(od_buffer_pos>0)){ |
| 2727 | memmove(_pcm,_pcm+od_buffer_pos*nchannels, |
| 2728 | sizeof(*_pcm)*trimmed_duration*nchannels); |
| 2729 | } |
| 2730 | /*Update bitrate tracking based on the actual samples we used from |
| 2731 | what was decoded.*/ |
| 2732 | _of->bytes_tracked+=pop->bytes; |
| 2733 | _of->samples_tracked+=trimmed_duration; |
| 2734 | if(OP_LIKELY(trimmed_duration>0)){ |
| 2735 | if(_li!=NULL)*_li=_of->cur_link; |
| 2736 | return trimmed_duration; |
| 2737 | } |
| 2738 | } |
| 2739 | } |
| 2740 | /*Don't grab another page yet. |
| 2741 | This one might have more packets, or might have buffered data now.*/ |
| 2742 | continue; |
| 2743 | } |
| 2744 | } |
| 2745 | /*Suck in another page.*/ |
| 2746 | ret=op_fetch_and_process_page(_of,NULL,-1,1,1,0); |
| 2747 | if(OP_UNLIKELY(ret==OP_EOF)){ |
| 2748 | if(_li!=NULL)*_li=_of->cur_link; |
| 2749 | return 0; |
| 2750 | } |
| 2751 | if(OP_UNLIKELY(ret<0))return ret; |
| 2752 | } |
| 2753 | } |
| 2754 |
| 2755 | /*A generic filter to apply to the decoded audio data. |
| 2756 | _src is non-const because we will destructively modify the contents of the |
| 2757 | source buffer that we consume in some cases.*/ |
| 2758 | typedef int (*op_read_filter_func)(OggOpusFile *_of,void *_dst,int _dst_sz, |
| 2759 | op_sample *_src,int _nsamples,int _nchannels); |
| 2760 |
| 2761 | /*Decode some samples and then apply a custom filter to them. |
| 2762 | This is used to convert to different output formats.*/ |
| 2763 | static int op_filter_read_native(OggOpusFile *_of,void *_dst,int _dst_sz, |
| 2764 | op_read_filter_func _filter,int *_li){ |
| 2765 | int ret; |
| 2766 | /*Ensure we have some decoded samples in our buffer.*/ |
| 2767 | ret=op_read_native(_of,NULL,0,_li); |
| 2768 | /*Now apply the filter to them.*/ |
| 2769 | if(OP_LIKELY(ret>=0)&&OP_LIKELY(_of->ready_state>=OP_INITSET)){ |
| 2770 | int od_buffer_pos; |
| 2771 | od_buffer_pos=_of->od_buffer_pos; |
| 2772 | ret=_of->od_buffer_size-od_buffer_pos; |
| 2773 | if(OP_LIKELY(ret>0)){ |
| 2774 | int nchannels; |
| 2775 | nchannels=_of->links[_of->seekable?_of->cur_link:0].head.channel_count; |
| 2776 | ret=(*_filter)(_of,_dst,_dst_sz, |
| 2777 | _of->od_buffer+nchannels*od_buffer_pos,ret,nchannels); |
| 2778 | OP_ASSERT(ret>=0); |
| 2779 | OP_ASSERT(ret<=_of->od_buffer_size-od_buffer_pos); |
| 2780 | od_buffer_pos+=ret; |
| 2781 | _of->od_buffer_pos=od_buffer_pos; |
| 2782 | } |
| 2783 | } |
| 2784 | return ret; |
| 2785 | } |
| 2786 |
| 2787 | #if !defined(OP_FIXED_POINT)||!defined(OP_DISABLE_FLOAT_API) |
| 2788 |
| 2789 | /*Matrices for downmixing from the supported channel counts to stereo. |
| 2790 | The matrices with 5 or more channels are normalized to a total volume of 2.0, |
| 2791 | since most mixes sound too quiet if normalized to 1.0 (as there is generally |
| 2792 | little volume in the side/rear channels).*/ |
| 2793 | static const float OP_STEREO_DOWNMIX[OP_NCHANNELS_MAX-2][OP_NCHANNELS_MAX][2]={ |
| 2794 | /*3.0*/ |
| 2795 | { |
| 2796 | {0.5858F,0.0F},{0.4142F,0.4142F},{0.0F,0.5858F} |
| 2797 | }, |
| 2798 | /*quadrophonic*/ |
| 2799 | { |
| 2800 | {0.4226F,0.0F},{0.0F,0.4226F},{0.366F,0.2114F},{0.2114F,0.336F} |
| 2801 | }, |
| 2802 | /*5.0*/ |
| 2803 | { |
| 2804 | {0.651F,0.0F},{0.46F,0.46F},{0.0F,0.651F},{0.5636F,0.3254F}, |
| 2805 | {0.3254F,0.5636F} |
| 2806 | }, |
| 2807 | /*5.1*/ |
| 2808 | { |
| 2809 | {0.529F,0.0F},{0.3741F,0.3741F},{0.0F,0.529F},{0.4582F,0.2645F}, |
| 2810 | {0.2645F,0.4582F},{0.3741F,0.3741F} |
| 2811 | }, |
| 2812 | /*6.1*/ |
| 2813 | { |
| 2814 | {0.4553F,0.0F},{0.322F,0.322F},{0.0F,0.4553F},{0.3943F,0.2277F}, |
| 2815 | {0.2277F,0.3943F},{0.2788F,0.2788F},{0.322F,0.322F} |
| 2816 | }, |
| 2817 | /*7.1*/ |
| 2818 | { |
| 2819 | {0.3886F,0.0F},{0.2748F,0.2748F},{0.0F,0.3886F},{0.3366F,0.1943F}, |
| 2820 | {0.1943F,0.3366F},{0.3366F,0.1943F},{0.1943F,0.3366F},{0.2748F,0.2748F} |
| 2821 | } |
| 2822 | }; |
| 2823 |
| 2824 | #endif |
| 2825 |
| 2826 | #if defined(OP_FIXED_POINT) |
| 2827 |
| 2828 | /*Matrices for downmixing from the supported channel counts to stereo. |
| 2829 | The matrices with 5 or more channels are normalized to a total volume of 2.0, |
| 2830 | since most mixes sound too quiet if normalized to 1.0 (as there is generally |
| 2831 | little volume in the side/rear channels). |
| 2832 | Hence we keep the coefficients in Q14, so the downmix values won't overflow a |
| 2833 | 32-bit number.*/ |
| 2834 | static const opus_int16 OP_STEREO_DOWNMIX_Q14 |
| 2835 | [OP_NCHANNELS_MAX-2][OP_NCHANNELS_MAX][2]={ |
| 2836 | /*3.0*/ |
| 2837 | { |
| 2838 | {9598,0},{6786,6786},{0,9598} |
| 2839 | }, |
| 2840 | /*quadrophonic*/ |
| 2841 | { |
| 2842 | {6924,0},{0,6924},{5996,3464},{3464,5996} |
| 2843 | }, |
| 2844 | /*5.0*/ |
| 2845 | { |
| 2846 | {10666,0},{7537,7537},{0,10666},{9234,5331},{5331,9234} |
| 2847 | }, |
| 2848 | /*5.1*/ |
| 2849 | { |
| 2850 | {8668,0},{6129,6129},{0,8668},{7507,4335},{4335,7507},{6129,6129} |
| 2851 | }, |
| 2852 | /*6.1*/ |
| 2853 | { |
| 2854 | {7459,0},{5275,5275},{0,7459},{6460,3731},{3731,6460},{4568,4568}, |
| 2855 | {5275,5275} |
| 2856 | }, |
| 2857 | /*7.1*/ |
| 2858 | { |
| 2859 | {6368,0},{4502,4502},{0,6368},{5515,3183},{3183,5515},{5515,3183}, |
| 2860 | {3183,5515},{4502,4502} |
| 2861 | } |
| 2862 | }; |
| 2863 |
| 2864 | int op_read(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size,int *_li){ |
| 2865 | return op_read_native(_of,_pcm,_buf_size,_li); |
| 2866 | } |
| 2867 |
| 2868 | static int op_stereo_filter(OggOpusFile *_of,void *_dst,int _dst_sz, |
| 2869 | op_sample *_src,int _nsamples,int _nchannels){ |
| 2870 | (void)_of; |
| 2871 | _nsamples=OP_MIN(_nsamples,_dst_sz>>1); |
| 2872 | if(_nchannels==2)memcpy(_dst,_src,_nsamples*2*sizeof(*_src)); |
| 2873 | else{ |
| 2874 | opus_int16 *dst; |
| 2875 | int i; |
| 2876 | dst=(opus_int16 *)_dst; |
| 2877 | if(_nchannels==1){ |
| 2878 | for(i=0;i<_nsamples;i++)dst[2*i+0]=dst[2*i+1]=_src[i]; |
| 2879 | } |
| 2880 | else{ |
| 2881 | for(i=0;i<_nsamples;i++){ |
| 2882 | opus_int32 l; |
| 2883 | opus_int32 r; |
| 2884 | int ci; |
| 2885 | l=r=0; |
| 2886 | for(ci=0;ci<_nchannels;ci++){ |
| 2887 | opus_int32 s; |
| 2888 | s=_src[_nchannels*i+ci]; |
| 2889 | l+=OP_STEREO_DOWNMIX_Q14[_nchannels-3][ci][0]*s; |
| 2890 | r+=OP_STEREO_DOWNMIX_Q14[_nchannels-3][ci][1]*s; |
| 2891 | } |
| 2892 | /*TODO: For 5 or more channels, we should do soft clipping here.*/ |
| 2893 | dst[2*i+0]=(opus_int16)OP_CLAMP(-32768,l+8192>>14,32767); |
| 2894 | dst[2*i+1]=(opus_int16)OP_CLAMP(-32768,r+8192>>14,32767); |
| 2895 | } |
| 2896 | } |
| 2897 | } |
| 2898 | return _nsamples; |
| 2899 | } |
| 2900 |
| 2901 | int op_read_stereo(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size){ |
| 2902 | return op_filter_read_native(_of,_pcm,_buf_size,op_stereo_filter,NULL); |
| 2903 | } |
| 2904 |
| 2905 | # if !defined(OP_DISABLE_FLOAT_API) |
| 2906 |
| 2907 | static int op_short2float_filter(OggOpusFile *_of,void *_dst,int _dst_sz, |
| 2908 | op_sample *_src,int _nsamples,int _nchannels){ |
| 2909 | float *dst; |
| 2910 | int i; |
| 2911 | (void)_of; |
| 2912 | dst=(float *)_dst; |
| 2913 | if(OP_UNLIKELY(_nsamples*_nchannels>_dst_sz))_nsamples=_dst_sz/_nchannels; |
| 2914 | _dst_sz=_nsamples*_nchannels; |
| 2915 | for(i=0;i<_dst_sz;i++)dst[i]=(1.0F/32768)*_src[i]; |
| 2916 | return _nsamples; |
| 2917 | } |
| 2918 |
| 2919 | int op_read_float(OggOpusFile *_of,float *_pcm,int _buf_size,int *_li){ |
| 2920 | return op_filter_read_native(_of,_pcm,_buf_size,op_short2float_filter,_li); |
| 2921 | } |
| 2922 |
| 2923 | static int op_short2float_stereo_filter(OggOpusFile *_of, |
| 2924 | void *_dst,int _dst_sz,op_sample *_src,int _nsamples,int _nchannels){ |
| 2925 | float *dst; |
| 2926 | int i; |
| 2927 | dst=(float *)_dst; |
| 2928 | _nsamples=OP_MIN(_nsamples,_dst_sz>>1); |
| 2929 | if(_nchannels==1){ |
| 2930 | _nsamples=op_short2float_filter(_of,dst,_nsamples,_src,_nsamples,1); |
| 2931 | for(i=_nsamples;i-->0;)dst[2*i+0]=dst[2*i+1]=dst[i]; |
| 2932 | } |
| 2933 | else if(_nchannels<5){ |
| 2934 | /*For 3 or 4 channels, we can downmix in fixed point without risk of |
| 2935 | clipping.*/ |
| 2936 | if(_nchannels>2){ |
| 2937 | _nsamples=op_stereo_filter(_of,_src,_nsamples*2, |
| 2938 | _src,_nsamples,_nchannels); |
| 2939 | } |
| 2940 | return op_short2float_filter(_of,dst,_dst_sz,_src,_nsamples,2); |
| 2941 | } |
| 2942 | else{ |
| 2943 | /*For 5 or more channels, we convert to floats and then downmix (so that we |
| 2944 | don't risk clipping).*/ |
| 2945 | for(i=0;i<_nsamples;i++){ |
| 2946 | float l; |
| 2947 | float r; |
| 2948 | int ci; |
| 2949 | l=r=0; |
| 2950 | for(ci=0;ci<_nchannels;ci++){ |
| 2951 | float s; |
| 2952 | s=(1.0F/32768)*_src[_nchannels*i+ci]; |
| 2953 | l+=OP_STEREO_DOWNMIX[_nchannels-3][ci][0]*s; |
| 2954 | r+=OP_STEREO_DOWNMIX[_nchannels-3][ci][1]*s; |
| 2955 | } |
| 2956 | dst[2*i+0]=l; |
| 2957 | dst[2*i+1]=r; |
| 2958 | } |
| 2959 | } |
| 2960 | return _nsamples; |
| 2961 | } |
| 2962 |
| 2963 | int op_read_float_stereo(OggOpusFile *_of,float *_pcm,int _buf_size){ |
| 2964 | return op_filter_read_native(_of,_pcm,_buf_size, |
| 2965 | op_short2float_stereo_filter,NULL); |
| 2966 | } |
| 2967 |
| 2968 | # endif |
| 2969 |
| 2970 | #else |
| 2971 |
| 2972 | # if defined(OP_HAVE_LRINTF) |
| 2973 | # include <math.h> |
| 2974 | # define op_float2int(_x) (lrintf(_x)) |
| 2975 | # else |
| 2976 | # define op_float2int(_x) ((int)((_x)+((_x)<0?-0.5F:0.5F))) |
| 2977 | # endif |
| 2978 |
| 2979 | /*The dithering code here is adapted from opusdec, part of opus-tools. |
| 2980 | It was originally written by Greg Maxwell.*/ |
| 2981 |
| 2982 | static opus_uint32 op_rand(opus_uint32 _seed){ |
| 2983 | return _seed*96314165+907633515&0xFFFFFFFFU; |
| 2984 | } |
| 2985 |
| 2986 | /*This implements 16-bit quantization with full triangular dither and IIR noise |
| 2987 | shaping. |
| 2988 | The noise shaping filters were designed by Sebastian Gesemann, and are based |
| 2989 | on the LAME ATH curves with flattening to limit their peak gain to 20 dB. |
| 2990 | Everyone else's noise shaping filters are mildly crazy. |
| 2991 | The 48 kHz version of this filter is just a warped version of the 44.1 kHz |
| 2992 | filter and probably could be improved by shifting the HF shelf up in |
| 2993 | frequency a little bit, since 48 kHz has a bit more room and being more |
| 2994 | conservative against bat-ears is probably more important than more noise |
| 2995 | suppression. |
| 2996 | This process can increase the peak level of the signal (in theory by the peak |
| 2997 | error of 1.5 +20 dB, though that is unobservably rare). |
| 2998 | To avoid clipping, the signal is attenuated by a couple thousandths of a dB. |
| 2999 | Initially, the approach taken here was to only attenuate by the 99.9th |
| 3000 | percentile, making clipping rare but not impossible (like SoX), but the |
| 3001 | limited gain of the filter means that the worst case was only two |
| 3002 | thousandths of a dB more, so this just uses the worst case. |
| 3003 | The attenuation is probably also helpful to prevent clipping in the DAC |
| 3004 | reconstruction filters or downstream resampling, in any case.*/ |
| 3005 |
| 3006 | # define OP_GAIN (32753.0F) |
| 3007 |
| 3008 | # define OP_PRNG_GAIN (1.0F/0xFFFFFFFF) |
| 3009 |
| 3010 | /*48 kHz noise shaping filter, sd=2.34.*/ |
| 3011 |
| 3012 | static const float OP_FCOEF_B[4]={ |
| 3013 | 2.2374F,-0.7339F,-0.1251F,-0.6033F |
| 3014 | }; |
| 3015 |
| 3016 | static const float OP_FCOEF_A[4]={ |
| 3017 | 0.9030F,0.0116F,-0.5853F,-0.2571F |
| 3018 | }; |
| 3019 |
| 3020 | static int op_float2short_filter(OggOpusFile *_of,void *_dst,int _dst_sz, |
| 3021 | float *_src,int _nsamples,int _nchannels){ |
| 3022 | opus_int16 *dst; |
| 3023 | int ci; |
| 3024 | int i; |
| 3025 | dst=(opus_int16 *)_dst; |
| 3026 | if(OP_UNLIKELY(_nsamples*_nchannels>_dst_sz))_nsamples=_dst_sz/_nchannels; |
| 3027 | # if defined(OP_SOFT_CLIP) |
| 3028 | if(_of->state_channel_count!=_nchannels){ |
| 3029 | for(ci=0;ci<_nchannels;ci++)_of->clip_state[ci]=0; |
| 3030 | } |
| 3031 | opus_pcm_soft_clip(_src,_nsamples,_nchannels,_of->clip_state); |
| 3032 | # endif |
| 3033 | if(_of->dither_disabled){ |
| 3034 | for(i=0;i<_nchannels*_nsamples;i++){ |
| 3035 | dst[i]=op_float2int(OP_CLAMP(-32768,32768.0F*_src[i],32767)); |
| 3036 | } |
| 3037 | } |
| 3038 | else{ |
| 3039 | opus_uint32 seed; |
| 3040 | int mute; |
| 3041 | seed=_of->dither_seed; |
| 3042 | mute=_of->dither_mute; |
| 3043 | if(_of->state_channel_count!=_nchannels)mute=65; |
| 3044 | /*In order to avoid replacing digital silence with quiet dither noise, we |
| 3045 | mute if the output has been silent for a while.*/ |
| 3046 | if(mute>64)memset(_of->dither_a,0,sizeof(*_of->dither_a)*4*_nchannels); |
| 3047 | for(i=0;i<_nsamples;i++){ |
| 3048 | int silent; |
| 3049 | silent=1; |
| 3050 | for(ci=0;ci<_nchannels;ci++){ |
| 3051 | float r; |
| 3052 | float s; |
| 3053 | float err; |
| 3054 | int si; |
| 3055 | int j; |
| 3056 | s=_src[_nchannels*i+ci]; |
| 3057 | silent&=s==0; |
| 3058 | s*=OP_GAIN; |
| 3059 | err=0; |
| 3060 | for(j=0;j<4;j++){ |
| 3061 | err+=OP_FCOEF_B[j]*_of->dither_b[ci*4+j] |
| 3062 | -OP_FCOEF_A[j]*_of->dither_a[ci*4+j]; |
| 3063 | } |
| 3064 | for(j=3;j-->0;)_of->dither_a[ci*4+j+1]=_of->dither_a[ci*4+j]; |
| 3065 | for(j=3;j-->0;)_of->dither_b[ci*4+j+1]=_of->dither_b[ci*4+j]; |
| 3066 | _of->dither_a[ci*4]=err; |
| 3067 | s-=err; |
| 3068 | if(mute>16)r=0; |
| 3069 | else{ |
| 3070 | seed=op_rand(seed); |
| 3071 | r=seed*OP_PRNG_GAIN; |
| 3072 | seed=op_rand(seed); |
| 3073 | r-=seed*OP_PRNG_GAIN; |
| 3074 | } |
| 3075 | /*Clamp in float out of paranoia that the input will be > 96 dBFS and |
| 3076 | wrap if the integer is clamped.*/ |
| 3077 | si=op_float2int(OP_CLAMP(-32768,s+r,32767)); |
| 3078 | dst[_nchannels*i+ci]=(opus_int16)si; |
| 3079 | /*Including clipping in the noise shaping is generally disastrous: the |
| 3080 | futile effort to restore the clipped energy results in more clipping. |
| 3081 | However, small amounts---at the level which could normally be created |
| 3082 | by dither and rounding---are harmless and can even reduce clipping |
| 3083 | somewhat due to the clipping sometimes reducing the dither + rounding |
| 3084 | error.*/ |
| 3085 | _of->dither_b[ci*4]=mute>16?0:OP_CLAMP(-1.5F,si-s,1.5F); |
| 3086 | } |
| 3087 | mute++; |
| 3088 | if(!silent)mute=0; |
| 3089 | } |
| 3090 | _of->dither_mute=OP_MIN(mute,65); |
| 3091 | _of->dither_seed=seed; |
| 3092 | } |
| 3093 | _of->state_channel_count=_nchannels; |
| 3094 | return _nsamples; |
| 3095 | } |
| 3096 |
| 3097 | int op_read(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size,int *_li){ |
| 3098 | return op_filter_read_native(_of,_pcm,_buf_size,op_float2short_filter,_li); |
| 3099 | } |
| 3100 |
| 3101 | int op_read_float(OggOpusFile *_of,float *_pcm,int _buf_size,int *_li){ |
| 3102 | _of->state_channel_count=0; |
| 3103 | return op_read_native(_of,_pcm,_buf_size,_li); |
| 3104 | } |
| 3105 |
| 3106 | static int op_stereo_filter(OggOpusFile *_of,void *_dst,int _dst_sz, |
| 3107 | op_sample *_src,int _nsamples,int _nchannels){ |
| 3108 | (void)_of; |
| 3109 | _nsamples=OP_MIN(_nsamples,_dst_sz>>1); |
| 3110 | if(_nchannels==2)memcpy(_dst,_src,_nsamples*2*sizeof(*_src)); |
| 3111 | else{ |
| 3112 | float *dst; |
| 3113 | int i; |
| 3114 | dst=(float *)_dst; |
| 3115 | if(_nchannels==1){ |
| 3116 | for(i=0;i<_nsamples;i++)dst[2*i+0]=dst[2*i+1]=_src[i]; |
| 3117 | } |
| 3118 | else{ |
| 3119 | for(i=0;i<_nsamples;i++){ |
| 3120 | float l; |
| 3121 | float r; |
| 3122 | int ci; |
| 3123 | l=r=0; |
| 3124 | for(ci=0;ci<_nchannels;ci++){ |
| 3125 | l+=OP_STEREO_DOWNMIX[_nchannels-3][ci][0]*_src[_nchannels*i+ci]; |
| 3126 | r+=OP_STEREO_DOWNMIX[_nchannels-3][ci][1]*_src[_nchannels*i+ci]; |
| 3127 | } |
| 3128 | dst[2*i+0]=l; |
| 3129 | dst[2*i+1]=r; |
| 3130 | } |
| 3131 | } |
| 3132 | } |
| 3133 | return _nsamples; |
| 3134 | } |
| 3135 |
| 3136 | static int op_float2short_stereo_filter(OggOpusFile *_of, |
| 3137 | void *_dst,int _dst_sz,op_sample *_src,int _nsamples,int _nchannels){ |
| 3138 | opus_int16 *dst; |
| 3139 | dst=(opus_int16 *)_dst; |
| 3140 | if(_nchannels==1){ |
| 3141 | int i; |
| 3142 | _nsamples=op_float2short_filter(_of,dst,_dst_sz>>1,_src,_nsamples,1); |
| 3143 | for(i=_nsamples;i-->0;)dst[2*i+0]=dst[2*i+1]=dst[i]; |
| 3144 | } |
| 3145 | else{ |
| 3146 | if(_nchannels>2){ |
| 3147 | _nsamples=OP_MIN(_nsamples,_dst_sz>>1); |
| 3148 | _nsamples=op_stereo_filter(_of,_src,_nsamples*2, |
| 3149 | _src,_nsamples,_nchannels); |
| 3150 | } |
| 3151 | _nsamples=op_float2short_filter(_of,dst,_dst_sz,_src,_nsamples,2); |
| 3152 | } |
| 3153 | return _nsamples; |
| 3154 | } |
| 3155 |
| 3156 | int op_read_stereo(OggOpusFile *_of,opus_int16 *_pcm,int _buf_size){ |
| 3157 | return op_filter_read_native(_of,_pcm,_buf_size, |
| 3158 | op_float2short_stereo_filter,NULL); |
| 3159 | } |
| 3160 |
| 3161 | int op_read_float_stereo(OggOpusFile *_of,float *_pcm,int _buf_size){ |
| 3162 | _of->state_channel_count=0; |
| 3163 | return op_filter_read_native(_of,_pcm,_buf_size,op_stereo_filter,NULL); |
| 3164 | } |
| 3165 |
| 3166 | #endif |
| 3167 |