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