GLEGram 12.5 — Initial public release

Based on Swiftgram 12.5 (Telegram iOS 12.5).
All GLEGram features ported and organized in GLEGram/ folder.

Features: Ghost Mode, Saved Deleted Messages, Content Protection Bypass,
Font Replacement, Fake Profile, Chat Export, Plugin System, and more.

See CHANGELOG_12.5.md for full details.
This commit is contained in:
Leeksov
2026-04-06 09:48:12 +03:00
commit 4647310322
39685 changed files with 11052678 additions and 0 deletions
@@ -0,0 +1,194 @@
#import "OggOpusReader.h"
#import "opusfile/opusfile.h"
static int is_opus(ogg_page *og) {
ogg_stream_state os;
ogg_packet op;
ogg_stream_init(&os, ogg_page_serialno(og));
ogg_stream_pagein(&os, og);
if (ogg_stream_packetout(&os, &op) == 1)
{
if (op.bytes >= 19 && !memcmp(op.packet, "OpusHead", 8))
{
ogg_stream_clear(&os);
return 1;
}
}
ogg_stream_clear(&os);
return 0;
}
@implementation OggOpusFrame
- (instancetype)initWithNumSamples:(int)numSamples data:(NSData *)data {
self = [super init];
if (self != nil) {
_numSamples = numSamples;
_data = data;
}
return self;
}
@end
@interface OggOpusReader () {
OggOpusFile *_opusFile;
}
@end
@implementation OggOpusReader
- (instancetype _Nullable)initWithPath:(NSString *)path {
self = [super init];
if (self != nil) {
int error = OPUS_OK;
_opusFile = op_open_file(path.UTF8String, &error);
if (_opusFile == NULL || error != OPUS_OK) {
return nil;
}
}
return self;
}
- (void)dealloc {
if (_opusFile) {
op_free(_opusFile);
}
}
- (int32_t)read:(void *)pcmData bufSize:(int)bufSize {
return op_read(_opusFile, pcmData, bufSize, NULL);
}
+ (NSArray<OggOpusFrame *> * _Nullable)extractFrames:(NSData *)data {
NSMutableArray *result = [[NSMutableArray alloc] init];
ogg_page opage;
ogg_packet opacket;
ogg_sync_state ostate;
ogg_stream_state ostream;
int sampleRate = 48000;
if (ogg_sync_init(&ostate) < 0) {
return nil;
}
char *obuffer;
long obufferSize = (long)data.length;
obuffer = ogg_sync_buffer(&ostate, obufferSize);
if (!obuffer) {
return nil;
}
memcpy(obuffer, data.bytes, data.length);
// ogg_sync_wrote function is used to tell the ogg_sync_state struct how many bytes we wrote into the buffer.
if (ogg_sync_wrote(&ostate, obufferSize) < 0) {
return nil;
}
__unused int pages = 0;
__unused int packetsout = 0;
__unused int invalid = 0;
int eos = 0;
int headers = 0;
__unused int serialno = 0;
/* LOOP START */
while (ogg_sync_pageout(&ostate, &opage) == 1) {
pages++;
if (headers == 0) {
if (is_opus(&opage)) {
/* this is the start of an Opus stream */
serialno = ogg_page_serialno(&opage);
if (ogg_stream_init(&ostream, ogg_page_serialno(&opage)) < 0) {
return nil;
}
headers++;
} else if (!ogg_page_bos(&opage)) {
// We're past the header and haven't found an Opus stream.
// Time to give up.
break;
} else {
/* try again */
continue;
}
}
eos = ogg_page_eos(&opage);
/* submit the page for packetization */
if (ogg_stream_pagein(&ostream, &opage) < 0) {
return nil;
}
/* read and process available packets */
while (ogg_stream_packetout(&ostream, &opacket) == 1) {
packetsout++;
int samples;
/* skip header packets */
if (headers == 1 && opacket.bytes >= 19 && !memcmp(opacket.packet, "OpusHead", 8)) {
headers++;
continue;
}
if (headers == 2 && opacket.bytes >= 16 && !memcmp(opacket.packet, "OpusTags", 8)) {
headers++;
continue;
}
/* get packet duration */
samples = opus_packet_get_nb_samples(opacket.packet, (int)opacket.bytes, sampleRate);
if (samples <= 0) {
invalid++;
continue; // skipping invalid packet
}
[result addObject:[[OggOpusFrame alloc] initWithNumSamples:samples data:[NSData dataWithBytes:opacket.packet length:opacket.bytes]]];
/* update the rtp header and send */
/*this->rtp.header_size = 12 + 4 * this->rtp.cc;
this->rtp.seq++;
this->rtp.time += samples;
this->rtp.payload_size = opacket.bytes;
// Create RTP Packet
unsigned char *packet;
size_t packetSize = this->rtp.header_size + this->rtp.payload_size;
packet = (unsigned char *)malloc(packetSize);
if (!packet)
throw Napi::Error::New(info.Env(), "Couldn't allocate packet buffer.");
// Serialize header and copy to packet. Then copy payload to packet.
serialize_rtp_header(packet, this->rtp.header_size, &this->rtp);
memcpy(packet + this->rtp.header_size, opacket.packet, opacket.bytes);
Napi::Buffer<unsigned char> output = Napi::Buffer<unsigned char>::Copy(env, reinterpret_cast<unsigned char *>(packet), packetSize);
push.Call(thisObj, {output});*/
}
if (eos > 0) {
// End of the logical bitstream, clear headers to reset.
headers = 0;
}
}
/* CLEAN UP */
if (eos > 0)
{
ogg_stream_clear(&ostream);
ogg_sync_clear(&ostate);
}
return result;
}
@end
@@ -0,0 +1,11 @@
#import <Foundation/Foundation.h>
//! Project version number for OpusBinding.
FOUNDATION_EXPORT double OpusBindingVersionNumber;
//! Project version string for OpusBinding.
FOUNDATION_EXPORT const unsigned char OpusBindingVersionString[];
#import <OpusBinding/TGDataItem.h>
#import <OpusBinding/TGOggOpusWriter.h>
#import <OpusBinding/OggOpusReader.h>
@@ -0,0 +1,36 @@
#import "TGDataItem.h"
@interface TGDataItem () {
NSMutableData *_data;
}
@end
@implementation TGDataItem
- (instancetype)init {
self = [super init];
if (self != nil) {
_data = [[NSMutableData alloc] init];
}
return self;
}
- (instancetype)initWithData:(NSData *)data {
self = [super init];
if (self != nil) {
_data = [[NSMutableData alloc] init];
[self appendData:data];
}
return self;
}
- (void)appendData:(NSData *)data {
[_data appendData:data];
}
- (NSData *)data {
return _data;
}
@end
@@ -0,0 +1,857 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE Ogg CONTAINER SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2010 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: packing variable sized words into an octet stream
last mod: $Id: bitwise.c 18051 2011-08-04 17:56:39Z giles $
********************************************************************/
/* We're 'LSb' endian; if we write a word but read individual bits,
then we'll read the lsb first */
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <ogg/ogg.h>
#define BUFFER_INCREMENT 256
static const unsigned long mask[]=
{0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
0x3fffffff,0x7fffffff,0xffffffff };
static const unsigned int mask8B[]=
{0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
void oggpack_writeinit(oggpack_buffer *b){
memset(b,0,sizeof(*b));
b->ptr=b->buffer=_ogg_malloc(BUFFER_INCREMENT);
b->buffer[0]='\0';
b->storage=BUFFER_INCREMENT;
}
void oggpackB_writeinit(oggpack_buffer *b){
oggpack_writeinit(b);
}
int oggpack_writecheck(oggpack_buffer *b){
if(!b->ptr || !b->storage)return -1;
return 0;
}
int oggpackB_writecheck(oggpack_buffer *b){
return oggpack_writecheck(b);
}
void oggpack_writetrunc(oggpack_buffer *b,long bits){
long bytes=bits>>3;
if(b->ptr){
bits-=bytes*8;
b->ptr=b->buffer+bytes;
b->endbit=bits;
b->endbyte=bytes;
*b->ptr&=mask[bits];
}
}
void oggpackB_writetrunc(oggpack_buffer *b,long bits){
long bytes=bits>>3;
if(b->ptr){
bits-=bytes*8;
b->ptr=b->buffer+bytes;
b->endbit=bits;
b->endbyte=bytes;
*b->ptr&=mask8B[bits];
}
}
/* Takes only up to 32 bits. */
void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
if(bits<0 || bits>32) goto err;
if(b->endbyte>=b->storage-4){
void *ret;
if(!b->ptr)return;
if(b->storage>LONG_MAX-BUFFER_INCREMENT) goto err;
ret=_ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
if(!ret) goto err;
b->buffer=ret;
b->storage+=BUFFER_INCREMENT;
b->ptr=b->buffer+b->endbyte;
}
value&=mask[bits];
bits+=b->endbit;
b->ptr[0]|=value<<b->endbit;
if(bits>=8){
b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
if(bits>=16){
b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
if(bits>=24){
b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
if(bits>=32){
if(b->endbit)
b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
else
b->ptr[4]=0;
}
}
}
}
b->endbyte+=bits/8;
b->ptr+=bits/8;
b->endbit=bits&7;
return;
err:
oggpack_writeclear(b);
}
/* Takes only up to 32 bits. */
void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
if(bits<0 || bits>32) goto err;
if(b->endbyte>=b->storage-4){
void *ret;
if(!b->ptr)return;
if(b->storage>LONG_MAX-BUFFER_INCREMENT) goto err;
ret=_ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
if(!ret) goto err;
b->buffer=ret;
b->storage+=BUFFER_INCREMENT;
b->ptr=b->buffer+b->endbyte;
}
value=(value&mask[bits])<<(32-bits);
bits+=b->endbit;
b->ptr[0]|=value>>(24+b->endbit);
if(bits>=8){
b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
if(bits>=16){
b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
if(bits>=24){
b->ptr[3]=(unsigned char)(value>>(b->endbit));
if(bits>=32){
if(b->endbit)
b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
else
b->ptr[4]=0;
}
}
}
}
b->endbyte+=bits/8;
b->ptr+=bits/8;
b->endbit=bits&7;
return;
err:
oggpack_writeclear(b);
}
void oggpack_writealign(oggpack_buffer *b){
int bits=8-b->endbit;
if(bits<8)
oggpack_write(b,0,bits);
}
void oggpackB_writealign(oggpack_buffer *b){
int bits=8-b->endbit;
if(bits<8)
oggpackB_write(b,0,bits);
}
static void oggpack_writecopy_helper(oggpack_buffer *b,
void *source,
long bits,
void (*w)(oggpack_buffer *,
unsigned long,
int),
int msb){
unsigned char *ptr=(unsigned char *)source;
long bytes=bits/8;
bits-=bytes*8;
if(b->endbit){
int i;
/* unaligned copy. Do it the hard way. */
for(i=0;i<bytes;i++)
w(b,(unsigned long)(ptr[i]),8);
}else{
/* aligned block copy */
if(b->endbyte+bytes+1>=b->storage){
void *ret;
if(!b->ptr) goto err;
if(b->endbyte+bytes+BUFFER_INCREMENT>b->storage) goto err;
b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
ret=_ogg_realloc(b->buffer,b->storage);
if(!ret) goto err;
b->buffer=ret;
b->ptr=b->buffer+b->endbyte;
}
memmove(b->ptr,source,bytes);
b->ptr+=bytes;
b->endbyte+=bytes;
*b->ptr=0;
}
if(bits){
if(msb)
w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
else
w(b,(unsigned long)(ptr[bytes]),bits);
}
return;
err:
oggpack_writeclear(b);
}
void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
}
void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
}
void oggpack_reset(oggpack_buffer *b){
if(!b->ptr)return;
b->ptr=b->buffer;
b->buffer[0]=0;
b->endbit=b->endbyte=0;
}
void oggpackB_reset(oggpack_buffer *b){
oggpack_reset(b);
}
void oggpack_writeclear(oggpack_buffer *b){
if(b->buffer)_ogg_free(b->buffer);
memset(b,0,sizeof(*b));
}
void oggpackB_writeclear(oggpack_buffer *b){
oggpack_writeclear(b);
}
void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
memset(b,0,sizeof(*b));
b->buffer=b->ptr=buf;
b->storage=bytes;
}
void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
oggpack_readinit(b,buf,bytes);
}
/* Read in bits without advancing the bitptr; bits <= 32 */
long oggpack_look(oggpack_buffer *b,int bits){
unsigned long ret;
unsigned long m;
if(bits<0 || bits>32) return -1;
m=mask[bits];
bits+=b->endbit;
if(b->endbyte >= b->storage-4){
/* not the main path */
if(b->endbyte > b->storage-((bits+7)>>3)) return -1;
/* special case to avoid reading b->ptr[0], which might be past the end of
the buffer; also skips some useless accounting */
else if(!bits)return(0L);
}
ret=b->ptr[0]>>b->endbit;
if(bits>8){
ret|=b->ptr[1]<<(8-b->endbit);
if(bits>16){
ret|=b->ptr[2]<<(16-b->endbit);
if(bits>24){
ret|=b->ptr[3]<<(24-b->endbit);
if(bits>32 && b->endbit)
ret|=b->ptr[4]<<(32-b->endbit);
}
}
}
return(m&ret);
}
/* Read in bits without advancing the bitptr; bits <= 32 */
long oggpackB_look(oggpack_buffer *b,int bits){
unsigned long ret;
int m=32-bits;
if(m<0 || m>32) return -1;
bits+=b->endbit;
if(b->endbyte >= b->storage-4){
/* not the main path */
if(b->endbyte > b->storage-((bits+7)>>3)) return -1;
/* special case to avoid reading b->ptr[0], which might be past the end of
the buffer; also skips some useless accounting */
else if(!bits)return(0L);
}
ret=b->ptr[0]<<(24+b->endbit);
if(bits>8){
ret|=b->ptr[1]<<(16+b->endbit);
if(bits>16){
ret|=b->ptr[2]<<(8+b->endbit);
if(bits>24){
ret|=b->ptr[3]<<(b->endbit);
if(bits>32 && b->endbit)
ret|=b->ptr[4]>>(8-b->endbit);
}
}
}
return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
}
long oggpack_look1(oggpack_buffer *b){
if(b->endbyte>=b->storage)return(-1);
return((b->ptr[0]>>b->endbit)&1);
}
long oggpackB_look1(oggpack_buffer *b){
if(b->endbyte>=b->storage)return(-1);
return((b->ptr[0]>>(7-b->endbit))&1);
}
void oggpack_adv(oggpack_buffer *b,int bits){
bits+=b->endbit;
if(b->endbyte > b->storage-((bits+7)>>3)) goto overflow;
b->ptr+=bits/8;
b->endbyte+=bits/8;
b->endbit=bits&7;
return;
overflow:
b->ptr=NULL;
b->endbyte=b->storage;
b->endbit=1;
}
void oggpackB_adv(oggpack_buffer *b,int bits){
oggpack_adv(b,bits);
}
void oggpack_adv1(oggpack_buffer *b){
if(++(b->endbit)>7){
b->endbit=0;
b->ptr++;
b->endbyte++;
}
}
void oggpackB_adv1(oggpack_buffer *b){
oggpack_adv1(b);
}
/* bits <= 32 */
long oggpack_read(oggpack_buffer *b,int bits){
long ret;
unsigned long m;
if(bits<0 || bits>32) goto err;
m=mask[bits];
bits+=b->endbit;
if(b->endbyte >= b->storage-4){
/* not the main path */
if(b->endbyte > b->storage-((bits+7)>>3)) goto overflow;
/* special case to avoid reading b->ptr[0], which might be past the end of
the buffer; also skips some useless accounting */
else if(!bits)return(0L);
}
ret=b->ptr[0]>>b->endbit;
if(bits>8){
ret|=b->ptr[1]<<(8-b->endbit);
if(bits>16){
ret|=b->ptr[2]<<(16-b->endbit);
if(bits>24){
ret|=b->ptr[3]<<(24-b->endbit);
if(bits>32 && b->endbit){
ret|=b->ptr[4]<<(32-b->endbit);
}
}
}
}
ret&=m;
b->ptr+=bits/8;
b->endbyte+=bits/8;
b->endbit=bits&7;
return ret;
overflow:
err:
b->ptr=NULL;
b->endbyte=b->storage;
b->endbit=1;
return -1L;
}
/* bits <= 32 */
long oggpackB_read(oggpack_buffer *b,int bits){
long ret;
long m=32-bits;
if(m<0 || m>32) goto err;
bits+=b->endbit;
if(b->endbyte+4>=b->storage){
/* not the main path */
if(b->endbyte > b->storage-((bits+7)>>3)) goto overflow;
/* special case to avoid reading b->ptr[0], which might be past the end of
the buffer; also skips some useless accounting */
else if(!bits)return(0L);
}
ret=b->ptr[0]<<(24+b->endbit);
if(bits>8){
ret|=b->ptr[1]<<(16+b->endbit);
if(bits>16){
ret|=b->ptr[2]<<(8+b->endbit);
if(bits>24){
ret|=b->ptr[3]<<(b->endbit);
if(bits>32 && b->endbit)
ret|=b->ptr[4]>>(8-b->endbit);
}
}
}
ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
b->ptr+=bits/8;
b->endbyte+=bits/8;
b->endbit=bits&7;
return ret;
overflow:
err:
b->ptr=NULL;
b->endbyte=b->storage;
b->endbit=1;
return -1L;
}
long oggpack_read1(oggpack_buffer *b){
long ret;
if(b->endbyte >= b->storage) goto overflow;
ret=(b->ptr[0]>>b->endbit)&1;
b->endbit++;
if(b->endbit>7){
b->endbit=0;
b->ptr++;
b->endbyte++;
}
return ret;
overflow:
b->ptr=NULL;
b->endbyte=b->storage;
b->endbit=1;
return -1L;
}
long oggpackB_read1(oggpack_buffer *b){
long ret;
if(b->endbyte >= b->storage) goto overflow;
ret=(b->ptr[0]>>(7-b->endbit))&1;
b->endbit++;
if(b->endbit>7){
b->endbit=0;
b->ptr++;
b->endbyte++;
}
return ret;
overflow:
b->ptr=NULL;
b->endbyte=b->storage;
b->endbit=1;
return -1L;
}
long oggpack_bytes(oggpack_buffer *b){
return(b->endbyte+(b->endbit+7)/8);
}
long oggpack_bits(oggpack_buffer *b){
return(b->endbyte*8+b->endbit);
}
long oggpackB_bytes(oggpack_buffer *b){
return oggpack_bytes(b);
}
long oggpackB_bits(oggpack_buffer *b){
return oggpack_bits(b);
}
unsigned char *oggpack_get_buffer(oggpack_buffer *b){
return(b->buffer);
}
unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
return oggpack_get_buffer(b);
}
/* Self test of the bitwise routines; everything else is based on
them, so they damned well better be solid. */
#ifdef _V_SELFTEST
#include <stdio.h>
static int ilog(unsigned int v){
int ret=0;
while(v){
ret++;
v>>=1;
}
return(ret);
}
oggpack_buffer o;
oggpack_buffer r;
void report(char *in){
fprintf(stderr,"%s",in);
exit(1);
}
void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
long bytes,i;
unsigned char *buffer;
oggpack_reset(&o);
for(i=0;i<vals;i++)
oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
buffer=oggpack_get_buffer(&o);
bytes=oggpack_bytes(&o);
if(bytes!=compsize)report("wrong number of bytes!\n");
for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
report("wrote incorrect value!\n");
}
oggpack_readinit(&r,buffer,bytes);
for(i=0;i<vals;i++){
int tbit=bits?bits:ilog(b[i]);
if(oggpack_look(&r,tbit)==-1)
report("out of data!\n");
if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
report("looked at incorrect value!\n");
if(tbit==1)
if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
report("looked at single bit incorrect value!\n");
if(tbit==1){
if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
report("read incorrect single bit value!\n");
}else{
if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
report("read incorrect value!\n");
}
}
if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
}
void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
long bytes,i;
unsigned char *buffer;
oggpackB_reset(&o);
for(i=0;i<vals;i++)
oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
buffer=oggpackB_get_buffer(&o);
bytes=oggpackB_bytes(&o);
if(bytes!=compsize)report("wrong number of bytes!\n");
for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
report("wrote incorrect value!\n");
}
oggpackB_readinit(&r,buffer,bytes);
for(i=0;i<vals;i++){
int tbit=bits?bits:ilog(b[i]);
if(oggpackB_look(&r,tbit)==-1)
report("out of data!\n");
if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
report("looked at incorrect value!\n");
if(tbit==1)
if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
report("looked at single bit incorrect value!\n");
if(tbit==1){
if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
report("read incorrect single bit value!\n");
}else{
if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
report("read incorrect value!\n");
}
}
if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
}
int main(void){
unsigned char *buffer;
long bytes,i;
static unsigned long testbuffer1[]=
{18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
int test1size=43;
static unsigned long testbuffer2[]=
{216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
1233432,534,5,346435231,14436467,7869299,76326614,167548585,
85525151,0,12321,1,349528352};
int test2size=21;
static unsigned long testbuffer3[]=
{1,0,14,0,1,0,12,0,1,0,0,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0,1,1,1,1,1,0,0,1,
0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
int test3size=56;
static unsigned long large[]=
{2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
85525151,0,12321,1,2146528352};
int onesize=33;
static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
223,4};
static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
245,251,128};
int twosize=6;
static int two[6]={61,255,255,251,231,29};
static int twoB[6]={247,63,255,253,249,120};
int threesize=54;
static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
100,52,4,14,18,86,77,1};
static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
200,20,254,4,58,106,176,144,0};
int foursize=38;
static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
28,2,133,0,1};
static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
129,10,4,32};
int fivesize=45;
static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
84,75,159,2,1,0,132,192,8,0,0,18,22};
static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
172,150,169,129,79,128,0,6,4,32,0,27,9,0};
int sixsize=7;
static int six[7]={17,177,170,242,169,19,148};
static int sixB[7]={136,141,85,79,149,200,41};
/* Test read/write together */
/* Later we test against pregenerated bitstreams */
oggpack_writeinit(&o);
fprintf(stderr,"\nSmall preclipped packing (LSb): ");
cliptest(testbuffer1,test1size,0,one,onesize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nNull bit call (LSb): ");
cliptest(testbuffer3,test3size,0,two,twosize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nLarge preclipped packing (LSb): ");
cliptest(testbuffer2,test2size,0,three,threesize);
fprintf(stderr,"ok.");
fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
oggpack_reset(&o);
for(i=0;i<test2size;i++)
oggpack_write(&o,large[i],32);
buffer=oggpack_get_buffer(&o);
bytes=oggpack_bytes(&o);
oggpack_readinit(&r,buffer,bytes);
for(i=0;i<test2size;i++){
if(oggpack_look(&r,32)==-1)report("out of data. failed!");
if(oggpack_look(&r,32)!=large[i]){
fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
oggpack_look(&r,32),large[i]);
report("read incorrect value!\n");
}
oggpack_adv(&r,32);
}
if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
fprintf(stderr,"ok.");
fprintf(stderr,"\nSmall unclipped packing (LSb): ");
cliptest(testbuffer1,test1size,7,four,foursize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nLarge unclipped packing (LSb): ");
cliptest(testbuffer2,test2size,17,five,fivesize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
cliptest(testbuffer3,test3size,1,six,sixsize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nTesting read past end (LSb): ");
oggpack_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
for(i=0;i<64;i++){
if(oggpack_read(&r,1)!=0){
fprintf(stderr,"failed; got -1 prematurely.\n");
exit(1);
}
}
if(oggpack_look(&r,1)!=-1 ||
oggpack_read(&r,1)!=-1){
fprintf(stderr,"failed; read past end without -1.\n");
exit(1);
}
oggpack_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
fprintf(stderr,"failed 2; got -1 prematurely.\n");
exit(1);
}
if(oggpack_look(&r,18)!=0 ||
oggpack_look(&r,18)!=0){
fprintf(stderr,"failed 3; got -1 prematurely.\n");
exit(1);
}
if(oggpack_look(&r,19)!=-1 ||
oggpack_look(&r,19)!=-1){
fprintf(stderr,"failed; read past end without -1.\n");
exit(1);
}
if(oggpack_look(&r,32)!=-1 ||
oggpack_look(&r,32)!=-1){
fprintf(stderr,"failed; read past end without -1.\n");
exit(1);
}
oggpack_writeclear(&o);
fprintf(stderr,"ok.\n");
/********** lazy, cut-n-paste retest with MSb packing ***********/
/* Test read/write together */
/* Later we test against pregenerated bitstreams */
oggpackB_writeinit(&o);
fprintf(stderr,"\nSmall preclipped packing (MSb): ");
cliptestB(testbuffer1,test1size,0,oneB,onesize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nNull bit call (MSb): ");
cliptestB(testbuffer3,test3size,0,twoB,twosize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nLarge preclipped packing (MSb): ");
cliptestB(testbuffer2,test2size,0,threeB,threesize);
fprintf(stderr,"ok.");
fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
oggpackB_reset(&o);
for(i=0;i<test2size;i++)
oggpackB_write(&o,large[i],32);
buffer=oggpackB_get_buffer(&o);
bytes=oggpackB_bytes(&o);
oggpackB_readinit(&r,buffer,bytes);
for(i=0;i<test2size;i++){
if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
if(oggpackB_look(&r,32)!=large[i]){
fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
oggpackB_look(&r,32),large[i]);
report("read incorrect value!\n");
}
oggpackB_adv(&r,32);
}
if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
fprintf(stderr,"ok.");
fprintf(stderr,"\nSmall unclipped packing (MSb): ");
cliptestB(testbuffer1,test1size,7,fourB,foursize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nLarge unclipped packing (MSb): ");
cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
cliptestB(testbuffer3,test3size,1,sixB,sixsize);
fprintf(stderr,"ok.");
fprintf(stderr,"\nTesting read past end (MSb): ");
oggpackB_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
for(i=0;i<64;i++){
if(oggpackB_read(&r,1)!=0){
fprintf(stderr,"failed; got -1 prematurely.\n");
exit(1);
}
}
if(oggpackB_look(&r,1)!=-1 ||
oggpackB_read(&r,1)!=-1){
fprintf(stderr,"failed; read past end without -1.\n");
exit(1);
}
oggpackB_readinit(&r,(unsigned char *)"\0\0\0\0\0\0\0\0",8);
if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
fprintf(stderr,"failed 2; got -1 prematurely.\n");
exit(1);
}
if(oggpackB_look(&r,18)!=0 ||
oggpackB_look(&r,18)!=0){
fprintf(stderr,"failed 3; got -1 prematurely.\n");
exit(1);
}
if(oggpackB_look(&r,19)!=-1 ||
oggpackB_look(&r,19)!=-1){
fprintf(stderr,"failed; read past end without -1.\n");
exit(1);
}
if(oggpackB_look(&r,32)!=-1 ||
oggpackB_look(&r,32)!=-1){
fprintf(stderr,"failed; read past end without -1.\n");
exit(1);
}
oggpackB_writeclear(&o);
fprintf(stderr,"ok.\n\n");
return(0);
}
#endif /* _V_SELFTEST */
#undef BUFFER_INCREMENT
File diff suppressed because it is too large Load Diff
+210
View File
@@ -0,0 +1,210 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: toplevel libogg include
last mod: $Id: ogg.h 18044 2011-08-01 17:55:20Z gmaxwell $
********************************************************************/
#ifndef _OGG_H
#define _OGG_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <ogg/os_types.h>
typedef struct {
void *iov_base;
size_t iov_len;
} ogg_iovec_t;
typedef struct {
long endbyte;
int endbit;
unsigned char *buffer;
unsigned char *ptr;
long storage;
} oggpack_buffer;
/* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
typedef struct {
unsigned char *header;
long header_len;
unsigned char *body;
long body_len;
} ogg_page;
/* ogg_stream_state contains the current encode/decode state of a logical
Ogg bitstream **********************************************************/
typedef struct {
unsigned char *body_data; /* bytes from packet bodies */
long body_storage; /* storage elements allocated */
long body_fill; /* elements stored; fill mark */
long body_returned; /* elements of fill returned */
int *lacing_vals; /* The values that will go to the segment table */
ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
this way, but it is simple coupled to the
lacing fifo */
long lacing_storage;
long lacing_fill;
long lacing_packet;
long lacing_returned;
unsigned char header[282]; /* working space for header encode */
int header_fill;
int e_o_s; /* set when we have buffered the last packet in the
logical bitstream */
int b_o_s; /* set after we've written the initial page
of a logical bitstream */
long serialno;
long pageno;
ogg_int64_t packetno; /* sequence number for decode; the framing
knows where there's a hole in the data,
but we need coupling so that the codec
(which is in a separate abstraction
layer) also knows about the gap */
ogg_int64_t granulepos;
} ogg_stream_state;
/* ogg_packet is used to encapsulate the data and metadata belonging
to a single raw Ogg/Vorbis packet *************************************/
typedef struct {
unsigned char *packet;
long bytes;
long b_o_s;
long e_o_s;
ogg_int64_t granulepos;
ogg_int64_t packetno; /* sequence number for decode; the framing
knows where there's a hole in the data,
but we need coupling so that the codec
(which is in a separate abstraction
layer) also knows about the gap */
} ogg_packet;
typedef struct {
unsigned char *data;
int storage;
int fill;
int returned;
int unsynced;
int headerbytes;
int bodybytes;
} ogg_sync_state;
/* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
extern void oggpack_writeinit(oggpack_buffer *b);
extern int oggpack_writecheck(oggpack_buffer *b);
extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
extern void oggpack_writealign(oggpack_buffer *b);
extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
extern void oggpack_reset(oggpack_buffer *b);
extern void oggpack_writeclear(oggpack_buffer *b);
extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
extern long oggpack_look(oggpack_buffer *b,int bits);
extern long oggpack_look1(oggpack_buffer *b);
extern void oggpack_adv(oggpack_buffer *b,int bits);
extern void oggpack_adv1(oggpack_buffer *b);
extern long oggpack_read(oggpack_buffer *b,int bits);
extern long oggpack_read1(oggpack_buffer *b);
extern long oggpack_bytes(oggpack_buffer *b);
extern long oggpack_bits(oggpack_buffer *b);
extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
extern void oggpackB_writeinit(oggpack_buffer *b);
extern int oggpackB_writecheck(oggpack_buffer *b);
extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
extern void oggpackB_writealign(oggpack_buffer *b);
extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
extern void oggpackB_reset(oggpack_buffer *b);
extern void oggpackB_writeclear(oggpack_buffer *b);
extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
extern long oggpackB_look(oggpack_buffer *b,int bits);
extern long oggpackB_look1(oggpack_buffer *b);
extern void oggpackB_adv(oggpack_buffer *b,int bits);
extern void oggpackB_adv1(oggpack_buffer *b);
extern long oggpackB_read(oggpack_buffer *b,int bits);
extern long oggpackB_read1(oggpack_buffer *b);
extern long oggpackB_bytes(oggpack_buffer *b);
extern long oggpackB_bits(oggpack_buffer *b);
extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
/* Ogg BITSTREAM PRIMITIVES: encoding **************************/
extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
extern int ogg_stream_iovecin(ogg_stream_state *os, ogg_iovec_t *iov,
int count, long e_o_s, ogg_int64_t granulepos);
extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
extern int ogg_stream_pageout_fill(ogg_stream_state *os, ogg_page *og, int nfill);
extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
extern int ogg_stream_flush_fill(ogg_stream_state *os, ogg_page *og, int nfill);
/* Ogg BITSTREAM PRIMITIVES: decoding **************************/
extern int ogg_sync_init(ogg_sync_state *oy);
extern int ogg_sync_clear(ogg_sync_state *oy);
extern int ogg_sync_reset(ogg_sync_state *oy);
extern int ogg_sync_destroy(ogg_sync_state *oy);
extern int ogg_sync_check(ogg_sync_state *oy);
extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
/* Ogg BITSTREAM PRIMITIVES: general ***************************/
extern int ogg_stream_init(ogg_stream_state *os,int serialno);
extern int ogg_stream_clear(ogg_stream_state *os);
extern int ogg_stream_reset(ogg_stream_state *os);
extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
extern int ogg_stream_destroy(ogg_stream_state *os);
extern int ogg_stream_check(ogg_stream_state *os);
extern int ogg_stream_eos(ogg_stream_state *os);
extern void ogg_page_checksum_set(ogg_page *og);
extern int ogg_page_version(const ogg_page *og);
extern int ogg_page_continued(const ogg_page *og);
extern int ogg_page_bos(const ogg_page *og);
extern int ogg_page_eos(const ogg_page *og);
extern ogg_int64_t ogg_page_granulepos(const ogg_page *og);
extern int ogg_page_serialno(const ogg_page *og);
extern long ogg_page_pageno(const ogg_page *og);
extern int ogg_page_packets(const ogg_page *og);
extern void ogg_packet_clear(ogg_packet *op);
#ifdef __cplusplus
}
#endif
#endif /* _OGG_H */
@@ -0,0 +1,147 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: #ifdef jail to whip a few platforms into the UNIX ideal.
last mod: $Id: os_types.h 17712 2010-12-03 17:10:02Z xiphmont $
********************************************************************/
#ifndef _OS_TYPES_H
#define _OS_TYPES_H
/* make it easy on the folks that want to compile the libs with a
different malloc than stdlib */
#define _ogg_malloc malloc
#define _ogg_calloc calloc
#define _ogg_realloc realloc
#define _ogg_free free
#if defined(_WIN32)
# if defined(__CYGWIN__)
# include <stdint.h>
typedef int16_t ogg_int16_t;
typedef uint16_t ogg_uint16_t;
typedef int32_t ogg_int32_t;
typedef uint32_t ogg_uint32_t;
typedef int64_t ogg_int64_t;
typedef uint64_t ogg_uint64_t;
# elif defined(__MINGW32__)
# include <sys/types.h>
typedef short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long ogg_int64_t;
typedef unsigned long long ogg_uint64_t;
# elif defined(__MWERKS__)
typedef long long ogg_int64_t;
typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
# else
/* MSVC/Borland */
typedef __int64 ogg_int64_t;
typedef __int32 ogg_int32_t;
typedef unsigned __int32 ogg_uint32_t;
typedef __int16 ogg_int16_t;
typedef unsigned __int16 ogg_uint16_t;
# endif
#elif defined(__MACOS__)
# include <sys/types.h>
typedef SInt16 ogg_int16_t;
typedef UInt16 ogg_uint16_t;
typedef SInt32 ogg_int32_t;
typedef UInt32 ogg_uint32_t;
typedef SInt64 ogg_int64_t;
#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */
# include <inttypes.h>
typedef int16_t ogg_int16_t;
typedef uint16_t ogg_uint16_t;
typedef int32_t ogg_int32_t;
typedef uint32_t ogg_uint32_t;
typedef int64_t ogg_int64_t;
#elif defined(__HAIKU__)
/* Haiku */
# include <sys/types.h>
typedef short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long ogg_int64_t;
#elif defined(__BEOS__)
/* Be */
# include <inttypes.h>
typedef int16_t ogg_int16_t;
typedef uint16_t ogg_uint16_t;
typedef int32_t ogg_int32_t;
typedef uint32_t ogg_uint32_t;
typedef int64_t ogg_int64_t;
#elif defined (__EMX__)
/* OS/2 GCC */
typedef short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long ogg_int64_t;
#elif defined (DJGPP)
/* DJGPP */
typedef short ogg_int16_t;
typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long ogg_int64_t;
#elif defined(R5900)
/* PS2 EE */
typedef long ogg_int64_t;
typedef int ogg_int32_t;
typedef unsigned ogg_uint32_t;
typedef short ogg_int16_t;
#elif defined(__SYMBIAN32__)
/* Symbian GCC */
typedef signed short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
typedef signed int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long int ogg_int64_t;
#elif defined(__TMS320C6X__)
/* TI C64x compiler */
typedef signed short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
typedef signed int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long int ogg_int64_t;
#else
# include <ogg/config_types.h>
#endif
#endif /* _OS_TYPES_H */
@@ -0,0 +1,245 @@
/* Copyright (C)2012 Xiph.Org Foundation
Copyright (C)2012 Gregory Maxwell
Copyright (C)2012 Jean-Marc Valin
File: diag_range.c
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef _WIN32
#define I64FORMAT "I64d"
#define I64uFORMAT "I64u"
#else
#define I64FORMAT "lld"
#define I64uFORMAT "llu"
#endif
#include <stdio.h>
#include <opus/opus.h>
#include "diag_range.h"
/*This is some non-exported code copied wholesale from libopus.
*Normal programs shouldn't need these functions, but we use them here
*to parse deep inside multichannel packets in order to get diagnostic
*data for save-range. If you're thinking about copying it and you aren't
*making an opus stream diagnostic tool, you're probably doing something
*wrong.*/
static int parse_size(const unsigned char *data, opus_int32 len, short *size)
{
if (len<1)
{
*size = -1;
return -1;
} else if (data[0]<252)
{
*size = data[0];
return 1;
} else if (len<2)
{
*size = -1;
return -1;
} else {
*size = 4*data[1] + data[0];
return 2;
}
}
static int opus_packet_parse_impl(const unsigned char *data, opus_int32 len,
int self_delimited, unsigned char *out_toc,
const unsigned char *frames[48], short size[48], int *payload_offset)
{
int i, bytes;
int count;
int cbr;
unsigned char ch, toc;
int framesize;
int last_size;
const unsigned char *data0 = data;
if (size==NULL)
return OPUS_BAD_ARG;
framesize = opus_packet_get_samples_per_frame(data, 48000);
cbr = 0;
toc = *data++;
len--;
last_size = len;
switch (toc&0x3)
{
/* One frame */
case 0:
count=1;
break;
/* Two CBR frames */
case 1:
count=2;
cbr = 1;
if (!self_delimited)
{
if (len&0x1)
return OPUS_INVALID_PACKET;
size[0] = last_size = len/2;
}
break;
/* Two VBR frames */
case 2:
count = 2;
bytes = parse_size(data, len, size);
len -= bytes;
if (size[0]<0 || size[0] > len)
return OPUS_INVALID_PACKET;
data += bytes;
last_size = len-size[0];
break;
/* Multiple CBR/VBR frames (from 0 to 120 ms) */
case 3:
if (len<1)
return OPUS_INVALID_PACKET;
/* Number of frames encoded in bits 0 to 5 */
ch = *data++;
count = ch&0x3F;
if (count <= 0 || framesize*count > 5760)
return OPUS_INVALID_PACKET;
len--;
/* Padding flag is bit 6 */
if (ch&0x40)
{
int padding=0;
int p;
do {
if (len<=0)
return OPUS_INVALID_PACKET;
p = *data++;
len--;
padding += p==255 ? 254: p;
} while (p==255);
len -= padding;
}
if (len<0)
return OPUS_INVALID_PACKET;
/* VBR flag is bit 7 */
cbr = !(ch&0x80);
if (!cbr)
{
/* VBR case */
last_size = len;
for (i=0;i<count-1;i++)
{
bytes = parse_size(data, len, size+i);
len -= bytes;
if (size[i]<0 || size[i] > len)
return OPUS_INVALID_PACKET;
data += bytes;
last_size -= bytes+size[i];
}
if (last_size<0)
return OPUS_INVALID_PACKET;
} else if (!self_delimited)
{
/* CBR case */
last_size = len/count;
if (last_size*count!=len)
return OPUS_INVALID_PACKET;
for (i=0;i<count-1;i++)
size[i] = last_size;
}
break;
}
/* Self-delimited framing has an extra size for the last frame. */
if (self_delimited)
{
bytes = parse_size(data, len, size+count-1);
len -= bytes;
if (size[count-1]<0 || size[count-1] > len)
return OPUS_INVALID_PACKET;
data += bytes;
/* For CBR packets, apply the size to all the frames. */
if (cbr)
{
if (size[count-1]*count > len)
return OPUS_INVALID_PACKET;
for (i=0;i<count-1;i++)
size[i] = size[count-1];
} else if(size[count-1] > last_size)
return OPUS_INVALID_PACKET;
} else
{
/* Because it's not encoded explicitly, it's possible the size of the
last packet (or all the packets, for the CBR case) is larger than
1275. Reject them here.*/
if (last_size > 1275)
return OPUS_INVALID_PACKET;
size[count-1] = last_size;
}
if (frames)
{
for (i=0;i<count;i++)
{
frames[i] = data;
data += size[i];
}
}
if (out_toc)
*out_toc = toc;
if (payload_offset)
*payload_offset = data-data0;
return count;
}
void save_range(FILE *frange, int frame_size, unsigned char *packet, int nbBytes, opus_uint32 *rngs, int nb_streams){
int i, parsed_size;
const unsigned char *subpkt;
static const char *bw_strings[5]={"NB","MB","WB","SWB","FB"};
static const char *mode_strings[3]={"LP","HYB","MDCT"};
fprintf(frange,"%d, %d, ",frame_size,nbBytes);
subpkt=packet;
parsed_size=nbBytes;
for(i=0;i<nb_streams;i++){
int j,payload_offset,nf;
const unsigned char *frames[48];
unsigned char toc;
short size[48];
payload_offset=0;
nf=opus_packet_parse_impl(subpkt,parsed_size,i+1!=nb_streams,
&toc,frames,size,&payload_offset);
fprintf(frange,"[[%d",(int)(frames[0]-subpkt));
for(j=0;j<nf;j++)fprintf(frange,", %d",size[j]);
fprintf(frange,"], %s, %s, %c, %d",
mode_strings[((((subpkt[0]>>3)+48)&92)+4)>>5],
bw_strings[opus_packet_get_bandwidth(subpkt)-OPUS_BANDWIDTH_NARROWBAND],
subpkt[0]&4?'S':'M',opus_packet_get_samples_per_frame(subpkt,48000));
fprintf(frange,", %" I64uFORMAT "]%s",(unsigned long long)rngs[i],i+1==nb_streams?"\n":", ");
parsed_size-=payload_offset;
subpkt+=payload_offset;
}
}
@@ -0,0 +1,28 @@
/* Copyright (C)2012 Xiph.Org Foundation
File: diag_range.h
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
void save_range(FILE *frange, int frame_size, unsigned char *packet, int nbBytes, opus_uint32 *rngs, int nb_streams);
@@ -0,0 +1,286 @@
/* Copyright (C)2012 Xiph.Org Foundation
File: opus_header.c
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "opus_header.h"
#include <string.h>
#include <stdio.h>
/* Header contents:
- "OpusHead" (64 bits)
- version number (8 bits)
- Channels C (8 bits)
- Pre-skip (16 bits)
- Sampling rate (32 bits)
- Gain in dB (16 bits, S7.8)
- Mapping (8 bits, 0=single stream (mono/stereo) 1=Vorbis mapping,
2..254: reserved, 255: multistream with no mapping)
- if (mapping != 0)
- N = totel number of streams (8 bits)
- M = number of paired streams (8 bits)
- C times channel origin
- if (C<2*M)
- stream = byte/2
- if (byte&0x1 == 0)
- left
else
- right
- else
- stream = byte-M
*/
typedef struct {
unsigned char *data;
int maxlen;
int pos;
} Packet;
typedef struct {
const unsigned char *data;
int maxlen;
int pos;
} ROPacket;
static int write_uint32(Packet *p, ogg_uint32_t val)
{
if (p->pos>p->maxlen-4)
return 0;
p->data[p->pos ] = (val ) & 0xFF;
p->data[p->pos+1] = (val>> 8) & 0xFF;
p->data[p->pos+2] = (val>>16) & 0xFF;
p->data[p->pos+3] = (val>>24) & 0xFF;
p->pos += 4;
return 1;
}
static int write_uint16(Packet *p, ogg_uint16_t val)
{
if (p->pos>p->maxlen-2)
return 0;
p->data[p->pos ] = (val ) & 0xFF;
p->data[p->pos+1] = (val>> 8) & 0xFF;
p->pos += 2;
return 1;
}
static int write_chars(Packet *p, const unsigned char *str, int nb_chars)
{
int i;
if (p->pos>p->maxlen-nb_chars)
return 0;
for (i=0;i<nb_chars;i++)
p->data[p->pos++] = str[i];
return 1;
}
static int read_uint32(ROPacket *p, ogg_uint32_t *val)
{
if (p->pos>p->maxlen-4)
return 0;
*val = (ogg_uint32_t)p->data[p->pos ];
*val |= (ogg_uint32_t)p->data[p->pos+1]<< 8;
*val |= (ogg_uint32_t)p->data[p->pos+2]<<16;
*val |= (ogg_uint32_t)p->data[p->pos+3]<<24;
p->pos += 4;
return 1;
}
static int read_uint16(ROPacket *p, ogg_uint16_t *val)
{
if (p->pos>p->maxlen-2)
return 0;
*val = (ogg_uint16_t)p->data[p->pos ];
*val |= (ogg_uint16_t)p->data[p->pos+1]<<8;
p->pos += 2;
return 1;
}
static int read_chars(ROPacket *p, unsigned char *str, int nb_chars)
{
int i;
if (p->pos>p->maxlen-nb_chars)
return 0;
for (i=0;i<nb_chars;i++)
str[i] = p->data[p->pos++];
return 1;
}
int opus_header_parse(const unsigned char *packet, int len, OpusHeader *h)
{
int i;
char str[9];
ROPacket p;
unsigned char ch;
ogg_uint16_t shortval;
p.data = packet;
p.maxlen = len;
p.pos = 0;
str[8] = 0;
if (len<19)return 0;
read_chars(&p, (unsigned char*)str, 8);
if (memcmp(str, "OpusHead", 8)!=0)
return 0;
if (!read_chars(&p, &ch, 1))
return 0;
h->version = ch;
if((h->version&240) != 0) /* Only major version 0 supported. */
return 0;
if (!read_chars(&p, &ch, 1))
return 0;
h->channels = ch;
if (h->channels == 0)
return 0;
if (!read_uint16(&p, &shortval))
return 0;
h->preskip = shortval;
if (!read_uint32(&p, &h->input_sample_rate))
return 0;
if (!read_uint16(&p, &shortval))
return 0;
h->gain = (short)shortval;
if (!read_chars(&p, &ch, 1))
return 0;
h->channel_mapping = ch;
if (h->channel_mapping != 0)
{
if (!read_chars(&p, &ch, 1))
return 0;
if (ch<1)
return 0;
h->nb_streams = ch;
if (!read_chars(&p, &ch, 1))
return 0;
if (ch>h->nb_streams || (ch+h->nb_streams)>255)
return 0;
h->nb_coupled = ch;
/* Multi-stream support */
for (i=0;i<h->channels;i++)
{
if (!read_chars(&p, &h->stream_map[i], 1))
return 0;
if (h->stream_map[i]>(h->nb_streams+h->nb_coupled) && h->stream_map[i]!=255)
return 0;
}
} else {
if(h->channels>2)
return 0;
h->nb_streams = 1;
h->nb_coupled = h->channels>1;
h->stream_map[0]=0;
h->stream_map[1]=1;
}
/*For version 0/1 we know there won't be any more data
so reject any that have data past the end.*/
if ((h->version==0 || h->version==1) && p.pos != len)
return 0;
return 1;
}
int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len)
{
int i;
Packet p;
unsigned char ch;
p.data = packet;
p.maxlen = len;
p.pos = 0;
if (len<19)return 0;
if (!write_chars(&p, (const unsigned char*)"OpusHead", 8))
return 0;
/* Version is 1 */
ch = 1;
if (!write_chars(&p, &ch, 1))
return 0;
ch = h->channels;
if (!write_chars(&p, &ch, 1))
return 0;
if (!write_uint16(&p, h->preskip))
return 0;
if (!write_uint32(&p, h->input_sample_rate))
return 0;
if (!write_uint16(&p, h->gain))
return 0;
ch = h->channel_mapping;
if (!write_chars(&p, &ch, 1))
return 0;
if (h->channel_mapping != 0)
{
ch = h->nb_streams;
if (!write_chars(&p, &ch, 1))
return 0;
ch = h->nb_coupled;
if (!write_chars(&p, &ch, 1))
return 0;
/* Multi-stream support */
for (i=0;i<h->channels;i++)
{
if (!write_chars(&p, &h->stream_map[i], 1))
return 0;
}
}
return p.pos;
}
/* This is just here because it's a convenient file linked by both opusenc and
opusdec (to guarantee this maps stays in sync). */
const int wav_permute_matrix[8][8] =
{
{0}, /* 1.0 mono */
{0,1}, /* 2.0 stereo */
{0,2,1}, /* 3.0 channel ('wide') stereo */
{0,1,2,3}, /* 4.0 discrete quadraphonic */
{0,2,1,3,4}, /* 5.0 surround */
{0,2,1,4,5,3}, /* 5.1 surround */
{0,2,1,5,6,4,3}, /* 6.1 surround */
{0,2,1,6,7,4,5,3} /* 7.1 surround (classic theater 8-track) */
};
@@ -0,0 +1,51 @@
/* Copyright (C)2012 Xiph.Org Foundation
File: opus_header.h
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OPUS_HEADER_H
#define OPUS_HEADER_H
#include <ogg/ogg.h>
typedef struct {
int version;
int channels; /* Number of channels: 1..255 */
int preskip;
ogg_uint32_t input_sample_rate;
int gain; /* in dB S7.8 should be zero whenever possible */
int channel_mapping;
/* The rest is only used if channel_mapping != 0 */
int nb_streams;
int nb_coupled;
unsigned char stream_map[255];
} OpusHeader;
int opus_header_parse(const unsigned char *header, int len, OpusHeader *h);
int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len);
extern const int wav_permute_matrix[8][8];
#endif
@@ -0,0 +1,865 @@
#include <opus/opus_types.h>
#include <ogg/ogg.h>
#import "TGDataItem.h"
#import "TGOggOpusWriter.h"
#ifdef ENABLE_NLS
#include <libintl.h>
#define _(X) gettext(X)
#else
#define _(X) (X)
#define textdomain(X)
#define bindtextdomain(X, Y)
#endif
#ifdef gettext_noop
#define N_(X) gettext_noop(X)
#else
#define N_(X) (X)
#endif
typedef struct
{
void *readdata;
opus_int64 total_samples_per_channel;
int rawmode;
int channels;
long rate;
int gain;
int samplesize;
int endianness;
char *infilename;
int ignorelength;
int skip;
int extraout;
char *comments;
int comments_length;
int copy_comments;
} oe_enc_opt;
typedef struct
{
int (*id_func)(unsigned char *buf, int len); /* Returns true if can load file */
int id_data_len; /* Amount of data needed to id whether this can load the file */
int (*open_func)(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen);
void (*close_func)(void *);
char *format;
char *description;
} input_format;
#include <opus/opus.h>
#include <ogg/ogg.h>
#include "opus_header.h"
static bool comment_init(char **comments, int* length, const char *vendor_string);
static bool comment_add(char **comments, int* length, char *tag, char *val);
static bool comment_pad(char **comments, int* length, int amount);
static inline int writeOggPage(ogg_page *page, TGDataItem *fileItem)
{
int written = (int)(page->header_len + page->body_len);
NSMutableData *data = [[NSMutableData alloc] init];
[data appendBytes:page->header length:page->header_len];
[data appendBytes:page->body length:page->body_len];
[fileItem appendData:data];
return MAX(0, written);
}
@interface TGOggOpusWriter ()
{
TGDataItem *_dataItem;
OpusEncoder *_encoder;
uint8_t *_packet;
oe_enc_opt inopt;
ogg_stream_state os;
ogg_page og;
ogg_packet op;
ogg_int64_t last_granulepos;
ogg_int64_t enc_granulepos;
int last_segments;
int eos;
OpusHeader header;
ogg_int32_t _packetId;
int size_segments;
opus_int64 nb_encoded;
opus_int64 bytes_written;
opus_int64 pages_out;
opus_int64 total_bytes;
opus_int64 total_samples;
opus_int32 nb_samples;
opus_int32 peak_bytes;
opus_int32 min_bytes;
int max_frame_bytes;
opus_int32 bitrate;
opus_int32 rate;
opus_int32 coding_rate;
opus_int32 frame_size;
int with_cvbr;
int max_ogg_delay;
int comment_padding;
int serialno;
opus_int32 lookahead;
}
@property (nonatomic) ogg_sync_state syncState;
@end
@implementation TGOggOpusWriter
- (instancetype)init
{
self = [super init];
if (self != nil)
{
bitrate = 30 * 1024;
rate = 48000;
coding_rate = 48000;
frame_size = 960;
with_cvbr = 1;
max_ogg_delay = 48000;
comment_padding = 512;
_packetId = -1;
}
return self;
}
- (void)dealloc {
[self cleanup];
}
- (void)cleanup
{
if (_encoder != NULL)
{
opus_encoder_destroy(_encoder);
_encoder = NULL;
}
ogg_stream_clear(&os);
if (_packet != NULL)
{
free(_packet);
_packet = NULL;
}
}
- (bool)beginWithDataItem:(TGDataItem *)dataItem
{
_dataItem = dataItem;
inopt.channels = 1;
inopt.rate = coding_rate=rate;
inopt.gain = 0;
inopt.samplesize = 16;
inopt.endianness = 0;
inopt.rawmode = 0;
inopt.ignorelength = 0;
inopt.copy_comments = 0;
arc4random_buf(&serialno, sizeof(serialno));
const char *opus_version = opus_get_version_string();
comment_init(&inopt.comments, &inopt.comments_length, opus_version);
// bitrate = 16 * 1024;
// inopt.rawmode = 1;
// inopt.ignorelength = 1;
// inopt.samplesize = 16;
// inopt.rate = 16000;
// inopt.channels = 1;
rate = (opus_int32)inopt.rate;
inopt.skip = 0;
// In order to code the complete length we'll need to do a little padding
//setup_padder(&inopt, &original_samples);
if (rate > 24000)
coding_rate = 48000;
else if (rate > 16000)
coding_rate = 24000;
else if (rate > 12000)
coding_rate = 16000;
else if (rate > 8000)
coding_rate = 12000;
else
coding_rate = 8000;
// Scale the resampler complexity, but only for 48000 output because the near-cutoff behavior matters a lot more at lower rates
if (rate != coding_rate)
{
NSLog(@"Invalid rate");
return false;
}
header.channels = 1;
header.channel_mapping = 0;
header.input_sample_rate = rate;
header.gain = inopt.gain;
header.nb_streams = 1;
int result = OPUS_OK;
_encoder = opus_encoder_create(coding_rate, 1, OPUS_APPLICATION_AUDIO, &result);
if (result != OPUS_OK)
{
NSLog(@"Error cannot create encoder: %s", opus_strerror(result));
return false;
}
min_bytes = max_frame_bytes = (1275 * 3 + 7) * header.nb_streams;
_packet = malloc(max_frame_bytes);
result = opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(bitrate));
if (result != OPUS_OK)
{
NSLog(@"Error OPUS_SET_BITRATE returned: %s", opus_strerror(result));
return false;
}
/*result = opus_encoder_ctl(_encoder, OPUS_SET_VBR(1));
if (result != OPUS_OK)
{
NSLog(@"Error OPUS_SET_VBR returned: %s", opus_strerror(result));
return false;
}*/
/*ret = opus_multistream_encoder_ctl(st, OPUS_SET_VBR_CONSTRAINT(1));
if (ret != OPUS_OK)
{
NSLog(@"Error OPUS_SET_VBR_CONSTRAINT returned: %s", opus_strerror(ret));
return false;
}*/
/*ret = opus_multistream_encoder_ctl(st, OPUS_SET_COMPLEXITY(complexity));
if(ret != OPUS_OK)
{
NSLog(@"Error OPUS_SET_COMPLEXITY returned: %s", opus_strerror(ret));
return false;
}*/
/*result = opus_encoder_ctl(st, OPUS_SET_PACKET_LOSS_PERC(expect_loss));
if (ret != OPUS_OK)
{
NSLog(@"Error OPUS_SET_PACKET_LOSS_PERC returned: %s", opus_strerror(ret));
return false;
}*/
#ifdef OPUS_SET_LSB_DEPTH
result = opus_encoder_ctl(_encoder, OPUS_SET_LSB_DEPTH(MAX(8, MIN(24, inopt.samplesize))));
if (result != OPUS_OK)
{
NSLog(@"Warning OPUS_SET_LSB_DEPTH returned: %s", opus_strerror(result));
}
#endif
// We do the lookahead check late so user CTLs can change it
result = opus_encoder_ctl(_encoder, OPUS_GET_LOOKAHEAD(&lookahead));
if (result != OPUS_OK)
{
NSLog(@"Error OPUS_GET_LOOKAHEAD returned: %s", opus_strerror(result));
return false;
}
inopt.skip += lookahead;
// Regardless of the rate we're coding at the ogg timestamping/skip is always timed at 48000.
header.preskip = (int)(inopt.skip * (48000.0 / coding_rate));
// Extra samples that need to be read to compensate for the pre-skip
inopt.extraout = (int)(header.preskip * (rate / 48000.0));
// Initialize Ogg stream struct
if (ogg_stream_init(&os, serialno) == -1)
{
NSLog(@"Error: stream init failed");
return false;
}
// Write header
{
unsigned char header_data[100];
int packet_size = opus_header_to_packet(&header, header_data, 100);
op.packet = header_data;
op.bytes = packet_size;
op.b_o_s = 1;
op.e_o_s = 0;
op.granulepos = 0;
op.packetno = 0;
ogg_stream_packetin(&os, &op);
while ((result = ogg_stream_flush(&os, &og)))
{
if (!result)
break;
int pageBytesWritten = writeOggPage(&og, _dataItem);
if (pageBytesWritten != og.header_len + og.body_len)
{
NSLog(@"Error: failed writing header to output stream");
return false;
}
bytes_written += pageBytesWritten;
pages_out++;
}
comment_pad(&inopt.comments, &inopt.comments_length, comment_padding);
op.packet = (unsigned char *)inopt.comments;
op.bytes = inopt.comments_length;
op.b_o_s = 0;
op.e_o_s = 0;
op.granulepos = 0;
op.packetno = 1;
ogg_stream_packetin(&os, &op);
}
// Writing the rest of the opus header packets
while ((result = ogg_stream_flush(&os, &og)))
{
if (result == 0)
break;
int writtenPageBytes = writeOggPage(&og, _dataItem);
if (writtenPageBytes != og.header_len + og.body_len)
{
NSLog(@"Error: failed writing header to output stream");
return false;
}
bytes_written += writtenPageBytes;
pages_out++;
}
free(inopt.comments);
return true;
}
- (bool)parseExistingOpusFile:(NSData *)data
{
ogg_sync_init(&_syncState);
char *buffer = ogg_sync_buffer(&_syncState, (long)data.length);
memcpy(buffer, data.bytes, data.length);
ogg_sync_wrote(&_syncState, (long)data.length);
ogg_stream_state tempStream;
ogg_page page;
ogg_packet packet;
bool headerParsed = false;
bool foundStream = false;
ogg_int64_t finalGranulePos = 0;
while (ogg_sync_pageout(&_syncState, &page) == 1) {
if (!foundStream) {
serialno = ogg_page_serialno(&page);
if (ogg_stream_init(&tempStream, serialno) != 0) {
ogg_sync_clear(&_syncState);
return false;
}
foundStream = true;
}
if (ogg_page_serialno(&page) == serialno) {
ogg_stream_pagein(&tempStream, &page);
if (ogg_page_granulepos(&page) != -1) {
finalGranulePos = ogg_page_granulepos(&page);
}
while (ogg_stream_packetout(&tempStream, &packet) == 1) {
if (!headerParsed && packet.packetno == 0) {
if (![self parseOpusHeader:packet.packet length:packet.bytes]) {
ogg_stream_clear(&tempStream);
ogg_sync_clear(&_syncState);
return false;
}
headerParsed = true;
}
_packetId = (ogg_int32_t)packet.packetno;
if (packet.granulepos != -1) {
enc_granulepos = packet.granulepos;
last_granulepos = packet.granulepos;
finalGranulePos = packet.granulepos;
}
}
}
}
if (finalGranulePos > header.preskip) {
opus_int64 samples = finalGranulePos - header.preskip;
total_samples = (samples * rate) / 48000;
} else {
total_samples = 0;
}
ogg_stream_clear(&tempStream);
ogg_sync_clear(&_syncState);
if (!headerParsed) {
return false;
}
return true;
}
- (bool)parseOpusHeader:(unsigned char *)data length:(long)length
{
if (length < 19) {
NSLog(@"Opus header too short");
return false;
}
if (memcmp(data, "OpusHead", 8) != 0) {
NSLog(@"Invalid Opus header signature");
return false;
}
header.channels = data[9];
header.preskip = data[10] | (data[11] << 8);
header.input_sample_rate = data[12] | (data[13] << 8) | (data[14] << 16) | (data[15] << 24);
header.gain = (signed short)(data[16] | (data[17] << 8));
header.channel_mapping = data[18];
if (header.channels == 0) {
return false;
}
rate = header.input_sample_rate;
coding_rate = rate;
if (rate > 24000)
coding_rate = 48000;
else if (rate > 16000)
coding_rate = 24000;
else if (rate > 12000)
coding_rate = 16000;
else if (rate > 8000)
coding_rate = 12000;
else
coding_rate = 8000;
header.nb_streams = 1;
return true;
}
- (bool)initializeEncoderForAppend
{
bytes_written = _dataItem.data.length;
inopt.channels = header.channels;
inopt.rate = rate;
inopt.gain = header.gain;
inopt.samplesize = 16;
inopt.endianness = 0;
inopt.rawmode = 0;
inopt.ignorelength = 0;
inopt.copy_comments = 0;
int result = OPUS_OK;
_encoder = opus_encoder_create(coding_rate, header.channels, OPUS_APPLICATION_AUDIO, &result);
if (result != OPUS_OK) {
NSLog(@"Error cannot create encoder: %s", opus_strerror(result));
return false;
}
bitrate = 30 * 1024;
frame_size = 960;
opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(bitrate));
#ifdef OPUS_SET_LSB_DEPTH
opus_encoder_ctl(_encoder, OPUS_SET_LSB_DEPTH(16));
#endif
opus_encoder_ctl(_encoder, OPUS_GET_LOOKAHEAD(&lookahead));
if (ogg_stream_init(&os, serialno) == -1) {
NSLog(@"Error: stream init failed");
return false;
}
max_frame_bytes = (1275 * 3 + 7) * header.nb_streams;
_packet = malloc(max_frame_bytes);
return true;
}
- (bool)beginAppendWithDataItem:(TGDataItem *)dataItem
{
if (dataItem.data.length == 0) {
return [self beginWithDataItem:dataItem];
}
_dataItem = dataItem;
if (![self parseExistingOpusFile:_dataItem.data]) {
return false;
}
return [self initializeEncoderForAppend];
}
- (bool)writeFrame:(uint8_t *)framePcmBytes frameByteCount:(NSUInteger)frameByteCount
{
// Main encoding loop (one frame per iteration)
nb_samples = -1;
int cur_frame_size = frame_size;
_packetId++;
if (nb_samples < 0)
{
nb_samples = (opus_int32)(frameByteCount / 2);
total_samples += nb_samples;
if (nb_samples < frame_size)
op.e_o_s = 1;
else
op.e_o_s = 0;
}
op.e_o_s |= eos;
int nbBytes = 0;
if (nb_samples != 0)
{
uint8_t *paddedFrameBytes = framePcmBytes;
bool freePaddedFrameBytes = false;
if (nb_samples < cur_frame_size)
{
paddedFrameBytes = malloc(cur_frame_size * 2);
freePaddedFrameBytes = true;
memcpy(paddedFrameBytes, framePcmBytes, frameByteCount);
memset(paddedFrameBytes + nb_samples * 2, 0, cur_frame_size * 2 - nb_samples * 2);
}
// Encode current frame
nbBytes = opus_encode(_encoder, (opus_int16 *)paddedFrameBytes, cur_frame_size, _packet, max_frame_bytes / 10);
if (freePaddedFrameBytes)
{
free(paddedFrameBytes);
paddedFrameBytes = NULL;
}
if (nbBytes < 0)
{
NSLog(@"Encoding failed: %s. Aborting.", opus_strerror(nbBytes));
return false;
}
nb_encoded += cur_frame_size;
enc_granulepos += cur_frame_size * 48000 / coding_rate;
total_bytes += nbBytes;
size_segments = (nbBytes + 255) / 255;
peak_bytes = MAX(nbBytes, peak_bytes);
min_bytes = MIN(nbBytes, min_bytes);
}
// Flush early if adding this packet would make us end up with a continued page which we wouldn't have otherwise
while ((((size_segments<=255)&&(last_segments+size_segments>255)) ||
(enc_granulepos-last_granulepos>max_ogg_delay)) &&
ogg_stream_flush_fill(&os, &og, 255 * 255))
{
if (ogg_page_packets(&og) != 0)
last_granulepos = ogg_page_granulepos(&og);
last_segments -= og.header[26];
int writtenPageBytes = writeOggPage(&og, _dataItem);
if (writtenPageBytes != og.header_len + og.body_len)
{
NSLog(@"Error: failed writing data to output stream");
return false;
}
bytes_written += writtenPageBytes;
pages_out++;
}
if (framePcmBytes != NULL) {
op.packet = (unsigned char *)_packet;
op.bytes = nbBytes;
op.b_o_s = 0;
op.granulepos = enc_granulepos;
if (op.e_o_s)
{
/* We compute the final GP as ceil(len*48k/input_rate). When a resampling
decoder does the matching floor(len*input/48k) conversion the length will
be exactly the same as the input.
*/
op.granulepos = ((total_samples * 48000 + rate - 1) / rate) + header.preskip;
}
op.packetno = 2 + _packetId;
ogg_stream_packetin(&os, &op);
last_segments += size_segments;
}
// If the stream is over or we're sure that the delayed flush will fire, go ahead and flush now to avoid adding delay
while ((op.e_o_s || (enc_granulepos + (frame_size * 48000 / coding_rate) - last_granulepos > max_ogg_delay) ||
(last_segments >= 255)) ? ogg_stream_flush_fill(&os, &og, 255 * 255) : ogg_stream_pageout_fill(&os, &og, 255 * 255))
{
if (ogg_page_packets(&og) != 0)
last_granulepos = ogg_page_granulepos(&og);
last_segments -= og.header[26];
int writtenPageBytes = writeOggPage(&og, _dataItem);
if (writtenPageBytes != og.header_len + og.body_len)
{
NSLog(@"Error: failed writing data to output stream");
return false;
}
bytes_written += writtenPageBytes;
pages_out++;
}
return true;
}
- (NSUInteger)encodedBytes
{
return (NSUInteger)bytes_written;
}
- (NSTimeInterval)encodedDuration
{
return total_samples / (NSTimeInterval)coding_rate;
}
- (NSDictionary *)pause
{
[self flushPages];
return [self saveState];
}
- (bool)resumeWithDataItem:(TGDataItem *)dataItem encoderState:(NSDictionary *)state
{
if (![self restoreState:state withDataItem:dataItem])
return false;
_packetId++;
return true;
}
- (bool)flushPages
{
while (ogg_stream_flush_fill(&os, &og, 255 * 255))
{
if (ogg_page_packets(&og) != 0)
last_granulepos = ogg_page_granulepos(&og);
last_segments -= og.header[26];
int writtenPageBytes = writeOggPage(&og, _dataItem);
if (writtenPageBytes != og.header_len + og.body_len)
{
NSLog(@"Error: failed writing data to output stream");
return false;
}
bytes_written += writtenPageBytes;
pages_out++;
}
return true;
}
- (NSDictionary *)saveState
{
NSMutableDictionary *state = [NSMutableDictionary dictionary];
[state setObject:@(_packetId) forKey:@"packetId"];
[state setObject:@(enc_granulepos) forKey:@"enc_granulepos"];
[state setObject:@(last_granulepos) forKey:@"last_granulepos"];
[state setObject:@(last_segments) forKey:@"last_segments"];
[state setObject:@(nb_encoded) forKey:@"nb_encoded"];
[state setObject:@(bytes_written) forKey:@"bytes_written"];
[state setObject:@(pages_out) forKey:@"pages_out"];
[state setObject:@(total_bytes) forKey:@"total_bytes"];
[state setObject:@(total_samples) forKey:@"total_samples"];
[state setObject:@(serialno) forKey:@"serialno"];
[state setObject:@(rate) forKey:@"rate"];
[state setObject:@(coding_rate) forKey:@"coding_rate"];
[state setObject:@(frame_size) forKey:@"frame_size"];
[state setObject:@(bitrate) forKey:@"bitrate"];
[state setObject:@(with_cvbr) forKey:@"with_cvbr"];
[state setObject:@(lookahead) forKey:@"lookahead"];
NSDictionary *headerDict = @{
@"channels": @(header.channels),
@"channel_mapping": @(header.channel_mapping),
@"input_sample_rate": @(header.input_sample_rate),
@"gain": @(header.gain),
@"nb_streams": @(header.nb_streams),
@"preskip": @(header.preskip)
};
[state setObject:headerDict forKey:@"header"];
return state;
}
- (bool)restoreState:(NSDictionary *)state withDataItem:(TGDataItem *)dataItem
{
if (state == nil || dataItem == nil)
return false;
[self cleanup];
_dataItem = dataItem;
_packetId = [state[@"packetId"] intValue];
enc_granulepos = [state[@"enc_granulepos"] longLongValue];
last_granulepos = [state[@"last_granulepos"] longLongValue];
last_segments = [state[@"last_segments"] intValue];
nb_encoded = [state[@"nb_encoded"] longLongValue];
bytes_written = [state[@"bytes_written"] longLongValue];
pages_out = [state[@"pages_out"] longLongValue];
total_bytes = [state[@"total_bytes"] longLongValue];
total_samples = [state[@"total_samples"] longLongValue];
serialno = [state[@"serialno"] intValue];
rate = [state[@"rate"] intValue];
coding_rate = [state[@"coding_rate"] intValue];
frame_size = [state[@"frame_size"] intValue];
bitrate = [state[@"bitrate"] intValue];
with_cvbr = [state[@"with_cvbr"] intValue];
lookahead = [state[@"lookahead"] intValue];
NSDictionary *headerDict = state[@"header"];
header.channels = [headerDict[@"channels"] intValue];
header.channel_mapping = [headerDict[@"channel_mapping"] intValue];
header.input_sample_rate = [headerDict[@"input_sample_rate"] intValue];
header.gain = [headerDict[@"gain"] intValue];
header.nb_streams = [headerDict[@"nb_streams"] intValue];
header.preskip = [headerDict[@"preskip"] intValue];
int result = OPUS_OK;
_encoder = opus_encoder_create(coding_rate, header.channels, OPUS_APPLICATION_AUDIO, &result);
if (result != OPUS_OK)
{
NSLog(@"Error cannot create encoder: %s", opus_strerror(result));
return false;
}
opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(bitrate));
#ifdef OPUS_SET_LSB_DEPTH
opus_encoder_ctl(_encoder, OPUS_SET_LSB_DEPTH(16));
#endif
if (ogg_stream_init(&os, serialno) == -1)
{
NSLog(@"Error: stream init failed");
return false;
}
min_bytes = max_frame_bytes = (1275 * 3 + 7) * header.nb_streams;
_packet = malloc(max_frame_bytes);
return true;
}
@end
/*
Comments will be stored in the Vorbis style.
It is describled in the "Structure" section of
http://www.xiph.org/ogg/vorbis/doc/v-comment.html
However, Opus and other non-vorbis formats omit the "framing_bit".
The comment header is decoded as follows:
1) [vendor_length] = read an unsigned integer of 32 bits
2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets
3) [user_comment_list_length] = read an unsigned integer of 32 bits
4) iterate [user_comment_list_length] times {
5) [length] = read an unsigned integer of 32 bits
6) this iteration's user comment = read a UTF-8 vector as [length] octets
}
7) done.
*/
#define readint(buf, base) (((buf[base+3]<<24)&0xff000000)| \
((buf[base+2]<<16)&0xff0000)| \
((buf[base+1]<<8)&0xff00)| \
(buf[base]&0xff))
#define writeint(buf, base, val) do{ buf[base+3]=((val)>>24)&0xff; \
buf[base+2]=((val)>>16)&0xff; \
buf[base+1]=((val)>>8)&0xff; \
buf[base]=(val)&0xff; \
}while(0)
static bool comment_init(char **comments, int *length, const char *vendor_string)
{
// The 'vendor' field should be the actual encoding library used
int vendor_length = (int)strlen(vendor_string);
int user_comment_list_length = 0;
int len = 8 + 4 + vendor_length + 4;
char *p = (char *)malloc(len);
memcpy(p, "OpusTags", 8);
writeint(p, 8, vendor_length);
memcpy(p + 12, vendor_string, vendor_length);
writeint(p, 12 + vendor_length, user_comment_list_length);
*length = len;
*comments = p;
return true;
}
__unused bool comment_add(char **comments, int* length, char *tag, char *val)
{
char *p = *comments;
int vendor_length = readint(p, 8);
int user_comment_list_length = readint(p, 8 + 4 + vendor_length);
int tag_len = (tag ? (int)strlen(tag) + 1 : 0);
int val_len = (int)strlen(val);
int len = (*length) + 4 + tag_len + val_len;
p = (char *)realloc(p, len);
writeint(p, *length, tag_len+val_len); /* length of comment */
if (tag)
{
memcpy(p + *length + 4, tag, tag_len); /* comment tag */
(p+*length+4)[tag_len-1] = '='; /* separator */
}
memcpy(p + *length + 4 + tag_len, val, val_len); /* comment */
writeint(p, 8 + 4 + vendor_length, user_comment_list_length + 1);
*comments = p;
*length = len;
return true;
}
static bool comment_pad(char **comments, int* length, int amount)
{
if (amount > 0)
{
char *p = *comments;
// Make sure there is at least amount worth of padding free, and round up to the maximum that fits in the current ogg segments
int newlen = (*length + amount + 255) / 255 * 255 - 1;
p = realloc(p, newlen);
for (int i = *length; i < newlen; i++)
{
p[i] = 0;
}
*comments = p;
*length = newlen;
}
return true;
}
#undef readint
#undef writeint
@@ -0,0 +1,499 @@
/* Copyright (C)2007-2013 Xiph.Org Foundation
File: picture.c
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "picture.h"
static const char BASE64_TABLE[64]={
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};
/*Utility function for base64 encoding METADATA_BLOCK_PICTURE tags.
Stores BASE64_LENGTH(len)+1 bytes in dst (including a terminating NUL).*/
void base64_encode(char *dst, const char *src, int len){
unsigned s0;
unsigned s1;
unsigned s2;
int ngroups;
int i;
ngroups=len/3;
for(i=0;i<ngroups;i++){
s0=(unsigned char)src[3*i+0];
s1=(unsigned char)src[3*i+1];
s2=(unsigned char)src[3*i+2];
dst[4*i+0]=BASE64_TABLE[s0>>2];
dst[4*i+1]=BASE64_TABLE[(s0&3)<<4|s1>>4];
dst[4*i+2]=BASE64_TABLE[(s1&15)<<2|s2>>6];
dst[4*i+3]=BASE64_TABLE[s2&63];
}
len-=3*i;
if(len==1){
s0=(unsigned char)src[3*i+0];
dst[4*i+0]=BASE64_TABLE[s0>>2];
dst[4*i+1]=BASE64_TABLE[(s0&3)<<4];
dst[4*i+2]='=';
dst[4*i+3]='=';
i++;
}
else if(len==2){
s0=(unsigned char)src[3*i+0];
s1=(unsigned char)src[3*i+1];
dst[4*i+0]=BASE64_TABLE[s0>>2];
dst[4*i+1]=BASE64_TABLE[(s0&3)<<4|s1>>4];
dst[4*i+2]=BASE64_TABLE[(s1&15)<<2];
dst[4*i+3]='=';
i++;
}
dst[4*i]='\0';
}
/*A version of strncasecmp() that is guaranteed to only ignore the case of
ASCII characters.*/
int oi_strncasecmp(const char *a, const char *b, int n){
int i;
for(i=0;i<n;i++){
int aval;
int bval;
int diff;
aval=a[i];
bval=b[i];
if(aval>='a'&&aval<='z') {
aval-='a'-'A';
}
if(bval>='a'&&bval<='z'){
bval-='a'-'A';
}
diff=aval-bval;
if(diff){
return diff;
}
}
return 0;
}
int is_jpeg(const unsigned char *buf, size_t length){
return length>=11&&memcmp(buf,"\xFF\xD8\xFF\xE0",4)==0
&&(buf[4]<<8|buf[5])>=16&&memcmp(buf+6,"JFIF",5)==0;
}
int is_png(const unsigned char *buf, size_t length){
return length>=8&&memcmp(buf,"\x89PNG\x0D\x0A\x1A\x0A",8)==0;
}
int is_gif(const unsigned char *buf, size_t length){
return length>=6
&&(memcmp(buf,"GIF87a",6)==0||memcmp(buf,"GIF89a",6)==0);
}
#define READ_U32_BE(buf) \
(((buf)[0]<<24)|((buf)[1]<<16)|((buf)[2]<<8)|((buf)[3]&0xff))
/*Tries to extract the width, height, bits per pixel, and palette size of a
PNG.
On failure, simply leaves its outputs unmodified.*/
void extract_png_params(const unsigned char *data, size_t data_length,
ogg_uint32_t *width, ogg_uint32_t *height,
ogg_uint32_t *depth, ogg_uint32_t *colors,
int *has_palette){
if(is_png(data,data_length)){
size_t offs;
offs=8;
while(data_length-offs>=12){
ogg_uint32_t chunk_len;
chunk_len=READ_U32_BE(data+offs);
if(chunk_len>data_length-(offs+12))break;
else if(chunk_len==13&&memcmp(data+offs+4,"IHDR",4)==0){
int color_type;
*width=READ_U32_BE(data+offs+8);
*height=READ_U32_BE(data+offs+12);
color_type=data[offs+17];
if(color_type==3){
*depth=24;
*has_palette=1;
}
else{
int sample_depth;
sample_depth=data[offs+16];
if(color_type==0)*depth=sample_depth;
else if(color_type==2)*depth=sample_depth*3;
else if(color_type==4)*depth=sample_depth*2;
else if(color_type==6)*depth=sample_depth*4;
*colors=0;
*has_palette=0;
break;
}
}
else if(*has_palette>0&&memcmp(data+offs+4,"PLTE",4)==0){
*colors=chunk_len/3;
break;
}
offs+=12+chunk_len;
}
}
}
/*Tries to extract the width, height, bits per pixel, and palette size of a
GIF.
On failure, simply leaves its outputs unmodified.*/
void extract_gif_params(const unsigned char *data, size_t data_length,
ogg_uint32_t *width, ogg_uint32_t *height,
ogg_uint32_t *depth, ogg_uint32_t *colors,
int *has_palette){
if(is_gif(data,data_length)&&data_length>=14){
*width=data[6]|data[7]<<8;
*height=data[8]|data[9]<<8;
/*libFLAC hard-codes the depth to 24.*/
*depth=24;
*colors=1<<((data[10]&7)+1);
*has_palette=1;
}
}
/*Tries to extract the width, height, bits per pixel, and palette size of a
JPEG.
On failure, simply leaves its outputs unmodified.*/
void extract_jpeg_params(const unsigned char *data, size_t data_length,
ogg_uint32_t *width, ogg_uint32_t *height,
ogg_uint32_t *depth, ogg_uint32_t *colors,
int *has_palette){
if(is_jpeg(data,data_length)){
size_t offs;
offs=2;
for(;;){
size_t segment_len;
int marker;
while(offs<data_length&&data[offs]!=0xFF)offs++;
while(offs<data_length&&data[offs]==0xFF)offs++;
marker=data[offs];
offs++;
/*If we hit EOI* (end of image), or another SOI* (start of image),
or SOS (start of scan), then stop now.*/
if(offs>=data_length||(marker>=0xD8&&marker<=0xDA))break;
/*RST* (restart markers): skip (no segment length).*/
else if(marker>=0xD0&&marker<=0xD7)continue;
/*Read the length of the marker segment.*/
if(data_length-offs<2)break;
segment_len=data[offs]<<8|data[offs+1];
if(segment_len<2||data_length-offs<segment_len)break;
if(marker==0xC0||(marker>0xC0&&marker<0xD0&&(marker&3)!=0)){
/*Found a SOFn (start of frame) marker segment:*/
if(segment_len>=8){
*height=data[offs+3]<<8|data[offs+4];
*width=data[offs+5]<<8|data[offs+6];
*depth=data[offs+2]*data[offs+7];
*colors=0;
*has_palette=0;
}
break;
}
/*Other markers: skip the whole marker segment.*/
offs+=segment_len;
}
}
}
#define IMAX(a,b) ((a) > (b) ? (a) : (b))
/*Parse a picture SPECIFICATION as given on the command-line.
spec: The specification.
error_message: Returns an error message on error.
seen_file_icons: Bit flags used to track if any pictures of type 1 or type 2
have already been added, to ensure only one is allowed.
Return: A Base64-encoded string suitable for use in a METADATA_BLOCK_PICTURE
tag.*/
char *parse_picture_specification(const char *spec,
const char **error_message,
int *seen_file_icons){
FILE *picture_file;
unsigned long picture_type;
unsigned long width;
unsigned long height;
unsigned long depth;
unsigned long colors;
const char *mime_type;
const char *mime_type_end;
const char *description;
const char *description_end;
const char *filename;
unsigned char *buf;
char *out;
size_t cbuf;
size_t nbuf;
size_t data_offset;
size_t data_length;
size_t b64_length;
int is_url;
/*If a filename has a '|' in it, there's no way we can distinguish it from a
full specification just from the spec string.
Instead, try to open the file.
If it exists, the user probably meant the file.*/
picture_type=3;
width=height=depth=colors=0;
mime_type=mime_type_end=description=description_end=filename=spec;
is_url=0;
picture_file=fopen(filename,"rb");
if(picture_file==NULL&&strchr(spec,'|')){
const char *p;
char *q;
/*We don't have a plain file, and there is a pipe character: assume it's
the full form of the specification.*/
picture_type=strtoul(spec,&q,10);
if(*q!='|'||picture_type>20){
*error_message="invalid picture type";
return NULL;
}
if(picture_type>=1&&picture_type<=2&&(*seen_file_icons&picture_type)){
*error_message=picture_type==1?
"only one picture of type 1 (32x32 icon) allowed":
"only one picture of type 2 (icon) allowed";
return NULL;
}
/*An empty field implies a default of 'Cover (front)'.*/
if(spec==q)picture_type=3;
mime_type=q+1;
mime_type_end=mime_type+strcspn(mime_type,"|");
if(*mime_type_end!='|'){
*error_message="invalid picture specification: not enough fields";
return NULL;
}
/*The mime type must be composed of ASCII printable characters 0x20-0x7E.*/
for(p=mime_type;p<mime_type_end;p++)if(*p<0x20||*p>0x7E){
*error_message="invalid characters in mime type";
return NULL;
}
is_url=mime_type_end-mime_type==3
&&strncmp("-->",mime_type,mime_type_end-mime_type)==0;
description=mime_type_end+1;
description_end=description+strcspn(description,"|");
if(*description_end!='|'){
*error_message="invalid picture specification: not enough fields";
return NULL;
}
p=description_end+1;
if(*p!='|'){
width=strtoul(p,&q,10);
if(*q!='x'){
*error_message=
"invalid picture specification: can't parse resolution/color field";
return NULL;
}
p=q+1;
height=strtoul(p,&q,10);
if(*q!='x'){
*error_message=
"invalid picture specification: can't parse resolution/color field";
return NULL;
}
p=q+1;
depth=strtoul(p,&q,10);
if(*q=='/'){
p=q+1;
colors=strtoul(p,&q,10);
}
if(*q!='|'){
*error_message=
"invalid picture specification: can't parse resolution/color field";
return NULL;
}
p=q;
}
filename=p+1;
if(!is_url)picture_file=fopen(filename,"rb");
}
/*Buffer size: 8 static 4-byte fields plus 2 dynamic fields, plus the
file/URL data.
We reserve at least 10 bytes for the mime type, in case we still need to
extract it from the file.*/
data_offset=32+(description_end-description)+IMAX(mime_type_end-mime_type,10);
buf=NULL;
if(is_url){
/*Easy case: just stick the URL at the end.
We don't do anything to verify it's a valid URL.*/
data_length=strlen(filename);
cbuf=nbuf=data_offset+data_length;
buf=(unsigned char *)malloc(cbuf);
memcpy(buf+data_offset,filename,data_length);
}
else{
ogg_uint32_t file_width;
ogg_uint32_t file_height;
ogg_uint32_t file_depth;
ogg_uint32_t file_colors;
int has_palette;
/*Complicated case: we have a real file.
Read it in, attempt to parse the mime type and image dimensions if
necessary, and validate what the user passed in.*/
if(picture_file==NULL){
*error_message="error opening picture file";
return NULL;
}
nbuf=data_offset;
/*Add a reasonable starting image file size.*/
cbuf=data_offset+65536;
for(;;){
unsigned char *new_buf;
size_t nread;
new_buf=realloc(buf,cbuf);
if(new_buf==NULL){
fclose(picture_file);
free(buf);
*error_message="insufficient memory";
return NULL;
}
buf=new_buf;
nread=fread(buf+nbuf,1,cbuf-nbuf,picture_file);
nbuf+=nread;
if(nbuf<cbuf){
int error;
error=ferror(picture_file);
fclose(picture_file);
if(error){
free(buf);
*error_message="error reading picture file";
return NULL;
}
break;
}
if(cbuf==0xFFFFFFFF){
fclose(picture_file);
free(buf);
*error_message="file too large";
return NULL;
}
else if(cbuf>0x7FFFFFFFU)cbuf=0xFFFFFFFFU;
else cbuf=cbuf<<1|1;
}
data_length=nbuf-data_offset;
/*If there was no mimetype, try to extract it from the file data.*/
if(mime_type_end==mime_type){
if(is_jpeg(buf+data_offset,data_length)){
mime_type="image/jpeg";
mime_type_end=mime_type+10;
}
else if(is_png(buf+data_offset,data_length)){
mime_type="image/png";
mime_type_end=mime_type+9;
}
else if(is_gif(buf+data_offset,data_length)){
mime_type="image/gif";
mime_type_end=mime_type+9;
}
else{
free(buf);
*error_message="unable to guess MIME type from file, "
"must set it explicitly";
return NULL;
}
}
/*Try to extract the image dimensions/color information from the file.*/
file_width=file_height=file_depth=file_colors=0;
has_palette=-1;
if(mime_type_end-mime_type==9
&&oi_strncasecmp("image/png",mime_type,mime_type_end-mime_type)==0){
extract_png_params(buf+data_offset,data_length,
&file_width,&file_height,&file_depth,&file_colors,&has_palette);
}
else if(mime_type_end-mime_type==9
&&oi_strncasecmp("image/gif",mime_type,mime_type_end-mime_type)==0){
extract_gif_params(buf+data_offset,data_length,
&file_width,&file_height,&file_depth,&file_colors,&has_palette);
}
else if(mime_type_end-mime_type==10
&&oi_strncasecmp("image/jpeg",mime_type,mime_type_end-mime_type)==0){
extract_jpeg_params(buf+data_offset,data_length,
&file_width,&file_height,&file_depth,&file_colors,&has_palette);
}
if(!width)width=file_width;
if(!height)height=file_height;
if(!depth)depth=file_depth;
if(!colors)colors=file_colors;
if((file_width&&width!=file_width)
||(file_height&&height!=file_height)
||(file_depth&&depth!=file_depth)
/*We use has_palette to ensure we also reject non-0 user color counts for
images we've positively identified as non-paletted.*/
||(has_palette>=0&&colors!=file_colors)){
free(buf);
*error_message="invalid picture specification: "
"resolution/color field does not match file";
return NULL;
}
}
/*These fields MUST be set correctly OR all set to zero.
So if any of them (except colors, for which 0 is a valid value) are still
zero, clear the rest to zero.*/
if(width==0||height==0||depth==0)width=height=depth=colors=0;
if(picture_type==1&&(width!=32||height!=32
||mime_type_end-mime_type!=9
||oi_strncasecmp("image/png",mime_type,mime_type_end-mime_type)!=0)){
free(buf);
*error_message="pictures of type 1 MUST be 32x32 PNGs";
return NULL;
}
/*Build the METADATA_BLOCK_PICTURE buffer.
We do this backwards from data_offset, because we didn't necessarily know
how big the mime type string was before we read the data in.*/
data_offset-=4;
WRITE_U32_BE(buf+data_offset,(unsigned long)data_length);
data_offset-=4;
WRITE_U32_BE(buf+data_offset,colors);
data_offset-=4;
WRITE_U32_BE(buf+data_offset,depth);
data_offset-=4;
WRITE_U32_BE(buf+data_offset,height);
data_offset-=4;
WRITE_U32_BE(buf+data_offset,width);
data_offset-=description_end-description;
memcpy(buf+data_offset,description,description_end-description);
data_offset-=4;
WRITE_U32_BE(buf+data_offset,(unsigned long)(description_end-description));
data_offset-=mime_type_end-mime_type;
memcpy(buf+data_offset,mime_type,mime_type_end-mime_type);
data_offset-=4;
WRITE_U32_BE(buf+data_offset,(unsigned long)(mime_type_end-mime_type));
data_offset-=4;
WRITE_U32_BE(buf+data_offset,picture_type);
data_length=nbuf-data_offset;
b64_length=BASE64_LENGTH(data_length);
out=(char *)malloc(b64_length+1);
if(out!=NULL){
base64_encode(out,(char *)buf+data_offset,data_length);
if(picture_type>=1&&picture_type<=2)*seen_file_icons|=picture_type;
}
free(buf);
return out;
}
@@ -0,0 +1,50 @@
#ifndef __PICTURE_H
#define __PICTURE_H
#include <ogg/ogg.h>
typedef enum{
PIC_FORMAT_JPEG,
PIC_FORMAT_PNG,
PIC_FORMAT_GIF
}picture_format;
#define BASE64_LENGTH(len) (((len)+2)/3*4)
/*Utility function for base64 encoding METADATA_BLOCK_PICTURE tags.
Stores BASE64_LENGTH(len)+1 bytes in dst (including a terminating NUL).*/
void base64_encode(char *dst, const char *src, int len);
int oi_strncasecmp(const char *a, const char *b, int n);
int is_jpeg(const unsigned char *buf, size_t length);
int is_png(const unsigned char *buf, size_t length);
int is_gif(const unsigned char *buf, size_t length);
void extract_png_params(const unsigned char *data, size_t data_length,
ogg_uint32_t *width, ogg_uint32_t *height,
ogg_uint32_t *depth, ogg_uint32_t *colors,
int *has_palette);
void extract_gif_params(const unsigned char *data, size_t data_length,
ogg_uint32_t *width, ogg_uint32_t *height,
ogg_uint32_t *depth, ogg_uint32_t *colors,
int *has_palette);
void extract_jpeg_params(const unsigned char *data, size_t data_length,
ogg_uint32_t *width, ogg_uint32_t *height,
ogg_uint32_t *depth, ogg_uint32_t *colors,
int *has_palette);
char *parse_picture_specification(const char *spec,
const char **error_message,
int *seen_file_icons);
#define WRITE_U32_BE(buf, val) \
do{ \
(buf)[0]=(unsigned char)((val)>>24); \
(buf)[1]=(unsigned char)((val)>>16); \
(buf)[2]=(unsigned char)((val)>>8); \
(buf)[3]=(unsigned char)(val); \
} \
while(0);
#endif /* __PICTURE_H */
@@ -0,0 +1,125 @@
/* Copyright (C) 2002 Jean-Marc Valin
File: wav_io.c
Routines to handle wav (RIFF) headers
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#include "wav_io.h"
#include "opus_header.h"
/* Adjust the stream->channel mapping to ensure the proper output order for
WAV files. */
void adjust_wav_mapping(int mapping_family, int channels, unsigned char *stream_map)
{
unsigned char new_stream_map[8];
int i;
/* If we aren't using one of the defined semantic channel maps, or we have
more channels than we know what to do with, use a default 1-1 mapping. */
if(mapping_family != 1 || channels > 8)
return;
for(i = 0; i < channels; i++)
{
new_stream_map[wav_permute_matrix[channels-1][i]] = stream_map[i];
}
memcpy(stream_map, new_stream_map, channels*sizeof(*stream_map));
}
static size_t fwrite_le32(opus_int32 i32, FILE *file)
{
unsigned char buf[4];
buf[0]=(unsigned char)(i32&0xFF);
buf[1]=(unsigned char)(i32>>8&0xFF);
buf[2]=(unsigned char)(i32>>16&0xFF);
buf[3]=(unsigned char)(i32>>24&0xFF);
return fwrite(buf,4,1,file);
}
static size_t fwrite_le16(int i16, FILE *file)
{
unsigned char buf[2];
buf[0]=(unsigned char)(i16&0xFF);
buf[1]=(unsigned char)(i16>>8&0xFF);
return fwrite(buf,2,1,file);
}
int write_wav_header(FILE *file, int rate, int mapping_family, int channels)
{
int ret;
int extensible;
/* Multichannel files require a WAVEFORMATEXTENSIBLE header to declare the
proper channel meanings. */
extensible = mapping_family == 1 && 3 <= channels && channels <= 8;
ret = fprintf (file, "RIFF") >= 0;
ret &= fwrite_le32 (0x7fffffff, file);
ret &= fprintf (file, "WAVEfmt ") >= 0;
ret &= fwrite_le32 (extensible ? 40 : 16, file);
ret &= fwrite_le16 (extensible ? 0xfffe : 1, file);
ret &= fwrite_le16 (channels, file);
ret &= fwrite_le32 (rate, file);
ret &= fwrite_le32 (2*channels*rate, file);
ret &= fwrite_le16 (2*channels, file);
ret &= fwrite_le16 (16, file);
if(extensible)
{
static const unsigned char ksdataformat_subtype_pcm[16]=
{
0x01, 0x00, 0x00, 0x00,
0x00, 0x00,
0x10, 0x00,
0x80, 0x00,
0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
};
static const int wav_channel_masks[8] =
{
1, /* 1.0 mono */
1|2, /* 2.0 stereo */
1|2|4, /* 3.0 channel ('wide') stereo */
1|2|16|32, /* 4.0 discrete quadrophonic */
1|2|4|16|32, /* 5.0 */
1|2|4|8|16|32, /* 5.1 */
1|2|4|8|256|512|1024, /* 6.1 */
1|2|4|8|16|32|512|1024, /* 7.1 */
};
ret &= fwrite_le16 (22, file);
ret &= fwrite_le16 (16, file);
ret &= fwrite_le32 (wav_channel_masks[channels-1], file);
ret &= fwrite (ksdataformat_subtype_pcm, 16, 1, file);
}
ret &= fprintf (file, "data") >= 0;
ret &= fwrite_le32 (0x7fffffff, file);
return !ret ? -1 : extensible ? 40 : 16;
}
@@ -0,0 +1,62 @@
/* Copyright (C) 2002 Jean-Marc Valin
File: wav_io.h
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WAV_IO_H
#define WAV_IO_H
#include <stdio.h>
#include <opus/opus_types.h>
#if !defined(__LITTLE_ENDIAN__) && ( defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__) )
#define le_short(s) ((short) ((unsigned short) (s) << 8) | ((unsigned short) (s) >> 8))
#define be_short(s) ((short) (s))
#else
#define le_short(s) ((short) (s))
#define be_short(s) ((short) ((unsigned short) (s) << 8) | ((unsigned short) (s) >> 8))
#endif
/** Convert little endian */
static inline opus_int32 le_int(opus_int32 i)
{
#if !defined(__LITTLE_ENDIAN__) && ( defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__) )
opus_uint32 ui, ret;
ui = i;
ret = ui>>24;
ret |= (ui>>8)&0x0000ff00;
ret |= (ui<<8)&0x00ff0000;
ret |= (ui<<24);
return ret;
#else
return i;
#endif
}
void adjust_wav_mapping(int mapping_family, int channels, unsigned char *stream_map);
int write_wav_header(FILE *file, int rate, int mapping_family, int channels);
#endif
@@ -0,0 +1,683 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE libopusfile SOURCE CODE IS (C) COPYRIGHT 2012 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
* *
********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "internal.h"
#include <limits.h>
#include <string.h>
static unsigned op_parse_uint16le(const unsigned char *_data){
return _data[0]|_data[1]<<8;
}
static int op_parse_int16le(const unsigned char *_data){
int ret;
ret=_data[0]|_data[1]<<8;
return (ret^0x8000)-0x8000;
}
static opus_uint32 op_parse_uint32le(const unsigned char *_data){
return _data[0]|_data[1]<<8|_data[2]<<16|_data[3]<<24;
}
static opus_uint32 op_parse_uint32be(const unsigned char *_data){
return _data[3]|_data[2]<<8|_data[1]<<16|_data[0]<<24;
}
int opus_head_parse(OpusHead *_head,const unsigned char *_data,size_t _len){
OpusHead head;
if(_len<8)return OP_ENOTFORMAT;
if(memcmp(_data,"OpusHead",8)!=0)return OP_ENOTFORMAT;
if(_len<9)return OP_EBADHEADER;
head.version=_data[8];
if(head.version>15)return OP_EVERSION;
if(_len<19)return OP_EBADHEADER;
head.channel_count=_data[9];
head.pre_skip=op_parse_uint16le(_data+10);
head.input_sample_rate=op_parse_uint32le(_data+12);
head.output_gain=op_parse_int16le(_data+16);
head.mapping_family=_data[18];
if(head.mapping_family==0){
if(head.channel_count<1||head.channel_count>2)return OP_EBADHEADER;
if(head.version<=1&&_len>19)return OP_EBADHEADER;
head.stream_count=1;
head.coupled_count=head.channel_count-1;
if(_head!=NULL){
_head->mapping[0]=0;
_head->mapping[1]=1;
}
}
else if(head.mapping_family==1){
size_t size;
int ci;
if(head.channel_count<1||head.channel_count>8)return OP_EBADHEADER;
size=21+head.channel_count;
if(_len<size||head.version<=1&&_len>size)return OP_EBADHEADER;
head.stream_count=_data[19];
if(head.stream_count<1)return OP_EBADHEADER;
head.coupled_count=_data[20];
if(head.coupled_count>head.stream_count)return OP_EBADHEADER;
for(ci=0;ci<head.channel_count;ci++){
if(_data[21+ci]>=head.stream_count+head.coupled_count
&&_data[21+ci]!=255){
return OP_EBADHEADER;
}
}
if(_head!=NULL)memcpy(_head->mapping,_data+21,head.channel_count);
}
/*General purpose players should not attempt to play back content with
channel mapping family 255.*/
else if(head.mapping_family==255)return OP_EIMPL;
/*No other channel mapping families are currently defined.*/
else return OP_EBADHEADER;
if(_head!=NULL)memcpy(_head,&head,head.mapping-(unsigned char *)&head);
return 0;
}
void opus_tags_init(OpusTags *_tags){
memset(_tags,0,sizeof(*_tags));
}
void opus_tags_clear(OpusTags *_tags){
int ci;
for(ci=_tags->comments;ci-->0;)_ogg_free(_tags->user_comments[ci]);
_ogg_free(_tags->user_comments);
_ogg_free(_tags->comment_lengths);
_ogg_free(_tags->vendor);
}
/*Ensure there's room for up to _ncomments comments.*/
static int op_tags_ensure_capacity(OpusTags *_tags,size_t _ncomments){
char **user_comments;
int *comment_lengths;
size_t size;
if(OP_UNLIKELY(_ncomments>=(size_t)INT_MAX))return OP_EFAULT;
size=sizeof(*_tags->comment_lengths)*(_ncomments+1);
if(size/sizeof(*_tags->comment_lengths)!=_ncomments+1)return OP_EFAULT;
comment_lengths=(int *)_ogg_realloc(_tags->comment_lengths,size);
if(OP_UNLIKELY(comment_lengths==NULL))return OP_EFAULT;
comment_lengths[_ncomments]=0;
_tags->comment_lengths=comment_lengths;
size=sizeof(*_tags->user_comments)*(_ncomments+1);
if(size/sizeof(*_tags->user_comments)!=_ncomments+1)return OP_EFAULT;
user_comments=(char **)_ogg_realloc(_tags->user_comments,size);
if(OP_UNLIKELY(user_comments==NULL))return OP_EFAULT;
user_comments[_ncomments]=NULL;
_tags->user_comments=user_comments;
return 0;
}
/*Duplicate a (possibly non-NUL terminated) string with a known length.*/
static char *op_strdup_with_len(const char *_s,size_t _len){
size_t size;
char *ret;
size=sizeof(*ret)*(_len+1);
if(OP_UNLIKELY(size<_len))return NULL;
ret=(char *)_ogg_malloc(size);
if(OP_LIKELY(ret!=NULL)){
ret=(char *)memcpy(ret,_s,sizeof(*ret)*_len);
ret[_len]='\0';
}
return ret;
}
/*The actual implementation of opus_tags_parse().
Unlike the public API, this function requires _tags to already be
initialized, modifies its contents before success is guaranteed, and assumes
the caller will clear it on error.*/
static int opus_tags_parse_impl(OpusTags *_tags,
const unsigned char *_data,size_t _len){
opus_uint32 count;
size_t len;
int ncomments;
int ci;
len=_len;
if(len<8)return OP_ENOTFORMAT;
if(memcmp(_data,"OpusTags",8)!=0)return OP_ENOTFORMAT;
if(len<16)return OP_EBADHEADER;
_data+=8;
len-=8;
count=op_parse_uint32le(_data);
_data+=4;
len-=4;
if(count>len)return OP_EBADHEADER;
if(_tags!=NULL){
_tags->vendor=op_strdup_with_len((char *)_data,count);
if(_tags->vendor==NULL)return OP_EFAULT;
}
_data+=count;
len-=count;
if(len<4)return OP_EBADHEADER;
count=op_parse_uint32le(_data);
_data+=4;
len-=4;
/*Check to make sure there's minimally sufficient data left in the packet.*/
if(count>len>>2)return OP_EBADHEADER;
/*Check for overflow (the API limits this to an int).*/
if(count>(opus_uint32)INT_MAX-1)return OP_EFAULT;
if(_tags!=NULL){
int ret;
ret=op_tags_ensure_capacity(_tags,count);
if(ret<0)return ret;
}
ncomments=(int)count;
for(ci=0;ci<ncomments;ci++){
/*Check to make sure there's minimally sufficient data left in the packet.*/
if((size_t)(ncomments-ci)>len>>2)return OP_EBADHEADER;
count=op_parse_uint32le(_data);
_data+=4;
len-=4;
if(count>len)return OP_EBADHEADER;
/*Check for overflow (the API limits this to an int).*/
if(count>(opus_uint32)INT_MAX)return OP_EFAULT;
if(_tags!=NULL){
_tags->user_comments[ci]=op_strdup_with_len((char *)_data,count);
if(_tags->user_comments[ci]==NULL)return OP_EFAULT;
_tags->comment_lengths[ci]=(int)count;
_tags->comments=ci+1;
}
_data+=count;
len-=count;
}
return 0;
}
int opus_tags_parse(OpusTags *_tags,const unsigned char *_data,size_t _len){
if(_tags!=NULL){
OpusTags tags;
int ret;
opus_tags_init(&tags);
ret=opus_tags_parse_impl(&tags,_data,_len);
if(ret<0)opus_tags_clear(&tags);
else *_tags=*&tags;
return ret;
}
else return opus_tags_parse_impl(NULL,_data,_len);
}
/*The actual implementation of opus_tags_copy().
Unlike the public API, this function requires _dst to already be
initialized, modifies its contents before success is guaranteed, and assumes
the caller will clear it on error.*/
static int opus_tags_copy_impl(OpusTags *_dst,const OpusTags *_src){
char *vendor;
int ncomments;
int ret;
int ci;
vendor=_src->vendor;
_dst->vendor=op_strdup_with_len(vendor,strlen(vendor));
if(OP_UNLIKELY(_dst->vendor==NULL))return OP_EFAULT;
ncomments=_src->comments;
ret=op_tags_ensure_capacity(_dst,ncomments);
if(OP_UNLIKELY(ret<0))return ret;
for(ci=0;ci<ncomments;ci++){
int len;
len=_src->comment_lengths[ci];
OP_ASSERT(len>=0);
_dst->user_comments[ci]=op_strdup_with_len(_src->user_comments[ci],len);
if(OP_UNLIKELY(_dst->user_comments[ci]==NULL))return OP_EFAULT;
_dst->comment_lengths[ci]=len;
_dst->comments=ci+1;
}
return 0;
}
int opus_tags_copy(OpusTags *_dst,const OpusTags *_src){
OpusTags dst;
int ret;
opus_tags_init(&dst);
ret=opus_tags_copy_impl(&dst,_src);
if(OP_UNLIKELY(ret<0))opus_tags_clear(&dst);
else *_dst=*&dst;
return 0;
}
int opus_tags_add(OpusTags *_tags,const char *_tag,const char *_value){
char *comment;
int tag_len;
int value_len;
int ncomments;
int ret;
ncomments=_tags->comments;
ret=op_tags_ensure_capacity(_tags,ncomments+1);
if(OP_UNLIKELY(ret<0))return ret;
tag_len=strlen(_tag);
value_len=strlen(_value);
/*+2 for '=' and '\0'.*/
_tags->comment_lengths[ncomments]=0;
_tags->user_comments[ncomments]=comment=
(char *)_ogg_malloc(sizeof(*comment)*(tag_len+value_len+2));
if(OP_UNLIKELY(comment==NULL))return OP_EFAULT;
_tags->comment_lengths[ncomments]=tag_len+value_len+1;
memcpy(comment,_tag,sizeof(*comment)*tag_len);
comment[tag_len]='=';
memcpy(comment+tag_len+1,_value,sizeof(*comment)*(value_len+1));
return 0;
}
int opus_tags_add_comment(OpusTags *_tags,const char *_comment){
int comment_len;
int ncomments;
int ret;
ncomments=_tags->comments;
ret=op_tags_ensure_capacity(_tags,ncomments+1);
if(OP_UNLIKELY(ret<0))return ret;
comment_len=(int)strlen(_comment);
_tags->comment_lengths[ncomments]=0;
_tags->user_comments[ncomments]=op_strdup_with_len(_comment,comment_len);
if(OP_UNLIKELY(_tags->user_comments[ncomments]==NULL))return OP_EFAULT;
_tags->comment_lengths[ncomments]=comment_len;
return 0;
}
int opus_tagcompare(const char *_tag_name,const char *_comment){
return opus_tagncompare(_tag_name,strlen(_tag_name),_comment);
}
int opus_tagncompare(const char *_tag_name,int _tag_len,const char *_comment){
int ret;
OP_ASSERT(_tag_len>=0);
ret=op_strncasecmp(_tag_name,_comment,_tag_len);
return ret?ret:'='-_comment[_tag_len];
}
const char *opus_tags_query(const OpusTags *_tags,const char *_tag,int _count){
char **user_comments;
int tag_len;
int found;
int ncomments;
int ci;
tag_len=strlen(_tag);
ncomments=_tags->comments;
user_comments=_tags->user_comments;
found=0;
for(ci=0;ci<ncomments;ci++){
if(!opus_tagncompare(_tag,tag_len,user_comments[ci])){
/*We return a pointer to the data, not a copy.*/
if(_count==found++)return user_comments[ci]+tag_len+1;
}
}
/*Didn't find anything.*/
return NULL;
}
int opus_tags_query_count(const OpusTags *_tags,const char *_tag){
char **user_comments;
int tag_len;
int found;
int ncomments;
int ci;
tag_len=strlen(_tag);
ncomments=_tags->comments;
user_comments=_tags->user_comments;
found=0;
for(ci=0;ci<ncomments;ci++){
if(!opus_tagncompare(_tag,tag_len,user_comments[ci]))found++;
}
return found;
}
int opus_tags_get_track_gain(const OpusTags *_tags,int *_gain_q8){
char **comments;
int ncomments;
int ci;
comments=_tags->user_comments;
ncomments=_tags->comments;
/*Look for the first valid R128_TRACK_GAIN tag and use that.*/
for(ci=0;ci<ncomments;ci++){
if(opus_tagncompare("R128_TRACK_GAIN",15,comments[ci])==0){
char *p;
opus_int32 gain_q8;
int negative;
p=comments[ci]+16;
negative=0;
if(*p=='-'){
negative=-1;
p++;
}
else if(*p=='+')p++;
gain_q8=0;
while(*p>='0'&&*p<='9'){
gain_q8=10*gain_q8+*p-'0';
if(gain_q8>32767-negative)break;
p++;
}
/*This didn't look like a signed 16-bit decimal integer.
Not a valid R128_TRACK_GAIN tag.*/
if(*p!='\0')continue;
*_gain_q8=(int)(gain_q8+negative^negative);
return 0;
}
}
return OP_FALSE;
}
static int op_is_jpeg(const unsigned char *_buf,size_t _buf_sz){
return _buf_sz>=11&&memcmp(_buf,"\xFF\xD8\xFF\xE0",4)==0
&&(_buf[4]<<8|_buf[5])>=16&&memcmp(_buf+6,"JFIF",5)==0;
}
/*Tries to extract the width, height, bits per pixel, and palette size of a
JPEG.
On failure, simply leaves its outputs unmodified.*/
static void op_extract_jpeg_params(const unsigned char *_buf,size_t _buf_sz,
opus_uint32 *_width,opus_uint32 *_height,
opus_uint32 *_depth,opus_uint32 *_colors,int *_has_palette){
if(op_is_jpeg(_buf,_buf_sz)){
size_t offs;
offs=2;
for(;;){
size_t segment_len;
int marker;
while(offs<_buf_sz&&_buf[offs]!=0xFF)offs++;
while(offs<_buf_sz&&_buf[offs]==0xFF)offs++;
marker=_buf[offs];
offs++;
/*If we hit EOI* (end of image), or another SOI* (start of image),
or SOS (start of scan), then stop now.*/
if(offs>=_buf_sz||(marker>=0xD8&&marker<=0xDA))break;
/*RST* (restart markers): skip (no segment length).*/
else if(marker>=0xD0&&marker<=0xD7)continue;
/*Read the length of the marker segment.*/
if(_buf_sz-offs<2)break;
segment_len=_buf[offs]<<8|_buf[offs+1];
if(segment_len<2||_buf_sz-offs<segment_len)break;
if(marker==0xC0||(marker>0xC0&&marker<0xD0&&(marker&3)!=0)){
/*Found a SOFn (start of frame) marker segment:*/
if(segment_len>=8){
*_height=_buf[offs+3]<<8|_buf[offs+4];
*_width=_buf[offs+5]<<8|_buf[offs+6];
*_depth=_buf[offs+2]*_buf[offs+7];
*_colors=0;
*_has_palette=0;
}
break;
}
/*Other markers: skip the whole marker segment.*/
offs+=segment_len;
}
}
}
static int op_is_png(const unsigned char *_buf,size_t _buf_sz){
return _buf_sz>=8&&memcmp(_buf,"\x89PNG\x0D\x0A\x1A\x0A",8)==0;
}
/*Tries to extract the width, height, bits per pixel, and palette size of a
PNG.
On failure, simply leaves its outputs unmodified.*/
static void op_extract_png_params(const unsigned char *_buf,size_t _buf_sz,
opus_uint32 *_width,opus_uint32 *_height,
opus_uint32 *_depth,opus_uint32 *_colors,int *_has_palette){
if(op_is_png(_buf,_buf_sz)){
size_t offs;
offs=8;
while(_buf_sz-offs>=12){
ogg_uint32_t chunk_len;
chunk_len=op_parse_uint32be(_buf+offs);
if(chunk_len>_buf_sz-(offs+12))break;
else if(chunk_len==13&&memcmp(_buf+offs+4,"IHDR",4)==0){
int color_type;
*_width=op_parse_uint32be(_buf+offs+8);
*_height=op_parse_uint32be(_buf+offs+12);
color_type=_buf[offs+17];
if(color_type==3){
*_depth=24;
*_has_palette=1;
}
else{
int sample_depth;
sample_depth=_buf[offs+16];
if(color_type==0)*_depth=sample_depth;
else if(color_type==2)*_depth=sample_depth*3;
else if(color_type==4)*_depth=sample_depth*2;
else if(color_type==6)*_depth=sample_depth*4;
*_colors=0;
*_has_palette=0;
break;
}
}
else if(*_has_palette>0&&memcmp(_buf+offs+4,"PLTE",4)==0){
*_colors=chunk_len/3;
break;
}
offs+=12+chunk_len;
}
}
}
static int op_is_gif(const unsigned char *_buf,size_t _buf_sz){
return _buf_sz>=6&&(memcmp(_buf,"GIF87a",6)==0||memcmp(_buf,"GIF89a",6)==0);
}
/*Tries to extract the width, height, bits per pixel, and palette size of a
GIF.
On failure, simply leaves its outputs unmodified.*/
static void op_extract_gif_params(const unsigned char *_buf,size_t _buf_sz,
opus_uint32 *_width,opus_uint32 *_height,
opus_uint32 *_depth,opus_uint32 *_colors,int *_has_palette){
if(op_is_gif(_buf,_buf_sz)&&_buf_sz>=14){
*_width=_buf[6]|_buf[7]<<8;
*_height=_buf[8]|_buf[9]<<8;
/*libFLAC hard-codes the depth to 24.*/
*_depth=24;
*_colors=1<<((_buf[10]&7)+1);
*_has_palette=1;
}
}
/*The actual implementation of opus_picture_tag_parse().
Unlike the public API, this function requires _pic to already be
initialized, modifies its contents before success is guaranteed, and assumes
the caller will clear it on error.*/
static int opus_picture_tag_parse_impl(OpusPictureTag *_pic,const char *_tag,
unsigned char *_buf,size_t _buf_sz,size_t _base64_sz){
opus_int32 picture_type;
opus_uint32 mime_type_length;
char *mime_type;
opus_uint32 description_length;
char *description;
opus_uint32 width;
opus_uint32 height;
opus_uint32 depth;
opus_uint32 colors;
opus_uint32 data_length;
opus_uint32 file_width;
opus_uint32 file_height;
opus_uint32 file_depth;
opus_uint32 file_colors;
int format;
int has_palette;
int colors_set;
size_t i;
/*Decode the BASE64 data.*/
for(i=0;i<_base64_sz;i++){
opus_uint32 value;
int j;
value=0;
for(j=0;j<4;j++){
unsigned c;
unsigned d;
c=(unsigned char)_tag[4*i+j];
if(c=='+')d=62;
else if(c=='/')d=63;
else if(c>='0'&&c<='9')d=52+c-'0';
else if(c>='a'&&c<='z')d=26+c-'a';
else if(c>='A'&&c<='Z')d=c-'A';
else if(c=='='&&3*i+j>_buf_sz)d=0;
else return OP_ENOTFORMAT;
value=value<<6|d;
}
_buf[3*i]=(unsigned char)(value>>16);
if(3*i+1<_buf_sz){
_buf[3*i+1]=(unsigned char)(value>>8);
if(3*i+2<_buf_sz)_buf[3*i+2]=(unsigned char)value;
}
}
i=0;
picture_type=op_parse_uint32be(_buf+i);
i+=4;
/*Extract the MIME type.*/
mime_type_length=op_parse_uint32be(_buf+i);
i+=4;
if(mime_type_length>_buf_sz-32)return OP_ENOTFORMAT;
mime_type=(char *)_ogg_malloc(sizeof(*_pic->mime_type)*(mime_type_length+1));
if(mime_type==NULL)return OP_EFAULT;
memcpy(mime_type,_buf+i,sizeof(*mime_type)*mime_type_length);
mime_type[mime_type_length]='\0';
_pic->mime_type=mime_type;
i+=mime_type_length;
/*Extract the description string.*/
description_length=op_parse_uint32be(_buf+i);
i+=4;
if(description_length>_buf_sz-mime_type_length-32)return OP_ENOTFORMAT;
description=
(char *)_ogg_malloc(sizeof(*_pic->mime_type)*(description_length+1));
if(description==NULL)return OP_EFAULT;
memcpy(description,_buf+i,sizeof(*description)*description_length);
description[description_length]='\0';
_pic->description=description;
i+=description_length;
/*Extract the remaining fields.*/
width=op_parse_uint32be(_buf+i);
i+=4;
height=op_parse_uint32be(_buf+i);
i+=4;
depth=op_parse_uint32be(_buf+i);
i+=4;
colors=op_parse_uint32be(_buf+i);
i+=4;
/*If one of these is set, they all must be, but colors==0 is a valid value.*/
colors_set=width!=0||height!=0||depth!=0||colors!=0;
if(width==0||height==0||depth==0&&colors_set)return OP_ENOTFORMAT;
data_length=op_parse_uint32be(_buf+i);
i+=4;
if(data_length>_buf_sz-i)return OP_ENOTFORMAT;
/*Trim extraneous data so we don't copy it below.*/
_buf_sz=i+data_length;
/*Attempt to determine the image format.*/
format=OP_PIC_FORMAT_UNKNOWN;
if(mime_type_length==3&&strcmp(mime_type,"-->")==0){
format=OP_PIC_FORMAT_URL;
/*Picture type 1 must be a 32x32 PNG.*/
if(picture_type==1&&(width!=0||height!=0)&&(width!=32||height!=32)){
return OP_ENOTFORMAT;
}
/*Append a terminating NUL for the convenience of our callers.*/
_buf[_buf_sz++]='\0';
}
else{
if(mime_type_length==10
&&op_strncasecmp(mime_type,"image/jpeg",mime_type_length)==0){
if(op_is_jpeg(_buf+i,data_length))format=OP_PIC_FORMAT_JPEG;
}
else if(mime_type_length==9
&&op_strncasecmp(mime_type,"image/png",mime_type_length)==0){
if(op_is_png(_buf+i,data_length))format=OP_PIC_FORMAT_PNG;
}
else if(mime_type_length==9
&&op_strncasecmp(mime_type,"image/gif",mime_type_length)==0){
if(op_is_gif(_buf+i,data_length))format=OP_PIC_FORMAT_GIF;
}
else if(mime_type_length==0||(mime_type_length==6
&&op_strncasecmp(mime_type,"image/",mime_type_length)==0)){
if(op_is_jpeg(_buf+i,data_length))format=OP_PIC_FORMAT_JPEG;
else if(op_is_png(_buf+i,data_length))format=OP_PIC_FORMAT_PNG;
else if(op_is_gif(_buf+i,data_length))format=OP_PIC_FORMAT_GIF;
}
file_width=file_height=file_depth=file_colors=0;
has_palette=-1;
switch(format){
case OP_PIC_FORMAT_JPEG:{
op_extract_jpeg_params(_buf+i,data_length,
&file_width,&file_height,&file_depth,&file_colors,&has_palette);
}break;
case OP_PIC_FORMAT_PNG:{
op_extract_png_params(_buf+i,data_length,
&file_width,&file_height,&file_depth,&file_colors,&has_palette);
}break;
case OP_PIC_FORMAT_GIF:{
op_extract_gif_params(_buf+i,data_length,
&file_width,&file_height,&file_depth,&file_colors,&has_palette);
}break;
}
if(has_palette>=0){
/*If we successfully extracted these parameters from the image, override
any declared values.*/
width=file_width;
height=file_height;
depth=file_depth;
colors=file_colors;
}
/*Picture type 1 must be a 32x32 PNG.*/
if(picture_type==1&&(format!=OP_PIC_FORMAT_PNG||width!=32||height!=32)){
return OP_ENOTFORMAT;
}
}
/*Adjust _buf_sz instead of using data_length to capture the terminating NUL
for URLs.*/
_buf_sz-=i;
memmove(_buf,_buf+i,sizeof(*_buf)*_buf_sz);
_buf=(unsigned char *)_ogg_realloc(_buf,_buf_sz);
if(_buf_sz>0&&_buf==NULL)return OP_EFAULT;
_pic->type=picture_type;
_pic->width=width;
_pic->height=height;
_pic->depth=depth;
_pic->colors=colors;
_pic->data_length=data_length;
_pic->data=_buf;
_pic->format=format;
return 0;
}
int opus_picture_tag_parse(OpusPictureTag *_pic,const char *_tag){
OpusPictureTag pic;
unsigned char *buf;
size_t base64_sz;
size_t buf_sz;
size_t tag_length;
int ret;
if(opus_tagncompare("METADATA_BLOCK_PICTURE",22,_tag)==0)_tag+=23;
/*Figure out how much BASE64-encoded data we have.*/
tag_length=strlen(_tag);
if(tag_length&3)return OP_ENOTFORMAT;
base64_sz=tag_length>>2;
buf_sz=3*base64_sz;
if(buf_sz<32)return OP_ENOTFORMAT;
if(_tag[tag_length-1]=='=')buf_sz--;
if(_tag[tag_length-2]=='=')buf_sz--;
if(buf_sz<32)return OP_ENOTFORMAT;
/*Allocate an extra byte to allow appending a terminating NUL to URL data.*/
buf=(unsigned char *)_ogg_malloc(sizeof(*buf)*(buf_sz+1));
if(buf==NULL)return OP_EFAULT;
opus_picture_tag_init(&pic);
ret=opus_picture_tag_parse_impl(&pic,_tag,buf,buf_sz,base64_sz);
if(ret<0){
opus_picture_tag_clear(&pic);
_ogg_free(buf);
}
else *_pic=*&pic;
return ret;
}
void opus_picture_tag_init(OpusPictureTag *_pic){
memset(_pic,0,sizeof(*_pic));
}
void opus_picture_tag_clear(OpusPictureTag *_pic){
_ogg_free(_pic->description);
_ogg_free(_pic->mime_type);
_ogg_free(_pic->data);
}
@@ -0,0 +1,42 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE libopusfile SOURCE CODE IS (C) COPYRIGHT 2012 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
* *
********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "internal.h"
#if defined(OP_ENABLE_ASSERTIONS)
void op_fatal_impl(const char *_str,const char *_file,int _line){
fprintf(stderr,"Fatal (internal) error in %s, line %i: %s\n",
_file,_line,_str);
abort();
}
#endif
/*A version of strncasecmp() that is guaranteed to only ignore the case of
ASCII characters.*/
int op_strncasecmp(const char *_a,const char *_b,int _n){
int i;
for(i=0;i<_n;i++){
int a;
int b;
int d;
a=_a[i];
b=_b[i];
if(a>='a'&&a<='z')a-='a'-'A';
if(b>='a'&&b<='z')b-='a'-'A';
d=a-b;
if(d)return d;
}
return 0;
}
@@ -0,0 +1,249 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE libopusfile SOURCE CODE IS (C) COPYRIGHT 2012 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
* *
********************************************************************/
#if !defined(_opusfile_internal_h)
# define _opusfile_internal_h (1)
# if !defined(_REENTRANT)
# define _REENTRANT
# endif
# if !defined(_GNU_SOURCE)
# define _GNU_SOURCE
# endif
# if !defined(_LARGEFILE_SOURCE)
# define _LARGEFILE_SOURCE
# endif
# if !defined(_LARGEFILE64_SOURCE)
# define _LARGEFILE64_SOURCE
# endif
# if !defined(_FILE_OFFSET_BITS)
# define _FILE_OFFSET_BITS 64
# endif
# include <stdlib.h>
# include "opusfile/opusfile.h"
typedef struct OggOpusLink OggOpusLink;
# if defined(OP_FIXED_POINT)
typedef opus_int16 op_sample;
# else
typedef float op_sample;
/*We're using this define to test for libopus 1.1 or later until libopus
provides a better mechanism.*/
# if defined(OPUS_GET_EXPERT_FRAME_DURATION_REQUEST)
/*Enable soft clipping prevention in 16-bit decodes.*/
# define OP_SOFT_CLIP (1)
# endif
# endif
# if OP_GNUC_PREREQ(4,2)
/*Disable excessive warnings about the order of operations.*/
# pragma GCC diagnostic ignored "-Wparentheses"
# elif defined(_MSC_VER)
/*Disable excessive warnings about the order of operations.*/
# pragma warning(disable:4554)
/*Disable warnings about "deprecated" POSIX functions.*/
# pragma warning(disable:4996)
# endif
# if OP_GNUC_PREREQ(3,0)
/*Another alternative is
(__builtin_constant_p(_x)?!!(_x):__builtin_expect(!!(_x),1))
but that evaluates _x multiple times, which may be bad.*/
# define OP_LIKELY(_x) (__builtin_expect(!!(_x),1))
# define OP_UNLIKELY(_x) (__builtin_expect(!!(_x),0))
# else
# define OP_LIKELY(_x) (!!(_x))
# define OP_UNLIKELY(_x) (!!(_x))
# endif
# if defined(OP_ENABLE_ASSERTIONS)
# if OP_GNUC_PREREQ(2,5)||__SUNPRO_C>=0x590
__attribute__((noreturn))
# endif
void op_fatal_impl(const char *_str,const char *_file,int _line);
# define OP_FATAL(_str) (op_fatal_impl(_str,__FILE__,__LINE__))
# define OP_ASSERT(_cond) \
do{ \
if(OP_UNLIKELY(!(_cond)))OP_FATAL("assertion failed: " #_cond); \
} \
while(0)
# define OP_ALWAYS_TRUE(_cond) OP_ASSERT(_cond)
# else
# define OP_FATAL(_str) abort()
# define OP_ASSERT(_cond)
# define OP_ALWAYS_TRUE(_cond) ((void)(_cond))
# endif
# define OP_INT64_MAX (2*(((ogg_int64_t)1<<62)-1)|1)
# define OP_INT64_MIN (-OP_INT64_MAX-1)
# define OP_INT32_MAX (2*(((ogg_int32_t)1<<30)-1)|1)
# define OP_INT32_MIN (-OP_INT32_MAX-1)
# define OP_MIN(_a,_b) ((_a)<(_b)?(_a):(_b))
# define OP_MAX(_a,_b) ((_a)>(_b)?(_a):(_b))
# define OP_CLAMP(_lo,_x,_hi) (OP_MAX(_lo,OP_MIN(_x,_hi)))
/*Advance a file offset by the given amount, clamping against OP_INT64_MAX.
This is used to advance a known offset by things like OP_CHUNK_SIZE or
OP_PAGE_SIZE_MAX, while making sure to avoid signed overflow.
It assumes that both _offset and _amount are non-negative.*/
#define OP_ADV_OFFSET(_offset,_amount) \
(OP_MIN(_offset,OP_INT64_MAX-(_amount))+(_amount))
/*The maximum channel count for any mapping we'll actually decode.*/
# define OP_NCHANNELS_MAX (8)
/*Initial state.*/
# define OP_NOTOPEN (0)
/*We've found the first Opus stream in the first link.*/
# define OP_PARTOPEN (1)
# define OP_OPENED (2)
/*We've found the first Opus stream in the current link.*/
# define OP_STREAMSET (3)
/*We've initialized the decoder for the chosen Opus stream in the current
link.*/
# define OP_INITSET (4)
/*Information cached for a single link in a chained Ogg Opus file.
We choose the first Opus stream encountered in each link to play back (and
require at least one).*/
struct OggOpusLink{
/*The byte offset of the first header page in this link.*/
opus_int64 offset;
/*The byte offset of the first data page from the chosen Opus stream in this
link (after the headers).*/
opus_int64 data_offset;
/*The byte offset of the last page from the chosen Opus stream in this link.
This is used when seeking to ensure we find a page before the last one, so
that end-trimming calculations work properly.
This is only valid for seekable sources.*/
opus_int64 end_offset;
/*The granule position of the last sample.
This is only valid for seekable sources.*/
ogg_int64_t pcm_end;
/*The granule position before the first sample.*/
ogg_int64_t pcm_start;
/*The serial number.*/
ogg_uint32_t serialno;
/*The contents of the info header.*/
OpusHead head;
/*The contents of the comment header.*/
OpusTags tags;
};
struct OggOpusFile{
/*The callbacks used to access the data source.*/
OpusFileCallbacks callbacks;
/*A FILE *, memory bufer, etc.*/
void *source;
/*Whether or not we can seek with this data source.*/
int seekable;
/*The number of links in this chained Ogg Opus file.*/
int nlinks;
/*The cached information from each link in a chained Ogg Opus file.
If source isn't seekable (e.g., it's a pipe), only the current link
appears.*/
OggOpusLink *links;
/*The number of serial numbers from a single link.*/
int nserialnos;
/*The capacity of the list of serial numbers from a single link.*/
int cserialnos;
/*Storage for the list of serial numbers from a single link.*/
ogg_uint32_t *serialnos;
/*This is the current offset of the data processed by the ogg_sync_state.
After a seek, this should be set to the target offset so that we can track
the byte offsets of subsequent pages.
After a call to op_get_next_page(), this will point to the first byte after
that page.*/
opus_int64 offset;
/*The total size of this data source, or -1 if it's unseekable.*/
opus_int64 end;
/*Used to locate pages in the data source.*/
ogg_sync_state oy;
/*One of OP_NOTOPEN, OP_PARTOPEN, OP_OPENED, OP_STREAMSET, OP_INITSET.*/
int ready_state;
/*The current link being played back.*/
int cur_link;
/*The number of decoded samples to discard from the start of decoding.*/
opus_int32 cur_discard_count;
/*The granule position of the previous packet (current packet start time).*/
ogg_int64_t prev_packet_gp;
/*The number of bytes read since the last bitrate query, including framing.*/
opus_int64 bytes_tracked;
/*The number of samples decoded since the last bitrate query.*/
ogg_int64_t samples_tracked;
/*Takes physical pages and welds them into a logical stream of packets.*/
ogg_stream_state os;
/*Re-timestamped packets from a single page.
Buffering these relies on the undocumented libogg behavior that ogg_packet
pointers remain valid until the next page is submitted to the
ogg_stream_state they came from.*/
ogg_packet op[255];
/*The index of the next packet to return.*/
int op_pos;
/*The total number of packets available.*/
int op_count;
/*Central working state for the packet-to-PCM decoder.*/
OpusMSDecoder *od;
/*The application-provided packet decode callback.*/
op_decode_cb_func decode_cb;
/*The application-provided packet decode callback context.*/
void *decode_cb_ctx;
/*The stream count used to initialize the decoder.*/
int od_stream_count;
/*The coupled stream count used to initialize the decoder.*/
int od_coupled_count;
/*The channel count used to initialize the decoder.*/
int od_channel_count;
/*The channel mapping used to initialize the decoder.*/
unsigned char od_mapping[OP_NCHANNELS_MAX];
/*The buffered data for one decoded packet.*/
op_sample *od_buffer;
/*The current position in the decoded buffer.*/
int od_buffer_pos;
/*The number of valid samples in the decoded buffer.*/
int od_buffer_size;
/*The type of gain offset to apply.
One of OP_HEADER_GAIN, OP_TRACK_GAIN, or OP_ABSOLUTE_GAIN.*/
int gain_type;
/*The offset to apply to the gain.*/
opus_int32 gain_offset_q8;
/*Internal state for soft clipping and dithering float->short output.*/
#if !defined(OP_FIXED_POINT)
# if defined(OP_SOFT_CLIP)
float clip_state[OP_NCHANNELS_MAX];
# endif
float dither_a[OP_NCHANNELS_MAX*4];
float dither_b[OP_NCHANNELS_MAX*4];
opus_uint32 dither_seed;
int dither_mute;
int dither_disabled;
/*The number of channels represented by the internal state.
This gets set to 0 whenever anything that would prevent state propagation
occurs (switching between the float/short APIs, or between the
stereo/multistream APIs).*/
int state_channel_count;
#endif
};
int op_strncasecmp(const char *_a,const char *_b,int _n);
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,366 @@
/********************************************************************
* *
* THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
* *
********************************************************************
function: stdio-based convenience library for opening/seeking/decoding
last mod: $Id: vorbisfile.c 17573 2010-10-27 14:53:59Z xiphmont $
********************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "internal.h"
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#if defined(_WIN32)
# include <io.h>
#endif
typedef struct OpusMemStream OpusMemStream;
#define OP_MEM_SIZE_MAX (~(size_t)0>>1)
#define OP_MEM_DIFF_MAX ((ptrdiff_t)OP_MEM_SIZE_MAX)
/*The context information needed to read from a block of memory as if it were a
file.*/
struct OpusMemStream{
/*The block of memory to read from.*/
const unsigned char *data;
/*The total size of the block.
This must be at most OP_MEM_SIZE_MAX to prevent signed overflow while
seeking.*/
ptrdiff_t size;
/*The current file position.
This is allowed to be set arbitrarily greater than size (i.e., past the end
of the block, though we will not read data past the end of the block), but
is not allowed to be negative (i.e., before the beginning of the block).*/
ptrdiff_t pos;
};
static int op_fread(void *_stream,unsigned char *_ptr,int _buf_size){
FILE *stream;
size_t ret;
/*Check for empty read.*/
if(_buf_size<=0)return 0;
stream=(FILE *)_stream;
ret=fread(_ptr,1,_buf_size,stream);
OP_ASSERT(ret<=(size_t)_buf_size);
/*If ret==0 and !feof(stream), there was a read error.*/
return ret>0||feof(stream)?(int)ret:OP_EREAD;
}
static int op_fseek(void *_stream,opus_int64 _offset,int _whence){
#if defined(_WIN32)
/*_fseeki64() is not exposed until MSCVCRT80.
This is the default starting with MSVC 2005 (_MSC_VER>=1400), but we want
to allow linking against older MSVCRT versions for compatibility back to
XP without installing extra runtime libraries.
i686-pc-mingw32 does not have fseeko() and requires
__MSVCRT_VERSION__>=0x800 for _fseeki64(), which screws up linking with
other libraries (that don't use MSVCRT80 from MSVC 2005 by default).
i686-w64-mingw32 does have fseeko() and respects _FILE_OFFSET_BITS, but I
don't know how to detect that at compile time.
We could just use fseeko64() (which is available in both), but its
implemented using fgetpos()/fsetpos() just like this code, except without
the overflow checking, so we prefer our version.*/
opus_int64 pos;
/*We don't use fpos_t directly because it might be a struct if __STDC__ is
non-zero or _INTEGRAL_MAX_BITS < 64.
I'm not certain when the latter is true, but someone could in theory set
the former.
Either way, it should be binary compatible with a normal 64-bit int (this
assumption is not portable, but I believe it is true for MSVCRT).*/
OP_ASSERT(sizeof(pos)==sizeof(fpos_t));
/*Translate the seek to an absolute one.*/
if(_whence==SEEK_CUR){
int ret;
ret=fgetpos((FILE *)_stream,(fpos_t *)&pos);
if(ret)return ret;
}
else if(_whence==SEEK_END)pos=_filelengthi64(_fileno((FILE *)_stream));
else if(_whence==SEEK_SET)pos=0;
else return -1;
/*Check for errors or overflow.*/
if(pos<0||_offset<-pos||_offset>OP_INT64_MAX-pos)return -1;
pos+=_offset;
return fsetpos((FILE *)_stream,(fpos_t *)&pos);
#else
/*This function actually conforms to the SUSv2 and POSIX.1-2001, so we prefer
it except on Windows.*/
return fseeko((FILE *)_stream,(off_t)_offset,_whence);
#endif
}
static opus_int64 op_ftell(void *_stream){
#if defined(_WIN32)
/*_ftelli64() is not exposed until MSCVCRT80, and ftello()/ftello64() have
the same problems as fseeko()/fseeko64() in MingW.
See above for a more detailed explanation.*/
opus_int64 pos;
OP_ASSERT(sizeof(pos)==sizeof(fpos_t));
return fgetpos((FILE *)_stream,(fpos_t *)&pos)?-1:pos;
#else
/*This function actually conforms to the SUSv2 and POSIX.1-2001, so we prefer
it except on Windows.*/
return ftello((FILE *)_stream);
#endif
}
static const OpusFileCallbacks OP_FILE_CALLBACKS={
op_fread,
op_fseek,
op_ftell,
(op_close_func)fclose
};
#if defined(_WIN32)
# include <stddef.h>
# include <errno.h>
/*Windows doesn't accept UTF-8 by default, and we don't have a wchar_t API,
so if we just pass the path to fopen(), then there'd be no way for a user
of our API to open a Unicode filename.
Instead, we translate from UTF-8 to UTF-16 and use Windows' wchar_t API.
This makes this API more consistent with platforms where the character set
used by fopen is the same as used on disk, which is generally UTF-8, and
with our metadata API, which always uses UTF-8.*/
static wchar_t *op_utf8_to_utf16(const char *_src){
wchar_t *dst;
size_t len;
len=strlen(_src);
/*Worst-case output is 1 wide character per 1 input character.*/
dst=(wchar_t *)_ogg_malloc(sizeof(*dst)*(len+1));
if(dst!=NULL){
size_t si;
size_t di;
for(di=si=0;si<len;si++){
int c0;
c0=(unsigned char)_src[si];
if(!(c0&0x80)){
/*Start byte says this is a 1-byte sequence.*/
dst[di++]=(wchar_t)c0;
continue;
}
else{
int c1;
/*This is safe, because c0 was not 0 and _src is NUL-terminated.*/
c1=(unsigned char)_src[si+1];
if((c1&0xC0)==0x80){
/*Found at least one continuation byte.*/
if((c0&0xE0)==0xC0){
wchar_t w;
/*Start byte says this is a 2-byte sequence.*/
w=(c0&0x1F)<<6|c1&0x3F;
if(w>=0x80U){
/*This is a 2-byte sequence that is not overlong.*/
dst[di++]=w;
si++;
continue;
}
}
else{
int c2;
/*This is safe, because c1 was not 0 and _src is NUL-terminated.*/
c2=(unsigned char)_src[si+2];
if((c2&0xC0)==0x80){
/*Found at least two continuation bytes.*/
if((c0&0xF0)==0xE0){
wchar_t w;
/*Start byte says this is a 3-byte sequence.*/
w=(c0&0xF)<<12|(c1&0x3F)<<6|c2&0x3F;
if(w>=0x800U&&(w<0xD800||w>=0xE000)&&w<0xFFFE){
/*This is a 3-byte sequence that is not overlong, not a
UTF-16 surrogate pair value, and not a 'not a character'
value.*/
dst[di++]=w;
si+=2;
continue;
}
}
else{
int c3;
/*This is safe, because c2 was not 0 and _src is
NUL-terminated.*/
c3=(unsigned char)_src[si+3];
if((c3&0xC0)==0x80){
/*Found at least three continuation bytes.*/
if((c0&0xF8)==0xF0){
opus_uint32 w;
/*Start byte says this is a 4-byte sequence.*/
w=(c0&7)<<18|(c1&0x3F)<<12|(c2&0x3F)<<6&(c3&0x3F);
if(w>=0x10000U&&w<0x110000U){
/*This is a 4-byte sequence that is not overlong and not
greater than the largest valid Unicode code point.
Convert it to a surrogate pair.*/
w-=0x10000;
dst[di++]=(wchar_t)(0xD800+(w>>10));
dst[di++]=(wchar_t)(0xDC00+(w&0x3FF));
si+=3;
continue;
}
}
}
}
}
}
}
}
/*If we got here, we encountered an illegal UTF-8 sequence.*/
_ogg_free(dst);
return NULL;
}
OP_ASSERT(di<=len);
dst[di]='\0';
}
return dst;
}
#endif
void *op_fopen(OpusFileCallbacks *_cb,const char *_path,const char *_mode){
FILE *fp;
#if !defined(_WIN32)
fp=fopen(_path,_mode);
#else
fp=NULL;
if(_path==NULL||_mode==NULL)errno=EINVAL;
else{
wchar_t *wpath;
wchar_t *wmode;
wpath=op_utf8_to_utf16(_path);
wmode=op_utf8_to_utf16(_mode);
if(wmode==NULL)errno=EINVAL;
else if(wpath==NULL)errno=ENOENT;
else fp=_wfopen(wpath,wmode);
_ogg_free(wmode);
_ogg_free(wpath);
}
#endif
if(fp!=NULL)*_cb=*&OP_FILE_CALLBACKS;
return fp;
}
void *op_fdopen(OpusFileCallbacks *_cb,int _fd,const char *_mode){
FILE *fp;
fp=fdopen(_fd,_mode);
if(fp!=NULL)*_cb=*&OP_FILE_CALLBACKS;
return fp;
}
void *op_freopen(OpusFileCallbacks *_cb,const char *_path,const char *_mode,
void *_stream){
FILE *fp;
#if !defined(_WIN32)
fp=freopen(_path,_mode,(FILE *)_stream);
#else
fp=NULL;
if(_path==NULL||_mode==NULL)errno=EINVAL;
else{
wchar_t *wpath;
wchar_t *wmode;
wpath=op_utf8_to_utf16(_path);
wmode=op_utf8_to_utf16(_mode);
if(wmode==NULL)errno=EINVAL;
else if(wpath==NULL)errno=ENOENT;
else fp=_wfreopen(wpath,wmode,(FILE *)_stream);
_ogg_free(wmode);
_ogg_free(wpath);
}
#endif
if(fp!=NULL)*_cb=*&OP_FILE_CALLBACKS;
return fp;
}
static int op_mem_read(void *_stream,unsigned char *_ptr,int _buf_size){
OpusMemStream *stream;
ptrdiff_t size;
ptrdiff_t pos;
stream=(OpusMemStream *)_stream;
/*Check for empty read.*/
if(_buf_size<=0)return 0;
size=stream->size;
pos=stream->pos;
/*Check for EOF.*/
if(pos>=size)return 0;
/*Check for a short read.*/
_buf_size=(int)OP_MIN(size-pos,_buf_size);
memcpy(_ptr,stream->data+pos,_buf_size);
pos+=_buf_size;
stream->pos=pos;
return _buf_size;
}
static int op_mem_seek(void *_stream,opus_int64 _offset,int _whence){
OpusMemStream *stream;
ptrdiff_t pos;
stream=(OpusMemStream *)_stream;
pos=stream->pos;
OP_ASSERT(pos>=0);
switch(_whence){
case SEEK_SET:{
/*Check for overflow:*/
if(_offset<0||_offset>OP_MEM_DIFF_MAX)return -1;
pos=(ptrdiff_t)_offset;
}break;
case SEEK_CUR:{
/*Check for overflow:*/
if(_offset<-pos||_offset>OP_MEM_DIFF_MAX-pos)return -1;
pos=(ptrdiff_t)(pos+_offset);
}break;
case SEEK_END:{
ptrdiff_t size;
size=stream->size;
OP_ASSERT(size>=0);
/*Check for overflow:*/
if(_offset>size||_offset<size-OP_MEM_DIFF_MAX)return -1;
pos=(ptrdiff_t)(size-_offset);
}break;
default:return -1;
}
stream->pos=pos;
return 0;
}
static opus_int64 op_mem_tell(void *_stream){
OpusMemStream *stream;
stream=(OpusMemStream *)_stream;
return (ogg_int64_t)stream->pos;
}
static int op_mem_close(void *_stream){
_ogg_free(_stream);
return 0;
}
static const OpusFileCallbacks OP_MEM_CALLBACKS={
op_mem_read,
op_mem_seek,
op_mem_tell,
op_mem_close
};
void *op_mem_stream_create(OpusFileCallbacks *_cb,
const unsigned char *_data,size_t _size){
OpusMemStream *stream;
if(_size>OP_MEM_SIZE_MAX)return NULL;
stream=(OpusMemStream *)_ogg_malloc(sizeof(*stream));
if(stream!=NULL){
*_cb=*&OP_MEM_CALLBACKS;
stream->data=_data;
stream->size=_size;
stream->pos=0;
}
return stream;
}